Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 968892d811 | |||
| a3a9444c3b | |||
| e1006c63de | |||
| 21981eb946 | |||
| ac4f2653af | |||
| 51727e419a | |||
| b791f7be68 | |||
| 334b83c973 | |||
| 6ea4a2e0f9 | |||
| ec5d7e2efe | |||
| 737191c170 | |||
| f199eda322 | |||
| 9161e0901f | |||
| 5460c7f676 | |||
| 2a9f6f5628 | |||
| 58dbb7ef3e | |||
| 75b82024de | |||
| 4af1ad8848 | |||
| 164153dc9c | |||
| ac0672bc11 | |||
| 24dd3acd09 | |||
| 4efe7cef58 | |||
| 2dab20f718 | |||
| be298777af | |||
| 45a671940b | |||
| 601971d43d | |||
| c9bce7c976 | |||
| 614747ffca | |||
| 931cc0d1d9 | |||
| b6b4f8c360 | |||
| ff81d80cf9 | |||
| 01000757f3 | |||
| d75dec2a50 | |||
| a45f78217c | |||
| d3761183c3 | |||
| 5d07770ce2 | |||
| 91bdc12e78 |
@@ -45,6 +45,7 @@ from .errors import (
|
|||||||
Cafe24AuthError,
|
Cafe24AuthError,
|
||||||
Cafe24ConfigError,
|
Cafe24ConfigError,
|
||||||
Cafe24Error,
|
Cafe24Error,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
Cafe24RateLimitError,
|
Cafe24RateLimitError,
|
||||||
)
|
)
|
||||||
@@ -80,6 +81,7 @@ __all__ = [
|
|||||||
"Cafe24RateLimitError",
|
"Cafe24RateLimitError",
|
||||||
"Cafe24ApiError",
|
"Cafe24ApiError",
|
||||||
"Cafe24FtpError",
|
"Cafe24FtpError",
|
||||||
|
"Cafe24FtpConflict",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -164,6 +164,10 @@ class Cafe24Client:
|
|||||||
method = method.upper()
|
method = method.upper()
|
||||||
forced_refresh = False
|
forced_refresh = False
|
||||||
last_error: Exception | None = None
|
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):
|
for attempt in range(self._max_retries + 1):
|
||||||
self._pace()
|
self._pace()
|
||||||
@@ -224,7 +228,9 @@ class Cafe24Client:
|
|||||||
time.sleep(wait)
|
time.sleep(wait)
|
||||||
continue
|
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:
|
if error.retryable and attempt < self._max_retries:
|
||||||
last_error = error
|
last_error = error
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
@@ -241,7 +247,11 @@ class Cafe24Client:
|
|||||||
http_status=status, result="ERROR", error_message=message,
|
http_status=status, result="ERROR", error_message=message,
|
||||||
duration_ms=elapsed,
|
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:
|
if attempt < self._max_retries:
|
||||||
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
time.sleep(min(8.0, 0.5 * (2**attempt)))
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -7,15 +7,28 @@ Admin API(OAuth)로는 스킨 파일을 다루지 못한다(`config.py` 상단
|
|||||||
|
|
||||||
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
실물 확인(스크린샷): 호스트 `{mall_id}.ftp.cafe24.com`, 포트 21, SSL/TLS 미사용
|
||||||
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
(평문 FTP). 파일은 텍스트(UTF-8)로 다룬다.
|
||||||
|
|
||||||
|
쓰기는 원본에 직접 STOR 하지 않는다 (write_text_file)
|
||||||
|
직접 STOR 는 전송 도중 끊기면 원본이 **앞부분만 남은 채** 잘린다(스킨 템플릿이면
|
||||||
|
모든 상품 페이지가 깨진다). 그래서
|
||||||
|
1) 같은 폴더의 임시 파일에 올리고 (원본은 아직 그대로)
|
||||||
|
2) 다시 받아 바이트 단위로 검증하고
|
||||||
|
3) 교체 직전 원본을 다시 읽어 편집 시작 값과 같은지 확인하고(충돌 방지)
|
||||||
|
4) RNFR/RNTO 로 이름을 바꿔 교체한다
|
||||||
|
서버가 "이미 있는 이름으로 바꾸기"를 거부하면 원본을 옆 이름으로 비킨 뒤 교체하고,
|
||||||
|
실패하면 원본을 제자리로 되돌린다. 이름 바꾸기 자체를 지원하지 않으면 **중단**한다
|
||||||
|
(직접 STOR 로 물러서지 않는다).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ftplib
|
import ftplib
|
||||||
import io
|
import io
|
||||||
|
import posixpath
|
||||||
|
import uuid
|
||||||
|
|
||||||
from .config import Cafe24FtpConfig
|
from .config import Cafe24FtpConfig
|
||||||
from .errors import Cafe24FtpError
|
from .errors import Cafe24FtpConflict, Cafe24FtpError
|
||||||
|
|
||||||
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
# 응답이 없을 때 무한 대기하지 않도록 — 관리 화면 요청 안에서 동기 호출되므로
|
||||||
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
# 너무 길면 안 되지만, 파일 하나(수십 KB) 전송에는 충분히 넉넉해야 한다.
|
||||||
@@ -35,37 +48,135 @@ def _connect(config: Cafe24FtpConfig) -> ftplib.FTP:
|
|||||||
raise Cafe24FtpError(f"FTP 연결/로그인에 실패했습니다: {exc}") from exc
|
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:
|
def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
|
||||||
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
"""디자인 보관함의 파일 1개를 읽어 텍스트로 돌려준다."""
|
||||||
ftp = _connect(config)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO()
|
|
||||||
try:
|
try:
|
||||||
ftp.retrbinary(f"RETR {path}", buf.write)
|
raw = _retr(ftp, path)
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일을 읽지 못했습니다({path}): {exc}") from exc
|
||||||
try:
|
try:
|
||||||
return buf.getvalue().decode("utf-8")
|
return raw.decode("utf-8")
|
||||||
except UnicodeDecodeError as exc:
|
except UnicodeDecodeError as exc:
|
||||||
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
raise Cafe24FtpError(f"파일 인코딩을 UTF-8로 해석하지 못했습니다({path}): {exc}") from exc
|
||||||
finally:
|
finally:
|
||||||
try:
|
_close(ftp)
|
||||||
ftp.quit()
|
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
|
||||||
ftp.close()
|
|
||||||
|
|
||||||
|
|
||||||
def write_text_file(config: Cafe24FtpConfig, path: str, content: str) -> None:
|
def temp_names(path: str, tag: str) -> tuple[str, str]:
|
||||||
"""디자인 보관함의 파일 1개를 통째로 덮어쓴다."""
|
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식."""
|
||||||
|
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)
|
ftp = _connect(config)
|
||||||
try:
|
try:
|
||||||
buf = io.BytesIO(content.encode("utf-8"))
|
# 1) 임시 파일에 올린다 — 원본은 아직 그대로다.
|
||||||
try:
|
try:
|
||||||
ftp.storbinary(f"STOR {path}", buf)
|
ftp.storbinary(f"STOR {tmp}", io.BytesIO(data))
|
||||||
except ftplib.all_errors as exc:
|
except ftplib.all_errors as exc:
|
||||||
raise Cafe24FtpError(f"파일을 쓰지 못했습니다({path}): {exc}") from exc
|
_delete_quiet(ftp, tmp)
|
||||||
finally:
|
raise Cafe24FtpError(f"임시 파일을 올리지 못했습니다 — 원본은 그대로입니다({path}): {exc}") from exc
|
||||||
|
|
||||||
|
# 2) 검증 — 다시 받아 바이트 단위로 비교한다(전송이 잘렸으면 여기서 잡힌다).
|
||||||
try:
|
try:
|
||||||
ftp.quit()
|
uploaded = _retr(ftp, tmp)
|
||||||
except Exception: # noqa: BLE001 — 정리 실패는 무시
|
except ftplib.all_errors as exc:
|
||||||
ftp.close()
|
_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):
|
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):
|
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)
|
super().__init__(message)
|
||||||
self.status = status
|
self.status = status
|
||||||
self.endpoint = endpoint
|
self.endpoint = endpoint
|
||||||
|
self.maybe_applied = maybe_applied
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def retryable(self) -> bool:
|
def retryable(self) -> bool:
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from dataclasses import dataclass
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .client import Cafe24Client
|
from .client import Cafe24Client
|
||||||
|
from .errors import Cafe24Error
|
||||||
|
|
||||||
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
# 카페24 상품 목록 API 의 1회 최대 조회 수
|
||||||
PAGE_LIMIT = 100
|
PAGE_LIMIT = 100
|
||||||
@@ -476,26 +477,55 @@ def wait_for_variants(
|
|||||||
return latest
|
return latest
|
||||||
|
|
||||||
|
|
||||||
|
VARIANT_CHUNK = 100 # 카페24 문서상 PUT variants 1회 최대 건수
|
||||||
|
|
||||||
|
# update_variants 행별 결과 상태
|
||||||
|
VARIANT_OK = "ok" # 카페24가 받아들임
|
||||||
|
VARIANT_FAILED = "failed" # 거절 — 반영되지 않음이 확실
|
||||||
|
VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을 못 받음 — 반영 여부 모름
|
||||||
|
|
||||||
|
|
||||||
def update_variants(
|
def update_variants(
|
||||||
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
|
||||||
) -> 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)
|
no = int(product_no)
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
for start in range(0, len(requests), 100):
|
for start in range(0, len(requests), VARIANT_CHUNK):
|
||||||
chunk = requests[start : start + 100]
|
chunk = requests[start : start + VARIANT_CHUNK]
|
||||||
if not chunk:
|
if not chunk:
|
||||||
continue
|
continue
|
||||||
payload = client.put(
|
try:
|
||||||
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
|
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
|
result = payload.get("variants") if isinstance(payload, dict) else None
|
||||||
|
returned: list[dict[str, Any]] = []
|
||||||
if isinstance(result, list):
|
if isinstance(result, list):
|
||||||
out.extend(result)
|
returned = [r for r in result if isinstance(r, dict)]
|
||||||
elif isinstance(result, dict):
|
elif isinstance(result, dict):
|
||||||
out.append(result)
|
returned = [result]
|
||||||
elif isinstance(payload.get("variant"), dict):
|
elif isinstance(payload, dict) and isinstance(payload.get("variant"), dict):
|
||||||
out.append(payload["variant"])
|
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
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -376,7 +376,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"key": "project",
|
"key": "project",
|
||||||
"title": "프로젝트 관리",
|
"title": "Project",
|
||||||
"subtitle": "Projects",
|
"subtitle": "Projects",
|
||||||
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
|
||||||
"url": "/project/",
|
"url": "/project/",
|
||||||
|
|||||||
+503
-96
@@ -14,10 +14,12 @@ API 로그에는 토큰/시크릿을 넣지 않는다.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Any, Iterator
|
from typing import Any, Iterator
|
||||||
|
|
||||||
|
from psycopg import errors as pg_errors
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg_pool import ConnectionPool
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
@@ -97,6 +99,315 @@ class Cafe24Store:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
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개 메서드
|
# OAuth 토큰 — app/integrations/cafe24/tokens.py 가 요구하는 3개 메서드
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -281,31 +592,38 @@ class Cafe24Store:
|
|||||||
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
# 마이그레이션 004 의 두 컬럼(last_write_snapshot, last_written_at)을 쓴다.
|
||||||
# 스냅샷 JSON 모양:
|
# 스냅샷 JSON 모양:
|
||||||
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
# {"product": {"data": {...store.SNAPSHOT_FIELDS...}, "written_at": ISO},
|
||||||
# "options": {"data": {...GET/PUT options 응답...}, "written_at": ISO},
|
# "options": {"data": {...GET/PUT options 응답..., "_before_signature", "_recent_values"},
|
||||||
# "variants": {"data": {variant_code: {...}}, "written_at": ISO}}
|
# "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
|
from psycopg.types.json import Jsonb # noqa: WPS433
|
||||||
|
|
||||||
no = int(product_no)
|
no = int(product_no)
|
||||||
if no <= 0 or section not in ("product", "options", "variants"):
|
if no <= 0 or section not in ("product", "options", "variants"):
|
||||||
return
|
return
|
||||||
|
now_iso = datetime.now(KST).isoformat(timespec="seconds")
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
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(
|
row = conn.execute(
|
||||||
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
"SELECT last_write_snapshot FROM cafe24_products WHERE product_no = %s FOR UPDATE",
|
||||||
(no,),
|
(no,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
current = dict(row["last_write_snapshot"]) if row and row.get("last_write_snapshot") else {}
|
||||||
if section == "variants" and isinstance(data, dict):
|
if section == "variants":
|
||||||
# 품목은 코드별로 누적 병합 — 일부만 바꿔도 이전에 바꾼 것을 잃지 않게.
|
previous = (current.get("variants") or {}).get("data") or {}
|
||||||
merged = dict((current.get("variants") or {}).get("data") or {})
|
data = store.merge_variant_snapshot(
|
||||||
merged.update(data)
|
previous, data if isinstance(data, dict) else {}, at=now_iso, replace=replace
|
||||||
data = merged
|
)
|
||||||
current[section] = {
|
current[section] = {"data": data, "written_at": now_iso}
|
||||||
"data": data,
|
|
||||||
"written_at": datetime.now(KST).isoformat(timespec="seconds"),
|
|
||||||
}
|
|
||||||
product = data if section == "product" and isinstance(data, dict) else {}
|
product = data if section == "product" and isinstance(data, dict) else {}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
@@ -345,51 +663,14 @@ class Cafe24Store:
|
|||||||
return {}
|
return {}
|
||||||
return dict(row["last_write_snapshot"])
|
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 하지 않는다)
|
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
|
||||||
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
|
||||||
|
# 읽기 지연 판정은 이 표가 아니라 cafe24_write_attempts(확인된 쓰기)를 본다 —
|
||||||
|
# 여기에는 충돌로 거절된 적용의 백업·예약 초안처럼 카페24에 올라간 적 없는 값도
|
||||||
|
# 들어 있기 때문이다(write_lineage 참고).
|
||||||
|
# 메타데이터(마이그레이션 005): mall_id·shop_no(복원 시 일치 검사), source
|
||||||
|
# (BACKUP 이 카페24 관측값인지, 지연 중이라 마지막 확인된 쓰기인지), source_revision_id.
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
def add_revision(
|
def add_revision(
|
||||||
self,
|
self,
|
||||||
@@ -399,13 +680,18 @@ class Cafe24Store:
|
|||||||
revision_type: str,
|
revision_type: str,
|
||||||
memo: str = "",
|
memo: str = "",
|
||||||
created_by: str = "",
|
created_by: str = "",
|
||||||
|
mall_id: str = "",
|
||||||
|
shop_no: int = 1,
|
||||||
|
source: str = "",
|
||||||
|
source_revision_id: int | None = None,
|
||||||
) -> int:
|
) -> int:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO cafe24_product_revisions
|
INSERT INTO cafe24_product_revisions
|
||||||
(product_no, html_content, revision_type, memo, created_by)
|
(product_no, html_content, revision_type, memo, created_by,
|
||||||
VALUES (%s,%s,%s,%s,%s)
|
mall_id, shop_no, source, source_revision_id)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
RETURNING id
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(
|
||||||
@@ -414,24 +700,33 @@ class Cafe24Store:
|
|||||||
store.normalize_revision_type(revision_type),
|
store.normalize_revision_type(revision_type),
|
||||||
(memo or "")[:500],
|
(memo or "")[:500],
|
||||||
created_by or "",
|
created_by or "",
|
||||||
|
mall_id or "",
|
||||||
|
int(shop_no or 1),
|
||||||
|
source or "",
|
||||||
|
source_revision_id,
|
||||||
),
|
),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
return int(row["id"]) if row else 0
|
return int(row["id"]) if row else 0
|
||||||
|
|
||||||
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
def list_revisions(self, product_no: int, *, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다."""
|
"""버전 목록. html_content 는 수 MB 일 수 있어 길이만 계산해서 준다.
|
||||||
with self._pool.connection() as conn:
|
|
||||||
rows = conn.execute(
|
005 적용 전이면 출처(source) 없이 돌려준다(읽기 경로는 막지 않는다)."""
|
||||||
"""
|
sql = """
|
||||||
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
SELECT id, product_no, revision_type, memo, created_by, created_at,
|
||||||
length(html_content) AS html_length
|
length(html_content) AS html_length{extra}
|
||||||
FROM cafe24_product_revisions
|
FROM cafe24_product_revisions
|
||||||
WHERE product_no = %s
|
WHERE product_no = %s
|
||||||
ORDER BY created_at DESC, id DESC
|
ORDER BY created_at DESC, id DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""",
|
"""
|
||||||
(int(product_no), max(1, min(int(limit), 200))),
|
args = (int(product_no), max(1, min(int(limit), 200)))
|
||||||
).fetchall()
|
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]
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
def get_revision(self, revision_id: int) -> dict[str, Any]:
|
||||||
@@ -568,18 +863,24 @@ class Cafe24Store:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@contextmanager
|
# ── 예약 실행 lease (마이그레이션 005) ──
|
||||||
def claim_due_schedule(self, *, now: datetime) -> Iterator[dict[str, Any] | None]:
|
# PROCESSING 은 lease_expires_at 까지만 유효하다. worker 가 죽으면 만료 후
|
||||||
"""실행할 예약 1건을 잡아 PROCESSING 으로 바꾼다(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 가 여러 개 떠 있어도 같은 예약을
|
`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 self._pool.connection() as conn:
|
||||||
with conn.transaction():
|
with conn.transaction():
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM cafe24_product_schedules
|
SELECT id FROM cafe24_product_schedules
|
||||||
WHERE status = 'PENDING'
|
WHERE status = 'PENDING'
|
||||||
AND scheduled_at <= %s
|
AND scheduled_at <= %s
|
||||||
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
AND (next_retry_at IS NULL OR next_retry_at <= %s)
|
||||||
@@ -589,48 +890,154 @@ class Cafe24Store:
|
|||||||
""",
|
""",
|
||||||
(now, now),
|
(now, now),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if row is not None:
|
if row is None:
|
||||||
conn.execute(
|
return None
|
||||||
"""
|
claimed = conn.execute(
|
||||||
UPDATE cafe24_product_schedules
|
"""
|
||||||
SET status = 'PROCESSING', started_at = now(), last_error = ''
|
UPDATE cafe24_product_schedules
|
||||||
WHERE id = %s
|
SET status = 'PROCESSING', started_at = now(), last_error = '',
|
||||||
""",
|
lease_owner = %s, lease_token = %s,
|
||||||
(row["id"],),
|
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(
|
def finish_schedule(
|
||||||
self,
|
self,
|
||||||
schedule_id: int,
|
schedule_id: int,
|
||||||
*,
|
*,
|
||||||
|
token: str,
|
||||||
status: str,
|
status: str,
|
||||||
error: str = "",
|
error: str = "",
|
||||||
next_retry_at: datetime | None = None,
|
next_retry_at: datetime | None = None,
|
||||||
retry_count: int | None = None,
|
retry_count: int | None = None,
|
||||||
) -> None:
|
) -> bool:
|
||||||
"""예약 종료 처리. 재시도로 되돌릴 때는 status='PENDING' + next_retry_at."""
|
"""예약 종료 처리(lease 가 내 것일 때만). 재시도로 되돌릴 때는 status='PENDING' + next_retry_at.
|
||||||
|
|
||||||
|
반환: 반영했으면 True. lease 를 잃었으면 False(다른 worker 가 복구 중 — 덮지 않는다).
|
||||||
|
"""
|
||||||
|
normalized = store.normalize_schedule_status(status)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
conn.execute(
|
row = conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE cafe24_product_schedules
|
UPDATE cafe24_product_schedules
|
||||||
SET status = %s,
|
SET status = %s,
|
||||||
last_error = %s,
|
last_error = %s,
|
||||||
next_retry_at = %s,
|
next_retry_at = %s,
|
||||||
retry_count = COALESCE(%s, retry_count),
|
retry_count = COALESCE(%s, retry_count),
|
||||||
|
lease_owner = '', lease_token = '', lease_expires_at = NULL,
|
||||||
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
completed_at = CASE WHEN %s IN ('SUCCESS','FAILED','CANCELLED')
|
||||||
THEN now() ELSE completed_at END
|
THEN now() ELSE completed_at END
|
||||||
WHERE id = %s
|
WHERE id = %s AND status = 'PROCESSING' AND lease_token = %s
|
||||||
|
RETURNING id
|
||||||
""",
|
""",
|
||||||
(
|
(normalized, (error or "")[:1000], next_retry_at, retry_count, normalized,
|
||||||
store.normalize_schedule_status(status),
|
int(schedule_id), token),
|
||||||
(error or "")[:1000],
|
).fetchone()
|
||||||
next_retry_at,
|
return row is not None
|
||||||
retry_count,
|
|
||||||
store.normalize_schedule_status(status),
|
def get_schedule(self, schedule_id: int) -> dict[str, Any]:
|
||||||
int(schedule_id),
|
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 (다른 모듈과 동일)
|
# 직렬화 — datetime → KST ISO, date → ISO (다른 모듈과 동일)
|
||||||
|
|||||||
@@ -13,8 +13,11 @@
|
|||||||
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
다른 데이터를 다루지만, 여기는 파일마다 경로만 다르고 나머지는 동일하다).
|
||||||
|
|
||||||
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
쓰기 순서는 상세페이지 적용과 동일한 원칙을 따른다:
|
||||||
FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
파일별 DB 잠금(writes.write_lock, 'design:{file_key}')
|
||||||
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부) → FTP 에 쓴다
|
→ FTP 에서 현재 내용을 다시 읽는다(로컬 값을 현재값으로 가정하지 않는다)
|
||||||
|
→ BACKUP 버전 저장 → 지문 대조(충돌 시 거부)
|
||||||
|
→ 임시 파일 업로드·검증 → 교체 직전 원본 재확인 → 이름 바꾸기로 교체
|
||||||
|
(design_ftp.write_text_file — 원본에 직접 STOR 하지 않는다)
|
||||||
→ MANUAL 버전 + 감사로그
|
→ MANUAL 버전 + 감사로그
|
||||||
|
|
||||||
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
핸들러는 `async def` 가 아니라 `def`(동기)다 — FTP 호출이 블로킹이므로
|
||||||
@@ -24,12 +27,14 @@ FastAPI 스레드풀에서 돌게 둔다(다른 cafe24 라우트와 동일한
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, HTTPException, Request
|
from fastapi import APIRouter, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||||
|
|
||||||
from app.integrations.cafe24 import (
|
from app.integrations.cafe24 import (
|
||||||
DESIGN_FILE_SPECS,
|
DESIGN_FILE_SPECS,
|
||||||
|
Cafe24FtpConflict,
|
||||||
Cafe24FtpError,
|
Cafe24FtpError,
|
||||||
design_file_label,
|
design_file_label,
|
||||||
design_file_path,
|
design_file_path,
|
||||||
@@ -38,7 +43,7 @@ from app.integrations.cafe24 import (
|
|||||||
load_ftp_config,
|
load_ftp_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import base_ctx, guard
|
from .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_products import _no_store
|
||||||
|
|
||||||
@@ -128,74 +133,76 @@ def design_file_apply(
|
|||||||
st, user = checked
|
st, user = checked
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
back = f"/cafe24/design/{file_key}"
|
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)
|
path = design_file_path(file_key)
|
||||||
ftp_config = _ftp_config()
|
ftp_config = _ftp_config()
|
||||||
if not ftp_config.configured:
|
if not ftp_config.configured:
|
||||||
return RedirectResponse(
|
return go(err="FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing))
|
||||||
url=f"{back}?err=" + "FTP 설정이 필요합니다: " + ", ".join(ftp_config.missing),
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
# 브라우저 textarea 는 줄바꿈을 CRLF 로 보낸다 — 그대로 저장하면 실제 수정이
|
||||||
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
# 없어도 매번 파일 전체의 줄바꿈이 바뀌어(지문 비교·"변경 없음" 판정이 어긋난다).
|
||||||
submitted = content.replace("\r\n", "\n")
|
submitted = content.replace("\r\n", "\n")
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return go(err="내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.")
|
||||||
url=f"{back}?err=" + "내용이 비어 있습니다. 파일을 비우려면 FTP 로 직접 하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# 같은 파일을 두 사람이 동시에 적용하지 못하게 파일별 DB 잠금 안에서 한다.
|
||||||
try:
|
try:
|
||||||
current = design_ftp.read_text_file(ftp_config, path)
|
with writes.write_lock(st, writes.design_lock_key(file_key), actor=actor, purpose=f"{file_key} 적용"):
|
||||||
except Cafe24FtpError as exc:
|
try:
|
||||||
st.log_audit(
|
current = design_ftp.read_text_file(ftp_config, path)
|
||||||
actor=actor, action=f"apply_design:{file_key}", result="FAIL",
|
except Cafe24FtpError as exc:
|
||||||
detail=f"현재값 조회 실패: {exc}",
|
writes.audit_safe(st, actor=actor, action=action, result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
)
|
return go(err=f"현재 파일을 읽지 못해 중단했습니다: {exc}")
|
||||||
return RedirectResponse(url=f"{back}?err=현재 파일을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
|
||||||
|
|
||||||
backup_id = st.add_design_revision(
|
backup_id = st.add_design_revision(
|
||||||
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
file_key=file_key, content=current, revision_type=store.REVISION_BACKUP,
|
||||||
memo="적용 직전 자동 백업", created_by=actor,
|
memo="적용 직전 자동 백업", created_by=actor,
|
||||||
)
|
)
|
||||||
|
|
||||||
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
if base_fingerprint and base_fingerprint != store.fingerprint(current):
|
||||||
st.log_audit(
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨")
|
||||||
result="FAIL", detail="충돌 — 편집 중 파일이 변경됨",
|
return go(err="편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.")
|
||||||
)
|
|
||||||
return RedirectResponse(
|
|
||||||
url=f"{back}?err=편집하는 동안 파일이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|
||||||
if submitted == current:
|
if submitted == current:
|
||||||
return RedirectResponse(url=f"{back}?msg=변경된 내용이 없어 적용하지 않았습니다.", status_code=303)
|
return go(msg="변경된 내용이 없어 적용하지 않았습니다.")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
design_ftp.write_text_file(ftp_config, path, submitted)
|
# 임시 파일 업로드 → 검증 → 교체 직전 원본 재확인(current 와 같아야) → 이름 바꾸기.
|
||||||
except Cafe24FtpError as exc:
|
design_ftp.write_text_file(ftp_config, path, submitted, expected_current=current)
|
||||||
st.log_audit(
|
except Cafe24FtpConflict as exc:
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=backup_id,
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
result="FAIL", detail=str(exc),
|
result="FAIL", detail=f"충돌 — 교체 직전 파일이 변경됨: {exc}")
|
||||||
)
|
return go(err=f"{exc} (직전 내용은 버전 {backup_id} 로 보관됨)")
|
||||||
logger.warning("디자인 파일 적용 실패(%s): %s", file_key, exc)
|
except Cafe24FtpError as exc:
|
||||||
return RedirectResponse(
|
maybe = bool(getattr(exc, "maybe_applied", False))
|
||||||
url=f"{back}?err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
writes.audit_safe(st, actor=actor, action=action, revision_id=backup_id,
|
||||||
status_code=303,
|
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,
|
record_note = ""
|
||||||
memo=memo, created_by=actor,
|
try:
|
||||||
)
|
revision_id = st.add_design_revision(
|
||||||
st.log_audit(
|
file_key=file_key, content=submitted, revision_type=store.REVISION_MANUAL,
|
||||||
actor=actor, action=f"apply_design:{file_key}", revision_id=revision_id, result="SUCCESS",
|
memo=memo, created_by=actor,
|
||||||
detail=f"{len(submitted)}자 적용 (백업 {backup_id})",
|
)
|
||||||
|
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)
|
logger.info("디자인 파일 적용(%s) (%s)", file_key, actor)
|
||||||
return RedirectResponse(
|
return go(msg=f"적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.{record_note}")
|
||||||
url=f"{back}?msg=적용했습니다. 직전 내용은 버전 {backup_id} 로 보관됩니다.",
|
|
||||||
status_code=303,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -9,15 +9,20 @@
|
|||||||
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
PUT /products/{no}/options 옵션명 · 옵션값 이름/이미지/표시방식 수정
|
||||||
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
DELETE /products/{no}/options 옵션 삭제 (품목도 함께 삭제 — 확인 후)
|
||||||
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
POST /products/{no}/options/image 옵션값 썸네일 업로드만 (경로 반환)
|
||||||
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매
|
PUT /products/{no}/variants 품목 자체코드 · 추가금액 · 진열 · 판매 (행별 결과)
|
||||||
|
|
||||||
공통 규칙
|
공통 규칙
|
||||||
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
- 카페24 호출은 `app.integrations.cafe24` 만 통한다(httpx 직접 호출 금지).
|
||||||
|
- 쓰기는 상품별 DB 잠금(writes.write_lock) 안에서 한다 — 같은 상품을 웹 여러
|
||||||
|
프로세스·예약 worker 가 동시에 쓰지 않게. 못 잡으면 409.
|
||||||
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
- 쓰기 전에 현재값을 읽되, **읽기 지연을 보정한 유효 현재값**과 비교해 바뀐
|
||||||
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
것만 보낸다(routes_products.load_product). 이걸 안 하면 "A→B 로 바꾼 직후
|
||||||
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
다시 B→A" 가 카페24의 예전 값(A)과 같다고 판단돼 무시된다.
|
||||||
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
- PUT 응답이 곧 현재값이다. 응답을 스냅샷(`save_write_snapshot`)에 남기고 화면도
|
||||||
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
응답으로 그린다 — 다시 GET 하지 않는다(GET 은 한동안 예전 값을 돌려준다).
|
||||||
|
PUT 이 성공한 뒤의 기록 실패는 쓰기 실패로 알리지 않는다(재전송을 부르지 않게).
|
||||||
|
- 품목은 **품목코드**(안정 식별자)로 짝짓는다. 옵션값 이름을 바꾼 직후 GET 품목이
|
||||||
|
예전 이름을 돌려줘도 스냅샷의 품목코드별 표기로 바로잡는다(store.apply_variant_patch).
|
||||||
- 모든 쓰기는 감사로그(`cafe24_audit_logs`)에 남긴다.
|
- 모든 쓰기는 감사로그(`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.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
from app.timezone import now_kst
|
||||||
|
|
||||||
from . import store
|
from . import store, writes
|
||||||
from .common import read_lag_grace_minutes, require_store
|
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")
|
logger = logging.getLogger("cafe24.product_info")
|
||||||
|
|
||||||
@@ -110,39 +115,40 @@ def product_basic(
|
|||||||
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
raise HTTPException(status_code=400, detail="바꿀 항목이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명·가격 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"현재값 조회 실패: {exc}")
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
|
||||||
changes: dict[str, str] = {}
|
changes: dict[str, str] = {}
|
||||||
before: dict[str, str] = {}
|
before: dict[str, str] = {}
|
||||||
for key, value in want.items():
|
for key, value in want.items():
|
||||||
old = str(current.get(key) or "")
|
old = str(current.get(key) or "")
|
||||||
same = old == value if key == "product_name" else store.price_equal(old, value)
|
same = old == value if key == "product_name" else store.price_equal(old, value)
|
||||||
if not same:
|
if not same:
|
||||||
changes[key] = value
|
changes[key] = value
|
||||||
before[key] = old
|
before[key] = old
|
||||||
if not changes:
|
if not changes:
|
||||||
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
return {"ok": True, "changed": [], "product": _scalar_view(current)}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, **changes)
|
updated = products.update_product(api.client, product_no, **changes)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="update_basic", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
result="FAIL", detail=f"{changes} 실패: {exc}")
|
result="FAIL", detail=f"{changes} 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 기본정보 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from 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}
|
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
|
||||||
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
|
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,
|
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
|
||||||
result="SUCCESS", detail=detail)
|
result="SUCCESS", detail=detail)
|
||||||
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
|
||||||
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
|
||||||
|
|
||||||
@@ -169,30 +175,31 @@ def product_image(
|
|||||||
data = _read_image(file)
|
data = _read_image(file)
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="대표 이미지 교체"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not current:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
if not current:
|
||||||
before = str(current.get("detail_image") or "")
|
raise HTTPException(status_code=404, detail="카페24에서 상품을 찾지 못했습니다.")
|
||||||
|
before = str(current.get("detail_image") or "")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
images = products.set_main_image(
|
images = products.set_main_image(
|
||||||
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
api.client, product_no, data, content_type=(file.content_type or "").lower()
|
||||||
)
|
)
|
||||||
if not images.get("detail_image"):
|
if not images.get("detail_image"):
|
||||||
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="FAIL", detail=f"등록 실패: {exc}")
|
result="FAIL", detail=f"등록 실패: {exc}")
|
||||||
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 대표이미지 변경 실패: %s", product_no, exc)
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
|
|
||||||
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
merged = {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
|
||||||
remember_write(st, product_no, merged)
|
remember_write(st, product_no, merged)
|
||||||
st.log_audit(actor=actor, action="set_main_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="set_main_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
result="SUCCESS", detail=f"'{before}' → '{images['detail_image']}'")
|
||||||
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 대표이미지 변경 (%s)", product_no, actor)
|
||||||
return {"ok": True, "product": _scalar_view(merged)}
|
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 "")}
|
{"name": str(o.get("name") or ""), "value": str(o.get("value") or "")}
|
||||||
for o in opts if isinstance(o, dict)
|
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 ""),
|
"custom_variant_code": str(v.get("custom_variant_code") or ""),
|
||||||
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
"additional_amount": str(v.get("additional_amount") or "0.00"),
|
||||||
"display": products._flag(v.get("display")), # noqa: SLF001
|
"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_link_image": str(v.get("option_link_image") or ""),
|
||||||
"option_color": str(v.get("option_color") or ""),
|
"option_color": str(v.get("option_color") or ""),
|
||||||
"value_no": v.get("value_no"),
|
"value_no": v.get("value_no"),
|
||||||
|
"pending": bool(v.get("pending")),
|
||||||
}
|
}
|
||||||
for v in values if isinstance(v, dict)
|
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]]:
|
def _snapshot_sections(st: Any, product_no: int) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||||
"""GET 품목 목록에 유예시간 안의 우리 쓰기(스냅샷)를 덮어씌운다.
|
"""(옵션 섹션, 품목 섹션) — 각각 {"data":…, "written_at":…} 또는 {}."""
|
||||||
|
snap = st.get_write_snapshot(product_no) or {}
|
||||||
|
return snap.get("options") or {}, snap.get("variants") or {}
|
||||||
|
|
||||||
삭제한 품목(`{"_deleted": true}`)은 카페24 GET 이 한동안 계속 돌려주므로 걸러낸다.
|
|
||||||
"""
|
def _within(written_at: object) -> bool:
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("variants") or {}
|
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 {}
|
data = section.get("data") or {}
|
||||||
if not data or not store.within_grace(section.get("written_at"), grace_minutes=read_lag_grace_minutes()):
|
if not isinstance(data, dict) or not data:
|
||||||
return variants
|
return list(variants)
|
||||||
out = []
|
out = []
|
||||||
for v in variants:
|
for v in variants:
|
||||||
code = str(v.get("variant_code") or "")
|
patched = store.apply_variant_patch(
|
||||||
patch = data.get(code)
|
v, data.get(str(v.get("variant_code") or "")),
|
||||||
if isinstance(patch, dict) and patch.get("_deleted"):
|
section_written_at=section.get("written_at"), grace_minutes=read_lag_grace_minutes(),
|
||||||
continue
|
)
|
||||||
out.append({**v, **patch} if isinstance(patch, dict) else v)
|
if patched is not None:
|
||||||
|
out.append(patched)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _apply_options_snapshot(st: Any, product_no: int, option: dict[str, Any]) -> dict[str, Any]:
|
def _annotate(option: dict[str, Any], variants: list[dict[str, Any]], recent: list[str]) -> tuple[dict, list]:
|
||||||
"""GET 옵션이 우리 마지막 쓰기와 다르고 유예시간 안이면 스냅샷(우리 쓰기)을 쓴다."""
|
"""옵션 1개 상품: 품목에 첫 옵션값 번호(value_no)를, 품목이 아직 안 보이는 최근 추가
|
||||||
section = (st.get_write_snapshot(product_no) or {}).get("options") or {}
|
옵션값에 pending 표시를 붙인다(화면이 "품목 없는 옵션값"으로 오해하지 않게)."""
|
||||||
data = section.get("data")
|
groups = option.get("options") if isinstance(option.get("options"), list) else []
|
||||||
if not isinstance(data, dict) or not store.within_grace(
|
if len(groups) != 1 or not isinstance(groups[0], dict):
|
||||||
section.get("written_at"), grace_minutes=read_lag_grace_minutes()
|
return option, variants
|
||||||
):
|
values = [v for v in (groups[0].get("option_value") or []) if isinstance(v, dict)]
|
||||||
return option
|
by_text = {str(v.get("option_text") or ""): v.get("value_no") for v in values}
|
||||||
return data
|
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]:
|
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))
|
raw_option = products.get_options(api.client, product_no)
|
||||||
view = _options_view(option)
|
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]] = []
|
variants: list[dict[str, Any]] = []
|
||||||
if view["has_option"]:
|
if products._flag(option.get("has_option"), default=False): # noqa: SLF001
|
||||||
variants = _apply_variant_snapshot(st, product_no, products.list_variants(api.client, product_no))
|
raw_variants = products.list_variants(api.client, product_no)
|
||||||
return {"option": view, "variants": [_variant_view(v) for v in variants], "raw_options": option}
|
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")
|
@product_info_router.get("/products/{product_no}/options")
|
||||||
@@ -322,29 +414,40 @@ def options_create(
|
|||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from 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)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 생성"):
|
||||||
existing = products.get_options(api.client, product_no)
|
try:
|
||||||
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
existing = products.get_options(api.client, product_no)
|
||||||
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
if products._flag(existing.get("has_option"), default=False): # noqa: SLF001
|
||||||
created = products.create_options(api.client, product_no, body)
|
raise HTTPException(status_code=409, detail="이미 옵션이 있는 상품입니다. 수정하거나 삭제한 뒤 다시 만드세요.")
|
||||||
except Cafe24Error as exc:
|
created = products.create_options(api.client, product_no, body)
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{body['options'][0]['option_name']} 실패: {exc}")
|
writes.audit_safe(st, actor=actor, action="create_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
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)
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
values = [v["option_text"] for v in body["options"][0]["option_value"]]
|
record_error = _save_snapshot_safe(
|
||||||
st.log_audit(actor=actor, action="create_options", product_no=product_no, result="SUCCESS",
|
st, product_no, "options",
|
||||||
detail=f"옵션 '{body['options'][0]['option_name']}' 생성: {', '.join(values)}")
|
_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)
|
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):
|
if len(variants) < len(values):
|
||||||
logger.warning("카페24 상품 %s 옵션 생성 후 품목 %s/%s 건만 조회됨", product_no, 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")
|
@product_info_router.put("/products/{product_no}/options")
|
||||||
@@ -358,6 +461,8 @@ def options_update(
|
|||||||
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
카페24 PUT 은 `original_options`(수정 전)와 `options`(수정 후)를 짝지어 받는다.
|
||||||
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
수정 전 값은 화면이 들고 있던 것이 아니라 **지금 카페24에서 다시 읽은 값**(읽기
|
||||||
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
지연 보정 후)을 쓴다 — 그래야 다른 곳에서 바뀐 이름과 어긋나지 않는다.
|
||||||
|
이름을 바꾸면 품목코드별로 새 표기를 스냅샷에 남긴다(GET 품목이 예전 이름을
|
||||||
|
돌려주는 동안에도 품목이 옵션값과 제대로 짝지어 보이게).
|
||||||
"""
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
@@ -366,64 +471,99 @@ def options_update(
|
|||||||
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
raise HTTPException(status_code=400, detail="옵션 목록이 비어 있습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 수정"):
|
||||||
loaded = _load_options_and_variants(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
loaded = _load_options_and_variants(st, api, product_no)
|
||||||
raise _http_from_cafe24(exc) from exc
|
except Cafe24Error as exc:
|
||||||
if not loaded["option"]["has_option"]:
|
raise _http_from_cafe24(exc) from exc
|
||||||
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
if not loaded["option"]["has_option"]:
|
||||||
original = loaded["option"]["options"]
|
raise HTTPException(status_code=409, detail="옵션이 없는 상품입니다. 먼저 옵션을 만드세요.")
|
||||||
try:
|
original = loaded["option"]["options"]
|
||||||
body = store.build_update_options_request(
|
try:
|
||||||
original, edited, option_list_type=str(payload.get("option_list_type") or ""),
|
body = store.build_update_options_request(
|
||||||
allow_append=True,
|
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:
|
# 이름 바꾸기 표(수정 전 → 수정 후) — 위치로 짝지어진다(build_update_options_request).
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
rename: dict[tuple[str, str], tuple[str, str]] = {}
|
||||||
if loaded["option"]["option_preset_code"]:
|
for o, n in zip(original, body["options"]):
|
||||||
body["option_preset_code"] = loaded["option"]["option_preset_code"]
|
for ov, nv in zip(o["option_value"], n["option_value"]):
|
||||||
# 뒤에 덧붙인 옵션값 수 — 카페24가 받아들이면 품목을 자동 생성한다(재시도 조회).
|
rename[(o["option_name"], ov["option_text"])] = (n["option_name"], nv["option_text"])
|
||||||
added = sum(
|
raw_labels = {str(v.get("variant_code") or ""): v.get("options") for v in loaded["raw_variants"]}
|
||||||
max(0, len(n["option_value"]) - len(o["option_value"]))
|
previous = (loaded["variants_section"].get("data") or {}) if _within(
|
||||||
for o, n in zip(body["original_options"], body["options"])
|
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:
|
fresh: list[dict[str, Any]] | None = None
|
||||||
updated = products.update_options(api.client, product_no, body)
|
if added:
|
||||||
except Cafe24Error as exc:
|
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
||||||
st.log_audit(actor=actor, action="update_options", product_no=product_no,
|
# 늦게 나타나는 품목은 pending 으로 표시된다(_annotate).
|
||||||
result="FAIL", detail=str(exc))
|
_osec, vsec = _snapshot_sections(st, product_no)
|
||||||
logger.warning("카페24 상품 %s 옵션 수정 실패: %s", product_no, exc)
|
fresh = _patch_variants(
|
||||||
raise _http_from_cafe24(exc) from exc
|
vsec, products.wait_for_variants(api.client, product_no, len(loaded["raw_variants"]) + added)
|
||||||
|
)
|
||||||
st.save_write_snapshot(product_no, "options", updated)
|
writes.audit_safe(st, actor=actor, action="update_options", product_no=product_no,
|
||||||
summary = "; ".join(
|
result="SUCCESS", detail=summary[:900])
|
||||||
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])
|
|
||||||
logger.info("카페24 상품 %s 옵션 수정 (%s)", product_no, actor)
|
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:
|
if added:
|
||||||
# 새 옵션값의 품목코드를 받아 돌려준다 — 화면이 자체코드/추가금액을 이어서 PUT 한다.
|
out["added"] = added
|
||||||
fresh = products.wait_for_variants(api.client, product_no, len(loaded["variants"]) + added)
|
return out
|
||||||
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}
|
|
||||||
|
|
||||||
|
|
||||||
@product_info_router.delete("/products/{product_no}/options")
|
@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)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="옵션 삭제"):
|
||||||
before = products.get_options(api.client, product_no)
|
try:
|
||||||
products.delete_options(api.client, product_no)
|
before = products.get_options(api.client, product_no)
|
||||||
except Cafe24Error as exc:
|
products.delete_options(api.client, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=str(exc))
|
writes.audit_safe(st, actor=actor, action="delete_options", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=str(exc))
|
||||||
names = ", ".join(
|
raise _http_from_cafe24(exc) from exc
|
||||||
str(o.get("option_name") or "") for o in (before.get("options") or []) if isinstance(o, dict)
|
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", {})
|
osec, _vsec = _snapshot_sections(st, product_no)
|
||||||
st.log_audit(actor=actor, action="delete_options", product_no=product_no,
|
record_error = _save_snapshot_safe(
|
||||||
result="SUCCESS", detail=f"삭제된 옵션: {names or '(없음)'}")
|
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)
|
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")
|
@product_info_router.post("/products/{product_no}/options/image")
|
||||||
@@ -464,13 +611,13 @@ def option_image_upload(
|
|||||||
try:
|
try:
|
||||||
path = products.upload_image_bytes(api.client, data)
|
path = products.upload_image_bytes(api.client, data)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="FAIL", detail=str(exc))
|
result="FAIL", detail=str(exc))
|
||||||
raise _http_from_cafe24(exc) from exc
|
raise _http_from_cafe24(exc) from exc
|
||||||
if not path:
|
if not path:
|
||||||
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
raise HTTPException(status_code=502, detail="카페24가 업로드 경로를 돌려주지 않았습니다.")
|
||||||
st.log_audit(actor=actor, action="upload_option_image", product_no=product_no,
|
writes.audit_safe(st, actor=actor, action="upload_option_image", product_no=product_no,
|
||||||
result="SUCCESS", detail=path)
|
result="SUCCESS", detail=path)
|
||||||
return {"ok": True, "path": 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):
|
if not store.VARIANT_CODE_RE.match(code):
|
||||||
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
raise HTTPException(status_code=400, detail=f"품목코드 형식이 올바르지 않습니다: {code}")
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 삭제"):
|
||||||
products.delete_variant(api.client, product_no, code)
|
try:
|
||||||
except Cafe24Error as exc:
|
products.delete_variant(api.client, product_no, code)
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
except Cafe24Error as exc:
|
||||||
result="FAIL", detail=f"{code}: {exc}")
|
writes.audit_safe(st, actor=actor, action="delete_variant", product_no=product_no,
|
||||||
raise _http_from_cafe24(exc) from exc
|
result="FAIL", detail=f"{code}: {exc}")
|
||||||
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 스냅샷에 삭제 표식을 남겨 걸러낸다.
|
raise _http_from_cafe24(exc) from exc
|
||||||
st.save_write_snapshot(product_no, "variants", {code: {"_deleted": True}})
|
# 카페24 GET 은 한동안 삭제된 품목을 계속 돌려준다 — 삭제 표식을 남겨 걸러낸다.
|
||||||
st.log_audit(actor=actor, action="delete_variant", product_no=product_no,
|
# 표식은 이후 늦게 도착한 수정이 있어도 유지된다(store.merge_variant_snapshot).
|
||||||
result="SUCCESS", detail=code)
|
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)
|
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")
|
@product_info_router.put("/products/{product_no}/variants")
|
||||||
@@ -503,7 +652,13 @@ def variants_update(
|
|||||||
product_no: int,
|
product_no: int,
|
||||||
payload: dict[str, Any] = Body(default_factory=dict),
|
payload: dict[str, Any] = Body(default_factory=dict),
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다."""
|
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
|
||||||
|
|
||||||
|
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
|
||||||
|
"failed": {code: 사유}, "unknown": {code: 사유}}
|
||||||
|
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
|
||||||
|
다시 보내지 않게). 하나도 반영되지 않았으면 502.
|
||||||
|
"""
|
||||||
st, user = require_store(request)
|
st, user = require_store(request)
|
||||||
actor = str(user.get("email") or "")
|
actor = str(user.get("email") or "")
|
||||||
rows = payload.get("rows")
|
rows = payload.get("rows")
|
||||||
@@ -517,31 +672,51 @@ def variants_update(
|
|||||||
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
raise HTTPException(status_code=400, detail="바뀐 값이 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="품목 수정"):
|
||||||
results = products.update_variants(api.client, product_no, requests)
|
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가 받아들였으므로). 응답에 담긴 값이 있으면
|
# 카페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]] = {}
|
by_code: dict[str, dict[str, Any]] = {}
|
||||||
for r in requests:
|
failed: dict[str, str] = {}
|
||||||
by_code[r["variant_code"]] = {k: v for k, v in r.items() if k != "variant_code"}
|
unknown: dict[str, str] = {}
|
||||||
for r in results:
|
for result in results:
|
||||||
code = str(r.get("variant_code") or "")
|
code = result["variant_code"]
|
||||||
if code in by_code:
|
if result["status"] == products.VARIANT_OK:
|
||||||
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
patch = dict(sent.get(code) or {})
|
||||||
if key in r and r[key] is not None:
|
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
|
||||||
by_code[code][key] = r[key]
|
value = (result.get("variant") or {}).get(key)
|
||||||
st.save_write_snapshot(product_no, "variants", by_code)
|
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(
|
detail = "; ".join(
|
||||||
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
|
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,
|
if failed or unknown:
|
||||||
result="SUCCESS", detail=detail[:900])
|
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
|
||||||
logger.info("카페24 상품 %s 품목 %s건 수정 (%s)", product_no, len(by_code), actor)
|
first = next(iter({**failed, **unknown}.values()), "")
|
||||||
return {"ok": True, "updated": {code: _variant_view({"variant_code": code, **patch})
|
detail += f" / 오류: {first}"
|
||||||
for code, patch in by_code.items()}}
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
from contextlib import contextmanager
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any
|
from typing import Any, Iterator
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import quote, urlencode
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
from fastapi import APIRouter, Body, Form, HTTPException, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
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.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
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
|
from .common import base_ctx, guard, read_lag_grace_minutes, require_store
|
||||||
|
|
||||||
logger = logging.getLogger("cafe24.products")
|
logger = logging.getLogger("cafe24.products")
|
||||||
@@ -121,6 +122,16 @@ def _short_dt(value: Any) -> str:
|
|||||||
return text.replace("T", " ")[:16]
|
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]:
|
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정."""
|
||||||
normalized = products.normalize_product(raw)
|
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(
|
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]:
|
) -> tuple[str, str, dict[str, Any] | None]:
|
||||||
"""(유효 HTML, 상태, 마지막 쓰기 revision). 상태는 store.SYNC_*."""
|
"""(유효 HTML, 상태, 마지막 확인된 쓰기). 상태는 store.SYNC_*.
|
||||||
grace = read_lag_grace_minutes()
|
|
||||||
since = now_kst() - timedelta(minutes=grace)
|
근거는 원격 반영이 확인된 쓰기(cafe24_write_attempts)뿐이다 — writes.resolve_effective.
|
||||||
last_write = st.latest_write_revision(product_no, since=since)
|
"""
|
||||||
if not last_write:
|
return writes.resolve_effective(st, product_no, cafe24_html, fetched_updated=fetched_updated)
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
def remember_write(st: Any, product_no: int, updated: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다."""
|
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. 정규화된 캐시 행을 돌려준다.
|
||||||
info = products.normalize_product(updated) if updated else {}
|
|
||||||
if info.get("product_no"):
|
카페24에는 이미 반영된 뒤라 기록 실패로 예외를 내지 않는다(로그만 — writes 참고).
|
||||||
st.upsert_products([info])
|
"""
|
||||||
st.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
info, _error = writes.remember_product_write(st, product_no, updated)
|
||||||
return info
|
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]:
|
def _info(product: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""편집기·정보 패널 공용 상품 요약."""
|
"""편집기·정보 패널 공용 상품 요약."""
|
||||||
info = products.normalize_product(product) if product else {}
|
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)
|
product, scalar_stale = load_product(st, api, product_no)
|
||||||
desc = products.descriptions_from_product(product)
|
desc = products.descriptions_from_product(product)
|
||||||
st.upsert_products([products.normalize_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:
|
except Cafe24Error as exc:
|
||||||
error = str(exc)
|
error = str(exc)
|
||||||
logger.warning("카페24 상품 %s 조회 실패: %s", product_no, 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 {
|
return {
|
||||||
"product_no": product_no,
|
"product_no": product_no,
|
||||||
# 고객이 보는 상세페이지 주소 (CAFE24_SHOP_URL, 없으면 카페24 기본 도메인)
|
# 고객이 보는 상세페이지 주소 (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_pending": sync_state == store.SYNC_PENDING,
|
||||||
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
"sync_external": sync_state == store.SYNC_EXTERNAL,
|
||||||
"scalar_stale": scalar_stale,
|
"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 "",
|
"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,
|
"editor_error": error,
|
||||||
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
"option_display_types": store.OPTION_DISPLAY_LABELS,
|
||||||
}
|
}
|
||||||
@@ -384,33 +416,34 @@ def product_rename(
|
|||||||
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
raise HTTPException(status_code=400, detail=f"상품명은 {NAME_MAX}자를 넘을 수 없습니다.")
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="상품명 변경"):
|
||||||
current, _ = load_product(st, api, product_no)
|
try:
|
||||||
except Cafe24Error as exc:
|
current, _ = load_product(st, api, product_no)
|
||||||
st.log_audit(
|
except Cafe24Error as exc:
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
writes.audit_safe(
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
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
|
)
|
||||||
|
raise HTTPException(status_code=502, detail=f"카페24 현재값을 읽지 못했습니다: {exc}") from exc
|
||||||
|
|
||||||
before = str(current.get("product_name") or "")
|
before = str(current.get("product_name") or "")
|
||||||
if before == name:
|
if before == name:
|
||||||
return {"ok": True, "product_name": before, "changed": False}
|
return {"ok": True, "product_name": before, "changed": False}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
updated = products.update_product(api.client, product_no, product_name=name)
|
updated = products.update_product(api.client, product_no, product_name=name)
|
||||||
except Cafe24Error as exc:
|
except Cafe24Error as exc:
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
result="FAIL", detail=f"'{before}' → '{name}' 실패: {exc}",
|
||||||
)
|
)
|
||||||
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
logger.warning("카페24 상품 %s 이름 변경 실패: %s", product_no, exc)
|
||||||
raise HTTPException(status_code=502, detail=str(exc)) from 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)
|
after = str(info.get("product_name") or name)
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action="rename_product", product_no=product_no,
|
st, actor=actor, action="rename_product", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
result="SUCCESS", detail=f"'{before}' → '{after}'",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
logger.info("카페24 상품 %s 이름 변경 (%s)", product_no, actor)
|
||||||
@@ -442,31 +475,32 @@ def product_status(
|
|||||||
want = bool(payload.get("value"))
|
want = bool(payload.get("value"))
|
||||||
|
|
||||||
api = build_cafe24_api(st)
|
api = build_cafe24_api(st)
|
||||||
try:
|
with locked_json(st, product_no, actor=actor, purpose="진열/판매 변경"):
|
||||||
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:
|
|
||||||
try:
|
try:
|
||||||
updated, _ = load_product(st, api, product_no)
|
updated = products.update_product(api.client, product_no, **{field: want})
|
||||||
except Cafe24Error as exc: # 쓰기는 됐다 — 화면만 요청값으로 맞춘다.
|
except Cafe24Error as exc:
|
||||||
logger.warning("카페24 상품 %s 상태 재조회 실패: %s", product_no, exc)
|
writes.audit_safe(
|
||||||
updated = {}
|
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 = {
|
state = {
|
||||||
"display": bool(info.get("display", want if field == "display" else True)),
|
"display": bool(info.get("display", want if field == "display" else True)),
|
||||||
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
"selling": bool(info.get("selling", want if field == "selling" else True)),
|
||||||
}
|
}
|
||||||
st.log_audit(
|
writes.audit_safe(
|
||||||
actor=actor, action=f"set_{field}", product_no=product_no,
|
st, actor=actor, action=f"set_{field}", product_no=product_no,
|
||||||
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
result="SUCCESS", detail=f"{field}={'T' if want else 'F'}",
|
||||||
)
|
)
|
||||||
logger.info("카페24 상품 %s %s=%s (%s)", product_no, field, want, actor)
|
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)
|
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")
|
@products_router.post("/products/{product_no}/apply")
|
||||||
def product_apply(
|
def product_apply(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -490,125 +613,165 @@ def product_apply(
|
|||||||
):
|
):
|
||||||
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
"""편집한 HTML 을 카페24에 즉시 적용한다.
|
||||||
|
|
||||||
순서를 지키는 것이 이 함수의 핵심이다.
|
순서(writes.write_product): 상품 잠금 → 카페24 현재값 재조회(로컬 값을 현재값으로
|
||||||
1) 카페24에서 **현재** HTML 을 다시 읽는다(로컬 값을 현재값으로 믿지 않는다)
|
믿지 않는다) → 결과 모르는 이전 시도 확인 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
2) 읽기 지연을 판정해 **유효 현재값**을 정한다(예전 값을 돌려주는 중이면
|
← 유일한 복구 수단 → 지문 대조(충돌 거부) → 시도 기록 → PUT → 버전·스냅샷 기록.
|
||||||
우리 마지막 쓰기가 현재값이다)
|
|
||||||
3) 그 값으로 BACKUP 버전을 남긴다 ← 유일한 복구 수단
|
|
||||||
4) 편집 시작 시점의 지문과 비교해 충돌이면 거부한다
|
|
||||||
5) 쓰고, 스냅샷·MANUAL 버전·감사로그를 남긴다
|
|
||||||
|
|
||||||
PC/모바일을 구분하지 않는다 — 두 필드에 같은 HTML 을 쓴다. 분리 사용 상품의
|
PC/모바일을 구분하지 않는다 — description 만 쓰고 separated_mobile_description="F".
|
||||||
모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
분리 사용 상품의 모바일 내용이 PC 와 달랐다면 덮어쓰기 전에 그 내용도 BACKUP 으로 남긴다.
|
||||||
"""
|
"""
|
||||||
checked = guard(request)
|
checked = guard(request)
|
||||||
if not isinstance(checked, tuple):
|
if not isinstance(checked, tuple):
|
||||||
return checked
|
return checked
|
||||||
st, user = 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에 반영한다. 한글 이미지 경로는
|
# 화면에서 보던 그대로(정리된 소스)를 카페24에 반영한다. 한글 이미지 경로는
|
||||||
# 원래의 퍼센트 인코딩으로 되돌린다.
|
# 원래의 퍼센트 인코딩으로 되돌린다.
|
||||||
submitted = store.format_html(store.encode_html_urls(html or ""))
|
submitted = store.format_html(store.encode_html_urls(html or ""))
|
||||||
if not submitted.strip():
|
if not submitted.strip():
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요.",
|
url=_with_msg(_back_url(product_no, list_query),
|
||||||
|
err="내용이 비어 있습니다. 상세페이지를 비우려면 카페24 관리자에서 하세요."),
|
||||||
status_code=303,
|
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:
|
try:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
revision = _revision_for(st, product_no, revision_id)
|
||||||
except Cafe24Error as exc:
|
except HTTPException as exc:
|
||||||
st.log_audit(
|
return RedirectResponse(url=_with_msg(back, err=str(exc.detail)), status_code=303)
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
body = str(revision.get("html_content") or "")
|
||||||
result="FAIL", detail=f"현재값 조회 실패: {exc}",
|
if not body.strip():
|
||||||
)
|
return RedirectResponse(url=_with_msg(back, err="내용이 빈 버전은 복원할 수 없습니다."), status_code=303)
|
||||||
return RedirectResponse(url=f"{back}&err=카페24 현재값을 읽지 못해 중단했습니다: {exc}", status_code=303)
|
if not base_fingerprint:
|
||||||
|
# 편집기가 본 현재값 없이 복원하면 그 사이 바뀐 내용을 모르고 덮는다.
|
||||||
# 읽기 지연 판정 — 카페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 값이 변경됨",
|
|
||||||
)
|
|
||||||
return RedirectResponse(
|
return RedirectResponse(
|
||||||
url=f"{back}&err=편집하는 동안 카페24 값이 변경되었습니다. 새로고침해 현재 내용을 확인한 뒤 다시 적용하세요.",
|
url=_with_msg(back, err="편집기를 새로고침한 뒤 버전 이력에서 다시 복원하세요."), status_code=303
|
||||||
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:
|
try:
|
||||||
# mobile_description 은 보내지 않는다 — update_descriptions 가
|
with writes.write_lock(st, writes.product_lock_key(product_no), actor=actor, purpose="적용 결과 확정"):
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제하고
|
attempt = st.get_attempt(attempt_id)
|
||||||
# 카페24가 모바일 값을 자동으로 맞춰준다(모바일도 항상 PC와 같다).
|
if (not attempt or int(attempt.get("product_no") or 0) != int(product_no)
|
||||||
updated = products.update_descriptions(api.client, product_no, description=submitted)
|
or attempt.get("status") not in open_states):
|
||||||
except Cafe24Error as exc:
|
return RedirectResponse(url=_with_msg(back, err="이미 확정됐거나 없는 시도입니다."), status_code=303)
|
||||||
st.log_audit(
|
schedule_id = attempt.get("schedule_id")
|
||||||
actor=actor, action="apply_description", product_no=product_no,
|
if result == "applied":
|
||||||
revision_id=backup_id, result="FAIL", detail=str(exc),
|
st.update_attempt(attempt_id, status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
)
|
resolved_by=actor, only_from=open_states)
|
||||||
logger.warning("카페24 상품 %s 적용 실패: %s", product_no, exc)
|
revision_id = writes.record_attempt(st, attempt)
|
||||||
return RedirectResponse(
|
if schedule_id:
|
||||||
url=f"{back}&err=적용에 실패했습니다: {exc} (직전 내용은 버전 {backup_id} 로 보관됨)",
|
st.review_schedule(int(schedule_id), status=store.STATUS_SUCCESS,
|
||||||
status_code=303,
|
note=f"{actor} 가 반영됨으로 확정", actor=actor, action="applied")
|
||||||
)
|
text = f"시도 #{attempt_id} 를 반영됨으로 확정했습니다(버전 {revision_id})."
|
||||||
|
else:
|
||||||
# PUT 응답은 쓰기 직후의 실제 값 — 스냅샷으로 남긴다(상품명·가격·updated_date 등).
|
st.update_attempt(attempt_id, status=store.ATTEMPT_ABANDONED, resolved_by=actor,
|
||||||
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
|
only_from=open_states)
|
||||||
|
if schedule_id:
|
||||||
# MANUAL revision 을 **먼저** 남긴다. 이것이 "마지막 쓰기" 기준이 되어, 카페24 GET 이
|
st.review_schedule(int(schedule_id), status=store.STATUS_FAILED,
|
||||||
# 한동안 예전 값을 돌려줘도 편집기는 방금 적용한 내용을 보여준다.
|
note=f"{actor} 가 반영 안 됨으로 확정", actor=actor, action="not_applied")
|
||||||
revision_id = st.add_revision(
|
text = f"시도 #{attempt_id} 를 반영 안 됨으로 확정했습니다. 필요하면 다시 적용하세요."
|
||||||
product_no=product_no,
|
except (writes.WriteBusy, writes.WriteSetupError) as exc:
|
||||||
html_content=submitted,
|
return RedirectResponse(url=_with_msg(back, err=str(exc)), status_code=303)
|
||||||
revision_type=store.REVISION_MANUAL,
|
writes.audit_safe(st, actor=actor, action=f"resolve_attempt:{result}", product_no=product_no,
|
||||||
memo=memo,
|
result="SUCCESS", detail=f"시도 #{attempt_id}")
|
||||||
created_by=actor,
|
return RedirectResponse(url=_with_msg(back, msg=text), status_code=303)
|
||||||
)
|
|
||||||
|
|
||||||
# 카페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,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -22,9 +22,9 @@ import logging
|
|||||||
from fastapi import APIRouter, Form, Request
|
from fastapi import APIRouter, Form, Request
|
||||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
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 .common import base_ctx, guard
|
||||||
from .routes_products import _no_store
|
from .routes_products import _no_store
|
||||||
|
|
||||||
@@ -55,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
|
|||||||
set_selling=row.get("set_selling"),
|
set_selling=row.get("set_selling"),
|
||||||
),
|
),
|
||||||
"editable": store.is_editable(row.get("status") or ""),
|
"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": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용",
|
||||||
"rows": rows,
|
"rows": rows,
|
||||||
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
|
"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": request.query_params.get("msg", ""),
|
||||||
"flash_error": request.query_params.get("err", ""),
|
"flash_error": request.query_params.get("err", ""),
|
||||||
}
|
}
|
||||||
@@ -114,6 +116,12 @@ def schedule_create(
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return RedirectResponse(url=f"{back}&err={exc}", status_code=303)
|
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
|
revision_id: int | None = None
|
||||||
if want_html:
|
if want_html:
|
||||||
body = store.format_html(store.encode_html_urls(html or ""))
|
body = store.format_html(store.encode_html_urls(html or ""))
|
||||||
@@ -127,6 +135,7 @@ def schedule_create(
|
|||||||
revision_type=store.REVISION_DRAFT,
|
revision_type=store.REVISION_DRAFT,
|
||||||
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
memo=f"예약 등록 ({run_at.strftime('%Y-%m-%d %H:%M')} 적용 예정)",
|
||||||
created_by=actor,
|
created_by=actor,
|
||||||
|
mall_id=load_config().mall_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
schedule_id = st.create_schedule(
|
schedule_id = st.create_schedule(
|
||||||
@@ -187,3 +196,51 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
|
|||||||
"display": normalized["display"],
|
"display": normalized["display"],
|
||||||
"selling": normalized["selling"],
|
"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
|
from __future__ import annotations
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -44,6 +45,9 @@ STATUS_PROCESSING = "PROCESSING"
|
|||||||
STATUS_SUCCESS = "SUCCESS"
|
STATUS_SUCCESS = "SUCCESS"
|
||||||
STATUS_FAILED = "FAILED"
|
STATUS_FAILED = "FAILED"
|
||||||
STATUS_CANCELLED = "CANCELLED"
|
STATUS_CANCELLED = "CANCELLED"
|
||||||
|
# 원격 반영 여부를 모른다(네트워크 끊김·worker 중단) — 사람이 카페24를 보고 확정한다.
|
||||||
|
# 자동으로 PENDING 에 돌려 재적용하지 않는다(마이그레이션 005).
|
||||||
|
STATUS_NEEDS_REVIEW = "NEEDS_REVIEW"
|
||||||
|
|
||||||
SCHEDULE_STATUSES: tuple[str, ...] = (
|
SCHEDULE_STATUSES: tuple[str, ...] = (
|
||||||
STATUS_PENDING,
|
STATUS_PENDING,
|
||||||
@@ -51,6 +55,7 @@ SCHEDULE_STATUSES: tuple[str, ...] = (
|
|||||||
STATUS_SUCCESS,
|
STATUS_SUCCESS,
|
||||||
STATUS_FAILED,
|
STATUS_FAILED,
|
||||||
STATUS_CANCELLED,
|
STATUS_CANCELLED,
|
||||||
|
STATUS_NEEDS_REVIEW,
|
||||||
)
|
)
|
||||||
|
|
||||||
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
||||||
@@ -59,8 +64,36 @@ SCHEDULE_STATUS_LABELS: dict[str, str] = {
|
|||||||
STATUS_SUCCESS: "완료",
|
STATUS_SUCCESS: "완료",
|
||||||
STATUS_FAILED: "실패",
|
STATUS_FAILED: "실패",
|
||||||
STATUS_CANCELLED: "취소",
|
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 는 임의 변경 금지
|
# 사용자가 손댈 수 있는 상태 — PROCESSING/SUCCESS 는 임의 변경 금지
|
||||||
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
EDITABLE_STATUSES: tuple[str, ...] = (STATUS_PENDING,)
|
||||||
|
|
||||||
@@ -509,11 +542,20 @@ def resolve_description(
|
|||||||
known_digests: set[str] | frozenset[str],
|
known_digests: set[str] | frozenset[str],
|
||||||
grace_minutes: int,
|
grace_minutes: int,
|
||||||
now: datetime | None = None,
|
now: datetime | None = None,
|
||||||
|
fetched_updated: object = None,
|
||||||
) -> tuple[str, str]:
|
) -> tuple[str, str]:
|
||||||
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
"""(화면·적용에 쓸 유효 HTML, 상태) 를 돌려준다.
|
||||||
|
|
||||||
last_write: 최근 쓰기 revision — {"html_content", "created_at"}.
|
last_write: **원격 반영이 확인된** 마지막 쓰기 — {"html_content", "created_at",
|
||||||
known_digests: 유예시간 안의 revision 들의 내용 해시(`content_digest()` 결과) 집합.
|
"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:
|
if not last_write:
|
||||||
return cafe24_html, SYNC_NONE
|
return cafe24_html, SYNC_NONE
|
||||||
@@ -523,11 +565,29 @@ def resolve_description(
|
|||||||
last_html = str(last_write.get("html_content") or "")
|
last_html = str(last_write.get("html_content") or "")
|
||||||
if cafe24_html == last_html:
|
if cafe24_html == last_html:
|
||||||
return cafe24_html, SYNC_SYNCED
|
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:
|
if content_digest(cafe24_html) in known_digests:
|
||||||
return last_html, SYNC_PENDING
|
return last_html, SYNC_PENDING
|
||||||
return cafe24_html, SYNC_EXTERNAL
|
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:
|
def content_digest(html: str) -> str:
|
||||||
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
"""revision 내용 대조용 md5 hex — DB 의 `md5(html_content)` 와 같은 값.
|
||||||
|
|
||||||
@@ -598,6 +658,172 @@ def overlay_recent_write(
|
|||||||
return merged, True
|
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 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
{# 읽기 지연 배너 — 카페24 관리자 API 가 아직 이전 값을 돌려주는 동안에는 마지막으로
|
||||||
적용한 내용(MANUAL/SCHEDULED revision)을 편집기에 보여준다. 쇼핑몰 화면에는 이미
|
적용한 내용(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 %}
|
{% if sync_pending %}
|
||||||
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
<div class="cf24-flash cf24-flash-warn" id="cf24-sync-banner">
|
||||||
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
<strong>카페24 반영 대기 중</strong> — 카페24 관리자 API 가 아직 이전 소스를 돌려주고 있어
|
||||||
@@ -199,28 +226,40 @@
|
|||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details class="cf24-details">
|
<details class="cf24-details" id="cf24-history">
|
||||||
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
<summary>버전 이력 {% if revisions %}({{ revisions | length }}건){% endif %}</summary>
|
||||||
{% if revisions %}
|
{% if revisions %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
<table class="erp-table cf24-compact">
|
<table class="erp-table cf24-compact">
|
||||||
<thead>
|
<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>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for rev in revisions %}
|
{% for rev in revisions %}
|
||||||
<tr>
|
<tr>
|
||||||
<td class="cf24-nowrap">{{ rev.created_at }}</td>
|
<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.html_length }}자</td>
|
||||||
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ rev.created_by or '—' }}</td>
|
||||||
<td>{{ rev.memo 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>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
<p class="cf24-muted">버전 선택 복원은 Phase 6 에서 붙습니다. 내용은 모두 보관됩니다.</p>
|
<p class="cf24-muted">
|
||||||
|
「원문」에서 그 버전의 소스를 확인·복사하고, 필요하면 「이 버전으로 복원」으로 카페24에 다시 적용합니다.
|
||||||
|
복원도 적용과 같은 순서(현재값 재조회 → 직전 내용 자동 백업 → 편집 중 변경 확인)를 거치며 이력에
|
||||||
|
<code>ROLLBACK</code> 으로 남습니다. 자동 복원(예약 종료 후 되돌리기)은 쓰지 않습니다.
|
||||||
|
</p>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
<p class="cf24-muted">아직 이 상품의 변경 이력이 없습니다.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<div class="erp-card cf24-card">
|
<div class="erp-card cf24-card">
|
||||||
<div class="cf24-card-head">
|
<div class="cf24-card-head">
|
||||||
<h3>예약 목록</h3>
|
<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>
|
</div>
|
||||||
|
|
||||||
<p class="cf24-note">
|
<p class="cf24-note">
|
||||||
@@ -22,6 +22,11 @@
|
|||||||
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
적용 직전 내용은 상품별 <code>BACKUP</code> 버전으로 보관됩니다.
|
||||||
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
<strong>대기</strong> 상태인 예약만 취소할 수 있습니다.
|
||||||
</p>
|
</p>
|
||||||
|
<p class="cf24-note">
|
||||||
|
<strong>확인 필요</strong> — 카페24에 쓰는 도중 응답이 끊겼거나 worker 가 멈춰 반영 여부를 알 수 없는 예약입니다.
|
||||||
|
자동으로 다시 실행하지 않습니다. 쇼핑몰에서 상세페이지·진열/판매를 확인한 뒤
|
||||||
|
「반영됨」(완료로 기록) · 「다시 실행」 · 「실패로 종료」 중 하나를 고르세요.
|
||||||
|
</p>
|
||||||
|
|
||||||
{% if rows %}
|
{% if rows %}
|
||||||
<div class="cf24-scroll">
|
<div class="cf24-scroll">
|
||||||
@@ -53,12 +58,13 @@
|
|||||||
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
|
{% 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 == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
|
||||||
{% elif r.status == 'PENDING' %}<span class="cf24-warn">{{ 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 %}
|
{% else %}<span class="cf24-muted">{{ r.status_label }}</span>{% endif %}
|
||||||
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
{% if r.retry_count %}<span class="cf24-muted">({{ r.retry_count }}회)</span>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
{{ r.memo or '' }}
|
{{ 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>
|
||||||
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
<td class="cf24-nowrap">{{ r.created_by or '—' }}</td>
|
||||||
<td class="cf24-nowrap">
|
<td class="cf24-nowrap">
|
||||||
@@ -67,6 +73,22 @@
|
|||||||
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
data-erp-confirm="예약 #{{ r.id }} 을 취소할까요?">
|
||||||
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
<button type="submit" class="erp-btn erp-btn-outline">취소</button>
|
||||||
</form>
|
</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 %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</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
|
from __future__ import annotations
|
||||||
|
|
||||||
import ftplib
|
import ftplib
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import timedelta
|
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 config as cfgmod
|
||||||
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
from app.integrations.cafe24 import crypto, oauth, products, tokens
|
||||||
from app.integrations.cafe24.errors import Cafe24ApiError, Cafe24AuthError, Cafe24ConfigError
|
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
|
from app.timezone import now_kst
|
||||||
|
|
||||||
SECRET = "unit-test-secret"
|
SECRET = "unit-test-secret"
|
||||||
@@ -25,6 +27,8 @@ SECRET = "unit-test-secret"
|
|||||||
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
||||||
# 기다릴 필요는 없다.
|
# 기다릴 필요는 없다.
|
||||||
products.time.sleep = lambda *_a, **_k: None
|
products.time.sleep = lambda *_a, **_k: None
|
||||||
|
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
||||||
|
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
_TEST_ENV = {
|
_TEST_ENV = {
|
||||||
"CAFE24_MALL_ID": "testmall",
|
"CAFE24_MALL_ID": "testmall",
|
||||||
@@ -711,203 +715,303 @@ def test_design_file_path_env_override():
|
|||||||
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
os.environ["CAFE24_PC_DETAIL_FTP_PATH"] = saved
|
||||||
|
|
||||||
|
|
||||||
class _FakeFTP:
|
_FTP_CFG = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
||||||
"""ftplib.FTP 대역 — 실제 소켓 없이 RETR/STOR 명령만 흉내낸다."""
|
_SWIPER = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
||||||
|
|
||||||
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",))
|
|
||||||
|
|
||||||
|
|
||||||
def test_design_ftp_read_and_write_roundtrip():
|
def test_design_ftp_read_and_write_roundtrip():
|
||||||
from app.integrations.cafe24 import design_ftp
|
from app.integrations.cafe24 import design_ftp
|
||||||
|
|
||||||
path = "/sde_design/mobile11/product-swiper/product-swiper.js"
|
with fakes.patched_ftp() as ftp:
|
||||||
_FakeFTP.files = {path: "old".encode("utf-8")}
|
ftp.reset({_SWIPER: "old".encode("utf-8")})
|
||||||
saved = ftplib.FTP
|
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "old"
|
||||||
ftplib.FTP = _FakeFTP
|
design_ftp.write_text_file(_FTP_CFG, _SWIPER, "new content", expected_current="old")
|
||||||
try:
|
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "new content"
|
||||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
# 원본에 직접 STOR 하지 않는다 — 임시 파일에 올린 뒤 이름 바꾸기로 교체
|
||||||
content = design_ftp.read_text_file(cfg, path)
|
stors = [e for e in ftp.log if e[0] == "STOR"]
|
||||||
assert content == "old"
|
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)
|
||||||
design_ftp.write_text_file(cfg, path, "new content")
|
# 임시 파일이 남지 않는다
|
||||||
assert design_ftp.read_text_file(cfg, path) == "new content"
|
assert set(ftp.files) == {_SWIPER}
|
||||||
finally:
|
|
||||||
ftplib.FTP = saved
|
|
||||||
|
|
||||||
|
|
||||||
def test_design_ftp_missing_file_raises_cafe24_error():
|
def test_design_ftp_missing_file_raises_cafe24_error():
|
||||||
from app.integrations.cafe24 import design_ftp
|
from app.integrations.cafe24 import design_ftp
|
||||||
from app.integrations.cafe24.errors import Cafe24FtpError
|
from app.integrations.cafe24.errors import Cafe24FtpError
|
||||||
|
|
||||||
_FakeFTP.files = {}
|
with fakes.patched_ftp() as ftp:
|
||||||
saved = ftplib.FTP
|
ftp.reset({})
|
||||||
ftplib.FTP = _FakeFTP
|
|
||||||
try:
|
|
||||||
cfg = cfgmod.Cafe24FtpConfig(host="h", port=21, user="u", password="p")
|
|
||||||
try:
|
try:
|
||||||
design_ftp.read_text_file(cfg, "/missing.js")
|
design_ftp.read_text_file(_FTP_CFG, "/missing.js")
|
||||||
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
raise AssertionError("Cafe24FtpError 가 났어야 한다")
|
||||||
except Cafe24FtpError:
|
except Cafe24FtpError:
|
||||||
pass
|
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:
|
def _worker_env(description="<p>A</p>", **schedule):
|
||||||
"""worker 가 쓰는 저장소 메서드만 흉내낸다."""
|
st = fakes.MemoryStore()
|
||||||
|
cafe = fakes.FakeCafe24(description)
|
||||||
def __init__(self, rows):
|
api = fakes.FakeApi(cafe)
|
||||||
self.rows = list(rows)
|
rid = st.add_revision(product_no=131, html_content="<p>예약 내용</p>", revision_type="DRAFT")
|
||||||
self.revisions = {}
|
fields = {"revision_id": rid, "set_display": True}
|
||||||
self.added = []
|
fields.update(schedule)
|
||||||
self.finished = []
|
sid = st.add_schedule(**fields)
|
||||||
self.audits = []
|
return st, cafe, api, sid, rid
|
||||||
|
|
||||||
@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 test_worker_applies_html_and_flags():
|
def test_worker_applies_html_and_flags():
|
||||||
st = _FakeStore([_schedule_row()])
|
st, cafe, api, sid, _rid = _worker_env()
|
||||||
st.revisions[55] = {"html_content": "<p>예약 내용</p>"}
|
assert worker.process_once(st, api) == 1
|
||||||
client = _WorkerClient({"product": _PRODUCT})
|
|
||||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
|
||||||
|
|
||||||
# 쓰기 직전 현재값을 읽어 BACKUP 을 남겼는가
|
# 쓰기 직전 현재값을 읽어 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 으로 보냈는가
|
# HTML 과 진열 상태를 한 번의 PUT 으로 보냈는가
|
||||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
put = cafe.puts()[0]
|
||||||
assert put["json"]["request"]["description"] == "<p>예약 내용</p>"
|
assert put[2]["request"]["description"] == "<p>예약 내용</p>"
|
||||||
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
# mobile_description 은 보내지 않는다 — separated_mobile_description="F" 로
|
||||||
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
# "PC 상세설명과 동일"을 강제한다(직접 보내면 "직접 등록"으로 바뀌어버린다).
|
||||||
assert "mobile_description" not in put["json"]["request"]
|
assert "mobile_description" not in put[2]["request"]
|
||||||
assert put["json"]["request"]["separated_mobile_description"] == "F"
|
assert put[2]["request"]["separated_mobile_description"] == "F"
|
||||||
assert put["json"]["request"]["display"] == "T"
|
assert put[2]["request"]["display"] == "T"
|
||||||
assert "selling" not in put["json"]["request"] # 변경 없음이면 보내지 않는다
|
assert "selling" not in put[2]["request"] # 변경 없음이면 보내지 않는다
|
||||||
assert st.finished == [
|
row = st.schedules[sid]
|
||||||
{"id": 7, "status": store.STATUS_SUCCESS, "error": "",
|
assert row["status"] == store.STATUS_SUCCESS and row["last_error"] == ""
|
||||||
"next_retry_at": None, "retry_count": None}
|
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():
|
def test_worker_flags_only_skips_backup():
|
||||||
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
"""HTML 없이 진열/판매만 바꾸는 예약은 상세설명을 읽거나 백업하지 않는다."""
|
||||||
st = _FakeStore([_schedule_row(revision_id=None, set_selling=False)])
|
st, cafe, api, sid, _ = _worker_env(revision_id=None, set_selling=False)
|
||||||
client = _WorkerClient({"product": _PRODUCT})
|
before = len(st.revisions)
|
||||||
assert worker.process_once(st, _FakeApi(client)) == 1
|
assert worker.process_once(st, api) == 1
|
||||||
assert st.added == [] # 백업 없음
|
assert len(st.revisions) == before # 백업·SCHEDULED 버전 없음
|
||||||
put = [c for c in client.calls if c["method"] == "PUT"][0]
|
put = cafe.puts()[0]
|
||||||
assert "description" not in put["json"]["request"]
|
assert put[2]["request"] == {"display": "T", "selling": "F"}
|
||||||
assert put["json"]["request"] == {"display": "T", "selling": "F"}
|
assert st.schedules[sid]["status"] == store.STATUS_SUCCESS
|
||||||
|
|
||||||
|
|
||||||
def test_worker_retries_then_fails():
|
def test_worker_retries_then_fails():
|
||||||
"""실패는 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED 로 확정한다."""
|
"""거절(반영 안 됨이 확실)은 재시도 예산 안에서 다시 시도하고, 소진되면 FAILED."""
|
||||||
boom = Cafe24ApiError("서버 오류", status=500)
|
st, cafe, api, sid, _ = _worker_env()
|
||||||
|
cafe.put_error = Cafe24ApiError("잘못된 요청", status=422)
|
||||||
st = _FakeStore([_schedule_row(retry_count=0)])
|
worker.process_once(st, api)
|
||||||
st.revisions[55] = {"html_content": "<p>x</p>"}
|
first = st.schedules[sid]
|
||||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
|
||||||
first = st.finished[0]
|
|
||||||
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
assert first["status"] == store.STATUS_PENDING # 다시 대기로
|
||||||
assert first["retry_count"] == 1
|
assert first["retry_count"] == 1
|
||||||
assert first["next_retry_at"] is not None
|
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, cafe2, api2, sid2, _ = _worker_env(retry_count=store.MAX_RETRY)
|
||||||
st2.revisions[55] = {"html_content": "<p>x</p>"}
|
cafe2.put_error = Cafe24ApiError("서버 오류", status=400)
|
||||||
worker.process_once(st2, _FakeApi(_WorkerClient({"product": _PRODUCT}, fail_put=boom)))
|
worker.process_once(st2, api2)
|
||||||
assert st2.finished[0]["status"] == store.STATUS_FAILED
|
assert st2.schedules[sid2]["status"] == store.STATUS_FAILED
|
||||||
assert any(a["result"] == "FAIL" for a in st2.audits)
|
assert any(a["result"] == "FAIL" for a in st2.audits)
|
||||||
|
|
||||||
|
|
||||||
def test_worker_missing_revision_is_failure_not_crash():
|
def test_worker_missing_revision_is_failure_not_crash():
|
||||||
st = _FakeStore([_schedule_row(revision_id=999, retry_count=store.MAX_RETRY)])
|
st, _cafe, api, sid, _ = _worker_env(revision_id=999, retry_count=store.MAX_RETRY)
|
||||||
worker.process_once(st, _FakeApi(_WorkerClient({"product": _PRODUCT})))
|
worker.process_once(st, api)
|
||||||
assert st.finished[0]["status"] == store.STATUS_FAILED
|
assert st.schedules[sid]["status"] == store.STATUS_FAILED
|
||||||
assert "999" in st.finished[0]["error"]
|
assert "999" in st.schedules[sid]["last_error"]
|
||||||
|
|
||||||
|
|
||||||
def test_worker_stops_when_nothing_due():
|
def test_worker_stops_when_nothing_due():
|
||||||
st = _FakeStore([])
|
st = fakes.MemoryStore()
|
||||||
assert worker.process_once(st, _FakeApi(_WorkerClient())) == 0
|
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 읽기 지연 보정 — 마지막 쓰기가 권위
|
# 카페24 읽기 지연 보정 — 마지막 쓰기가 권위
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -1185,7 +1289,8 @@ def test_upload_images_and_variants_wrappers():
|
|||||||
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
assert products.list_variants(client, 7) == [{"variant_code": "P000000R000A"}]
|
||||||
assert products.get_options(client, 7)["has_option"] == "T"
|
assert products.get_options(client, 7)["has_option"] == "T"
|
||||||
assert products.update_variants(client, 7, [{"variant_code": "P000000R000A", "display": "F"}]) == [
|
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]
|
sent = [c for c in client.calls if c[0] == "PUT"][-1]
|
||||||
assert sent[2]["requests"][0]["variant_code"] == "P000000R000A"
|
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"") == {}
|
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():
|
def _run_all():
|
||||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||||
for fn in fns:
|
for fn in fns:
|
||||||
|
|||||||
+223
-119
@@ -8,14 +8,28 @@
|
|||||||
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 그대로 무너진다.
|
||||||
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
compose 서비스 `dbx-cafe24-worker` 가 web 과 같은 이미지로 이 모듈을 돌린다.
|
||||||
|
|
||||||
한 번에 한 건씩 처리한다
|
한 번에 한 건씩, lease 로 잡는다 (마이그레이션 005)
|
||||||
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잠그고 PROCESSING 으로
|
`claim_due_schedule` 이 `FOR UPDATE SKIP LOCKED` 로 한 건을 잡아 PROCESSING + lease
|
||||||
바꾼다. worker 가 실수로 두 개 떠도 같은 예약이 두 번 적용되지 않는다.
|
(만료 시각·token)로 바꾼다. worker 가 여럿이어도 같은 예약을 두 번 잡지 않는다.
|
||||||
|
카페24에 쓰기 직전 lease 를 연장해 "아직 내 것인가"를 확인하고(펜싱), 결과는
|
||||||
|
token 이 맞을 때만 남긴다 — 만료 뒤 늦게 끝난 worker 가 남의 결과를 덮지 않는다.
|
||||||
|
|
||||||
적용 순서는 화면 편집과 같다
|
적용 순서는 화면 편집과 같다 (writes.write_product 공용)
|
||||||
카페24 현재값 재조회 → BACKUP revision → PUT → SUCCESS + 감사로그
|
상품 잠금 → 카페24 현재값 재조회 → 유효 현재값(읽기 지연 보정) → BACKUP
|
||||||
실패하면 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시 시도하고,
|
→ 시도 기록 → PUT → 버전(SCHEDULED)·스냅샷 기록
|
||||||
소진되면 FAILED 로 확정한다. 되돌리기는 쓰지 않는다.
|
예약 직전 백업도 읽기 지연을 보정한 값이다(카페24가 아직 옛 HTML 을 돌려줘도
|
||||||
|
그것을 "직전 내용"으로 남기지 않는다). 백업의 source 로 관측값/확인된 적용값을 구분한다.
|
||||||
|
|
||||||
|
결과 분류
|
||||||
|
카페24가 거절 → 재시도 예산(store.MAX_RETRY) 안에서 간격을 두고 다시, 소진되면 FAILED
|
||||||
|
반영 여부 모름 → NEEDS_REVIEW (자동 재적용 금지 — 사람이 쇼핑몰을 보고 확정)
|
||||||
|
반영 성공·기록 실패 → SUCCESS + "기록 복구 필요" 메모. 기록은 다음 주기에 채운다(재적용 없음)
|
||||||
|
같은 상품을 다른 작업이 쓰는 중 → 재시도 횟수를 쓰지 않고 잠시 뒤 다시
|
||||||
|
|
||||||
|
중단 복구 (recover)
|
||||||
|
lease 가 만료된 PROCESSING 은 그 예약의 마지막 쓰기 시도를 보고 판정한다
|
||||||
|
(store.recovery_decision). 무조건 PENDING 으로 돌리지 않는다 — 카페24에 이미 반영됐을
|
||||||
|
수 있기 때문이다. 카페24 현재값이 예약 결과와 같으면 반영된 것으로 확정한다.
|
||||||
|
|
||||||
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
토큰 갱신은 TokenService 가 행 잠금 안에서 하므로 web 과 동시에 떠 있어도 안전하다.
|
||||||
"""
|
"""
|
||||||
@@ -25,6 +39,7 @@ from __future__ import annotations
|
|||||||
import argparse
|
import argparse
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import socket
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
@@ -33,141 +48,230 @@ from typing import Any
|
|||||||
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
|
||||||
from app.timezone import now_kst
|
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")
|
logger = logging.getLogger("cafe24.worker")
|
||||||
|
|
||||||
ACTOR = "SCHEDULER"
|
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:
|
def lease_seconds() -> int:
|
||||||
"""예약 1건 적용. 성공 시 사람이 읽을 요약 문자열."""
|
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"])
|
schedule_id = int(row["id"])
|
||||||
product_no = int(row["product_no"])
|
product_no = int(row["product_no"])
|
||||||
|
token = str(row.get("lease_token") or "")
|
||||||
|
lease = lease_seconds()
|
||||||
revision_id = row.get("revision_id")
|
revision_id = row.get("revision_id")
|
||||||
set_display = row.get("set_display")
|
set_display = row.get("set_display")
|
||||||
set_selling = row.get("set_selling")
|
set_selling = row.get("set_selling")
|
||||||
|
|
||||||
html: str | None = None
|
def fence() -> bool:
|
||||||
if revision_id:
|
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
|
||||||
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} 의 내용이 비어 있습니다.")
|
|
||||||
|
|
||||||
# 상세설명을 바꿀 때는 쓰기 직전 현재값을 읽어 백업한다(로컬 값을 믿지 않는다).
|
try:
|
||||||
backup_id = 0
|
html: str | None = None
|
||||||
if html is not None:
|
if revision_id:
|
||||||
current = products.fetch_descriptions(api.client, product_no)
|
revision = st.get_revision(int(revision_id))
|
||||||
backup_id = store_db.add_revision(
|
if not revision:
|
||||||
product_no=product_no,
|
raise Cafe24Error(f"예약이 가리키는 버전 {revision_id} 을 찾을 수 없습니다.")
|
||||||
html_content=current.description,
|
html = str(revision.get("html_content") or "")
|
||||||
revision_type=store.REVISION_BACKUP,
|
if not html.strip():
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업",
|
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
|
||||||
created_by=ACTOR,
|
with writes.write_lock(
|
||||||
)
|
st, writes.product_lock_key(product_no), actor=ACTOR,
|
||||||
if current.mobile_description and current.mobile_description != current.description:
|
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
|
||||||
store_db.add_revision(
|
) as lock:
|
||||||
product_no=product_no,
|
outcome = writes.write_product(
|
||||||
html_content=current.mobile_description,
|
st, api, product_no,
|
||||||
revision_type=store.REVISION_BACKUP,
|
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
|
||||||
memo=f"예약 #{schedule_id} 적용 직전 자동 백업 (모바일)",
|
set_display=set_display, set_selling=set_selling,
|
||||||
created_by=ACTOR,
|
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 은 보내지 않고
|
note = ""
|
||||||
# separated_mobile_description="F" 로 "PC 상세설명과 동일"을 강제한다.
|
if outcome.record_error:
|
||||||
# (mobile_description 을 직접 보내면 카페24가 그 설정을 "직접 등록"으로 바꿔버린다.)
|
note = f"카페24 반영 성공 · 로컬 기록 실패(자동 복구 예정, 재적용 안 함): {outcome.record_error}"
|
||||||
updated = products.update_product(
|
done = st.finish_schedule(schedule_id, token=token, status=store.STATUS_SUCCESS, error=note)
|
||||||
api.client,
|
if not done:
|
||||||
product_no,
|
# 반영은 됐다. 결과를 못 남겼어도 lease 만료 후 recover 가 시도 기록(REMOTE_OK/RECORDED)을
|
||||||
description=html,
|
# 보고 SUCCESS 로 확정한다 — 다시 적용하지 않는다.
|
||||||
separated_mobile_description="F" if html is not None else None,
|
logger.warning("예약 #%s 적용됨 — 결과 기록 실패(lease 잃음). 복구 단계가 확정합니다.", schedule_id)
|
||||||
display=set_display,
|
summary = _summary(row)
|
||||||
selling=set_selling,
|
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 의 읽기 지연에
|
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
|
||||||
# 흔들리지 않게 한다(routes_products._load_product 가 덮어씌운다).
|
return store.STATUS_SUCCESS
|
||||||
if isinstance(updated, dict) and updated.get("product_no"):
|
|
||||||
|
|
||||||
|
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:
|
try:
|
||||||
store_db.save_write_snapshot(product_no, "product", store.product_snapshot(updated))
|
with writes.write_lock(st, writes.product_lock_key(int(row["product_no"])), actor=ACTOR,
|
||||||
except Exception: # noqa: BLE001 — 스냅샷 실패가 예약 결과를 바꾸면 안 된다.
|
purpose=f"예약 #{schedule_id} 복구 확인", wait_seconds=0):
|
||||||
logger.exception("예약 #%s 상품 %s 스냅샷 저장 실패", schedule_id, product_no)
|
if _verify_attempt(st, api, attempt):
|
||||||
if html is not None:
|
st.update_attempt(int(attempt["id"]), status=store.ATTEMPT_REMOTE_OK, remote_ok=True,
|
||||||
# 화면 편집(apply)과 동일 — 카페24 관리자 API 의 쓰기 직후 읽기 지연을
|
resolved_by="auto:카페24 값이 예약 결과와 같음",
|
||||||
# 여기서 짧게 흡수한다(쇼핑몰에는 바로 반영되지만 관리자 조회만 뒤쳐질 때가 있다).
|
only_from=(store.ATTEMPT_STARTED, store.ATTEMPT_UNKNOWN))
|
||||||
# 확인이 안 돼도 실패가 아니다 — 화면은 마지막 쓰기(SCHEDULED revision)를 기준으로
|
decision, note = store.RECOVER_RECORD, "중단 복구: 카페24 현재값이 예약 결과와 같아 반영됨으로 확정"
|
||||||
# 그린다. 여기서 SCHEDULED revision 을 남겨야 그 기준이 생긴다.
|
except writes.WriteBusy:
|
||||||
products.wait_for_description(api.client, product_no, html)
|
pass # 다음 주기에 다시 — 판정은 REVIEW 로 남긴다
|
||||||
store_db.add_revision(
|
if decision == store.RECOVER_RECORD and attempt:
|
||||||
product_no=product_no,
|
try:
|
||||||
html_content=html,
|
writes.record_attempt(st, attempt)
|
||||||
revision_type=store.REVISION_SCHEDULED,
|
except Exception as exc: # noqa: BLE001 — 반영은 됐다. 기록은 다음 주기에.
|
||||||
memo=f"예약 #{schedule_id} 적용",
|
logger.exception("예약 #%s 복구 중 버전 기록 실패", schedule_id)
|
||||||
created_by=ACTOR,
|
note += f" (버전 기록 실패 — 자동 재시도: {type(exc).__name__})"
|
||||||
)
|
decision = store.RECOVER_SUCCESS
|
||||||
|
|
||||||
summary = store.describe_schedule_action(
|
if decision == store.RECOVER_SUCCESS:
|
||||||
has_html=html is not None, set_display=set_display, set_selling=set_selling
|
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(
|
for row in rows:
|
||||||
actor=ACTOR,
|
try:
|
||||||
action="schedule_apply",
|
recover_one(st, api, row)
|
||||||
product_no=product_no,
|
except Exception: # noqa: BLE001 — 한 건 때문에 나머지를 멈추지 않는다(lease 만료 후 다시)
|
||||||
revision_id=int(revision_id) if revision_id else None,
|
logger.exception("예약 #%s 복구 중 오류", row.get("id"))
|
||||||
schedule_id=schedule_id,
|
count += 1
|
||||||
result="SUCCESS",
|
return count
|
||||||
detail=summary + (f" (백업 {backup_id})" if backup_id else ""),
|
|
||||||
)
|
|
||||||
return summary
|
|
||||||
|
|
||||||
|
|
||||||
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
|
handled = 0
|
||||||
while True:
|
while True:
|
||||||
with store_db.claim_due_schedule(now=now_kst()) as row:
|
row = st.claim_due_schedule(now=now_kst(), owner=worker_owner(), ttl_seconds=lease_seconds())
|
||||||
if row is None:
|
if row is None:
|
||||||
return handled
|
return handled
|
||||||
# 잠금은 여기서 이미 풀렸다. 상태가 PROCESSING 이라 다른 worker 가 집지 않는다.
|
run_one(st, api, row)
|
||||||
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)
|
|
||||||
handled += 1
|
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
|
||||||
@@ -1,22 +1,604 @@
|
|||||||
"""토스쇼핑 — 판매자 API.
|
"""토스쇼핑 — 토스쇼핑 API(shopping-fep).
|
||||||
|
|
||||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
문서: https://shopping-docs.toss.im/dev (전체 목록 llms.txt, 각 쪽 주소 뒤에 .md 를 붙이면 원문)
|
||||||
|
|
||||||
|
인증(공식 방식): 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > 자체 개발 → [키 발급](호출 IP 입력) →
|
||||||
|
Access Key·Secret Key. OAuth2 client_credentials 로 토큰을 받는다.
|
||||||
|
POST https://oauth2.cert.toss.im/token (form: grant_type=client_credentials, client_id=Access Key,
|
||||||
|
client_secret=Secret Key, scope=toss-shopping-fep:write)
|
||||||
|
응답 expires_in 은 약 1년 — 매번 새로 받으면 이용이 제한될 수 있어(문서 안내) 암호화 저장해 두고 재사용,
|
||||||
|
401 이면 한 번만 새로 받는다. **키 발급 때 넣은 IP(이 서버 외부 IP)에서만 호출된다.**
|
||||||
|
API 는 https://shopping-fep.toss.im, 헤더 Authorization: Bearer {token}. HTTP 200 + resultType FAIL 로 오류를 준다.
|
||||||
|
호출 제한: 셀러·API 별 읽기 초당 50회(넘으면 TOO_MANY_REQUEST).
|
||||||
|
|
||||||
|
매출 = 토스쇼핑 파트너스 "순 거래액" = 매출 − 환불(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 17,700).
|
||||||
|
- 매출 SALE — 주문 내역 조회 GET /api/v3/shopping-fep/orders/v2?startDate=&endDate=&limit=50&nextCursor=
|
||||||
|
(한 번에 31일까지, 상태 생략 = 전체 상태, 커서 페이지). 줄 = 주문상품(orderProductId), 묶음 = 주문(orderId).
|
||||||
|
주문 하나 = 사건 하나(`toss:{orderId}`), 날짜 = 주문 시각(orderedAt, 한국 날짜 — 토스쇼핑은 주문 = 결제),
|
||||||
|
금액 = 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. 할인(totalDiscountPrice = 토스쇼핑 할인 + 토스페이 할인)은
|
||||||
|
discount_amount 로만 보관. 결제 전(BEFORE_PAYMENT)만 빼고 결제 뒤 취소·반품도 주문일 매출에 둔다(화면 "매출"도 환불 전 금액).
|
||||||
|
- 환불 CANCEL/RETURN — 환불일에 뺀다. 주문상품 하나에 한 번(사건 ID `toss:R{orderProductId}`). `merge_refunds`:
|
||||||
|
① 클레임 목록 GET /api/v3/shopping-fep/claims(날짜 조건이 없어 전체를 넘긴다)의 환불 완료(isRefunded) CANCEL·RETURN —
|
||||||
|
날짜 = refundedDt(한국 날짜). 반품은 이것뿐(주문 내역엔 반품 완료 날짜가 없다).
|
||||||
|
② 클레임이 없는 결제취소 — 주문 내역의 canceledAt(한국 날짜). 결제완료 단계의 고객 취소는 클레임이 생기지 않는다(문서).
|
||||||
|
기간보다 CANCEL_LOOKBACK_DAYS(90)일 앞 주문까지 불러 다른 날 주문을 기간 안에 취소한 것도 잡는다.
|
||||||
|
금액 = 그 주문상품의 price(판매가 × 수량, 매출과 같은 기준), 주문 내역에 없으면(90일보다 오래된 주문) 클레임 order.price.
|
||||||
|
9/6 실데이터: 9/5 주문(276435356)을 9/6 취소 11,900 — 클레임(CANCEL/COMPLETED)·canceledAt 둘 다 9/6 = 화면 환불 11,900.
|
||||||
|
정산 건별(settlement-steps)의 REFUND 는 이 취소를 담지 않아(구매확정 전 취소는 정산에 안 올라옴) 쓰지 않는다.
|
||||||
|
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 날짜별 매출·환불·순 거래액과 환불 출처별(정산·취소 시각·클레임) 비교.
|
||||||
|
- 구매자·수령인 이름·연락처·주소·요청사항은 저장하지 않는다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .base import CredentialField, MarketplaceAdapter
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from .base import (
|
||||||
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
|
ApiError,
|
||||||
|
AuthFailed,
|
||||||
|
CredentialField,
|
||||||
|
MarketplaceAdapter,
|
||||||
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
|
TokenExpired,
|
||||||
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
|
TOKEN_URL = "https://oauth2.cert.toss.im/token"
|
||||||
|
HOST = "https://shopping-fep.toss.im"
|
||||||
|
ORDERS_PATH = "/api/v3/shopping-fep/orders/v2"
|
||||||
|
SETTLEMENT_PATH = "/api/v3/shopping-fep/settlement-steps"
|
||||||
|
SETTLEMENT_SIZE = 100 # 문서 1~100
|
||||||
|
SCOPE = "toss-shopping-fep:write"
|
||||||
|
EVENT_PREFIX = "toss:"
|
||||||
|
PAGE_SIZE = 50 # 문서 최대 50
|
||||||
|
WINDOW_DAYS = 31 # 한 번에 31일까지
|
||||||
|
MAX_PAGES = 2000 # 한 구간 10만 건 — 무한 반복 방지
|
||||||
|
TOKEN_MARGIN_SEC = 3600 # 만료 1시간 전이면 새로 받는다(토큰은 약 1년)
|
||||||
|
CALL_INTERVAL_SEC = 0.1 # 읽기 초당 50회 제한 — 넉넉히
|
||||||
|
RETRY_429 = 3
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
KST = timezone(timedelta(hours=9))
|
||||||
|
|
||||||
|
# 결제 전 주문만 매출에서 뺀다. 결제 뒤 취소·반품은 주문일 매출에 두고 원본 확인 표에 참고로 따로 보인다.
|
||||||
|
EXCLUDED_STATUS = frozenset({"BEFORE_PAYMENT"})
|
||||||
|
CLAIMED_STATUS = frozenset({"CANCELED_PAYMENT", "COMPLETED_RETURN"})
|
||||||
|
STATUS_KO = {
|
||||||
|
"BEFORE_PAYMENT": "결제전", "PAID": "결제완료", "PREPARING_PRODUCT": "상품준비중", "DELIVERING": "배송중",
|
||||||
|
"DELIVERED": "배송완료", "CONFIRMED_ORDER": "구매확정", "CLAIM_REQUESTED_CANCEL": "취소요청",
|
||||||
|
"CANCELED_PAYMENT": "결제취소", "CLAIM_REJECTED_CANCEL": "취소거절", "REQUESTED_EXCHANGE": "교환요청",
|
||||||
|
"ONGOING_EXCHANGE": "교환중", "COMPLETED_EXCHANGE": "교환완료", "CLAIM_REJECTED_EXCHANGE": "교환거절",
|
||||||
|
"REQUESTED_RETURN": "반품요청", "ONGOING_RETURN": "반품중", "COMPLETED_RETURN": "반품완료",
|
||||||
|
"CLAIM_REJECTED_RETURN": "반품거절", "CLAIM_COLLECTING": "수거중", "CLAIM_COLLECTED": "수거완료",
|
||||||
|
"CLAIM_DELIVERING": "재배송중",
|
||||||
|
}
|
||||||
|
# 원본 데이터 확인에서 값을 숨기는 항목(개인정보·자유 입력)
|
||||||
|
PERSONAL_KEYS = frozenset({
|
||||||
|
"ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone",
|
||||||
|
"address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber",
|
||||||
|
# 클레임 목록(order.* · 수거 주소 · 요청 사유 자유 입력 · 첨부 사진)
|
||||||
|
"ordererPhoneNumber", "receiverPhoneNumber", "returnAddress", "requestReason", "requestDetailReason",
|
||||||
|
"requestImages[]",
|
||||||
|
})
|
||||||
|
CLAIMS_PATH = "/api/v3/shopping-fep/claims"
|
||||||
|
CLAIM_PAGE_SIZE = 100
|
||||||
|
CLAIM_MAX_PAGES = 100 # 클레임 목록은 날짜로 못 거른다(전체를 넘긴다) — 1만 건까지
|
||||||
|
CANCEL_LOOKBACK_DAYS = 90 # 환불 후보(주문 취소 시각): 이만큼 전 주문까지 본다
|
||||||
|
|
||||||
|
|
||||||
|
def _won(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||||
|
except ValueError:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def kst_day(value: Any) -> date | None:
|
||||||
|
"""주문 시각 → 한국 날짜. 시간대가 붙어 있으면(Z, +00:00 …) 한국 시간으로 바꾸고, 없으면 한국 시간으로 본다."""
|
||||||
|
s = str(value or "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is not None:
|
||||||
|
dt = dt.astimezone(KST)
|
||||||
|
return dt.date()
|
||||||
|
|
||||||
|
|
||||||
|
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||||
|
"""주문상품 → 주문 하나로 합침(주문일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||||
|
금액 = price(판매가 × 수량) 합(할인 전, 배송비 제외). 할인·배송비·취소/반품분은 참고용으로 모은다.
|
||||||
|
배송비는 묶음(deliveryFeeGroupId)마다 한 번만 센다."""
|
||||||
|
orders: dict[str, dict[str, Any]] = {}
|
||||||
|
ship_groups: set[str] = set()
|
||||||
|
for it in items:
|
||||||
|
oid = str(it.get("orderId") or "")
|
||||||
|
day = kst_day(it.get("orderedAt"))
|
||||||
|
status = str(it.get("orderProductStatus") or "")
|
||||||
|
if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
|
||||||
|
continue
|
||||||
|
o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||||
|
"discount": 0, "names": [], "opt": "", "statuses": []})
|
||||||
|
price = _won(it.get("price"))
|
||||||
|
o["amount"] += price
|
||||||
|
if status in CLAIMED_STATUS:
|
||||||
|
o["claimed"] += price
|
||||||
|
group = str(it.get("deliveryFeeGroupId") or f"{oid}-{it.get('orderProductId')}")
|
||||||
|
if group not in ship_groups:
|
||||||
|
ship_groups.add(group)
|
||||||
|
o["ship"] += _won(it.get("deliveryFee"))
|
||||||
|
o["qty"] += _won(it.get("quantity"))
|
||||||
|
o["discount"] += _won(it.get("totalDiscountPrice"))
|
||||||
|
name = str(it.get("productName") or "")
|
||||||
|
if name and name not in o["names"]:
|
||||||
|
o["names"].append(name)
|
||||||
|
o["opt"] = o["opt"] or str(it.get("optionName") or "")
|
||||||
|
if status and status not in o["statuses"]:
|
||||||
|
o["statuses"].append(status)
|
||||||
|
return orders
|
||||||
|
|
||||||
|
|
||||||
|
def refund_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""정산 건별 목록 → 환불(stepType REFUND) 상품 줄만, 환불일(transactionTs 한국 날짜)이 [start, end] 인 것.
|
||||||
|
금액은 양수로(사건에서 − 를 붙인다). 배송비 줄(orderProductId 없음)은 매출에 배송비를 넣지 않으므로 뺀다."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
if str(it.get("stepType") or "") != "REFUND" or not it.get("orderProductId") or not it.get("orderId"):
|
||||||
|
continue
|
||||||
|
day = kst_day(it.get("transactionTs"))
|
||||||
|
if day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
amount = abs(_won(it.get("orderProductPrice"))) or abs(_won(it.get("stockPrice"))) * max(1, _won(it.get("quantity")))
|
||||||
|
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it["orderProductId"]),
|
||||||
|
"_day": day, "_ts": str(it.get("transactionTs") or ""), "amount": amount,
|
||||||
|
"qty": _won(it.get("quantity")), "name": str(it.get("displayProductName") or ""),
|
||||||
|
"order_day": kst_day(it.get("originTransactionTs"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 후보 — 주문 내역의 취소 시각(canceledAt 한국 날짜)이 [start, end] 인 주문상품. 금액 = price(판매가 × 수량)."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
day = kst_day(it.get("canceledAt"))
|
||||||
|
if not it.get("orderId") or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
status = str(it.get("orderProductStatus") or "")
|
||||||
|
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it.get("orderProductId") or ""), "_day": day,
|
||||||
|
"amount": _won(it.get("price")), "status": status, "note": STATUS_KO.get(status, status),
|
||||||
|
"order_day": kst_day(it.get("orderedAt"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def claim_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 후보 — 클레임 목록의 환불 완료(isRefunded, refundedDt 한국 날짜)가 [start, end] 인 것.
|
||||||
|
금액 = order.price(문서: "상품 가격" — 수량을 곱한 값인지 실데이터로 확인), 수량은 note 에."""
|
||||||
|
out = []
|
||||||
|
for it in items:
|
||||||
|
day = kst_day(it.get("refundedDt"))
|
||||||
|
order = it.get("order") if isinstance(it.get("order"), dict) else {}
|
||||||
|
product = it.get("product") if isinstance(it.get("product"), dict) else {}
|
||||||
|
if not it.get("isRefunded") or day is None or not (start <= day <= end) or not order.get("id"):
|
||||||
|
continue
|
||||||
|
out.append({"orderId": str(order["id"]), "orderProductId": str(order.get("orderProductId") or ""), "_day": day,
|
||||||
|
"amount": _won(order.get("price")), "note": f"{it.get('type') or '?'}/{it.get('status') or '?'} · "
|
||||||
|
f"수량 {_won(product.get('quantity'))}", "order_day": kst_day(order.get("createdDt"))})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def merge_refunds(order_items: Iterable[dict[str, Any]], claims: Iterable[dict[str, Any]],
|
||||||
|
start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""환불 규칙 — 클레임 환불 완료(CANCEL·RETURN, refundedDt) + 클레임이 없는 결제취소(canceledAt), 주문상품마다 한 번.
|
||||||
|
금액은 주문 내역의 price(판매가 × 수량)를 우선(없으면 클레임 order.price). 날짜가 [start, end] 인 것만.
|
||||||
|
클레임이 있는 주문상품은 그 클레임 날짜만 쓴다(기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 바뀌지 않게)."""
|
||||||
|
order_items = list(order_items)
|
||||||
|
by_op = {str(it.get("orderProductId")): it for it in order_items if it.get("orderProductId")}
|
||||||
|
out: dict[str, dict[str, Any]] = {}
|
||||||
|
claimed_ops: set[str] = set()
|
||||||
|
for c in claims:
|
||||||
|
order = c.get("order") if isinstance(c.get("order"), dict) else {}
|
||||||
|
product = c.get("product") if isinstance(c.get("product"), dict) else {}
|
||||||
|
kind = str(c.get("type") or "")
|
||||||
|
op = str(order.get("orderProductId") or "")
|
||||||
|
if not c.get("isRefunded") or kind not in ("CANCEL", "RETURN") or not order.get("id") or not op:
|
||||||
|
continue
|
||||||
|
claimed_ops.add(op)
|
||||||
|
day = kst_day(c.get("refundedDt"))
|
||||||
|
if day is None or not (start <= day <= end) or op in out:
|
||||||
|
continue
|
||||||
|
it = by_op.get(op) or {}
|
||||||
|
out[op] = {"orderId": str(order["id"]), "orderProductId": op, "_day": day, "type": kind,
|
||||||
|
"amount": _won(it["price"]) if "price" in it else _won(order.get("price")),
|
||||||
|
"qty": _won(it.get("quantity")) or _won(product.get("quantity")),
|
||||||
|
"name": str(it.get("productName") or product.get("name") or ""),
|
||||||
|
"order_day": kst_day(it.get("orderedAt") or order.get("createdDt"))}
|
||||||
|
for r in cancel_rows(order_items, start, end):
|
||||||
|
op = r["orderProductId"]
|
||||||
|
if not op or op in claimed_ops or op in out or r["status"] != "CANCELED_PAYMENT":
|
||||||
|
continue
|
||||||
|
it = by_op.get(op) or {}
|
||||||
|
out[op] = {"orderId": r["orderId"], "orderProductId": op, "_day": r["_day"], "type": "CANCEL",
|
||||||
|
"amount": r["amount"], "qty": _won(it.get("quantity")), "name": str(it.get("productName") or ""),
|
||||||
|
"order_day": kst_day(it.get("orderedAt"))}
|
||||||
|
return sorted(out.values(), key=lambda x: (x["_day"], x["orderId"], x["orderProductId"]))
|
||||||
|
|
||||||
|
|
||||||
|
def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값·합계 숨김)."""
|
||||||
|
fields = field_summary([flatten(r) for r in rows])
|
||||||
|
for f in fields:
|
||||||
|
if f["name"].rsplit(".", 1)[-1] in PERSONAL_KEYS:
|
||||||
|
f["personal"], f["sample"], f["sum"] = True, "", None
|
||||||
|
return fields
|
||||||
|
|
||||||
|
|
||||||
class TossAdapter(MarketplaceAdapter):
|
class TossAdapter(MarketplaceAdapter):
|
||||||
code = "toss"
|
code = "toss"
|
||||||
name = "토스쇼핑"
|
name = "토스쇼핑"
|
||||||
auth_type = "api_key"
|
auth_type = "oauth"
|
||||||
note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다."
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://shopping-docs.toss.im/dev"
|
||||||
|
note = ("토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발에서 발급한 Access Key·Secret Key 를 입력합니다. "
|
||||||
|
"키 발급 때 이 서버의 외부 IP 를 등록해야 호출됩니다.")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
# 키 이름(api_key·api_secret)은 처음 만든 입력칸 그대로 — 이미 저장한 값이 이어진다.
|
||||||
return [
|
return [
|
||||||
CredentialField("seller_id", "판매자 ID"),
|
CredentialField("api_key", "Access Key", secret=True,
|
||||||
CredentialField("api_key", "API Key", secret=True),
|
help="토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발의 Access Key"),
|
||||||
CredentialField("api_secret", "API Secret", secret=True, required=False),
|
CredentialField("api_secret", "Secret Key", secret=True,
|
||||||
|
help="같은 화면의 Secret Key"),
|
||||||
|
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||||
|
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# ── 인증 ──────────────────────────────────────────────
|
||||||
|
def _token(self, ctx: AdapterContext, *, force: bool = False) -> str:
|
||||||
|
"""저장된 토큰이 1시간 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
|
||||||
|
if not force:
|
||||||
|
tok = ctx.credentials.get("access_token")
|
||||||
|
try:
|
||||||
|
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
||||||
|
except ValueError:
|
||||||
|
exp = 0.0
|
||||||
|
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
|
||||||
|
return tok
|
||||||
|
return self._issue_token(ctx)
|
||||||
|
|
||||||
|
def _issue_token(self, ctx: AdapterContext) -> str:
|
||||||
|
import httpx # 지연 import
|
||||||
|
|
||||||
|
access_key = ctx.credentials.get("api_key").strip()
|
||||||
|
secret_key = ctx.credentials.get("api_secret").strip()
|
||||||
|
if not access_key or not secret_key:
|
||||||
|
raise NotConfigured("Access Key 와 Secret Key 를 입력하세요.")
|
||||||
|
form = {"grant_type": "client_credentials", "client_id": access_key, "client_secret": secret_key,
|
||||||
|
"scope": SCOPE}
|
||||||
|
try:
|
||||||
|
res = httpx.post(TOKEN_URL, data=form, timeout=ctx.timeout_sec,
|
||||||
|
headers={"Accept": "application/json; charset=UTF-8"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"토스 인증 서버 연결 실패: {type(exc).__name__}") from None
|
||||||
|
body = self._json(res)
|
||||||
|
if res.status_code >= 400 or not body.get("access_token"):
|
||||||
|
msg = self._err_text(body, res)
|
||||||
|
if res.status_code in (400, 401, 403):
|
||||||
|
raise AuthFailed(f"토스쇼핑 토큰 발급 실패({res.status_code}): {msg}. Access Key·Secret Key 와 "
|
||||||
|
"키 발급 때 등록한 IP(이 서버 외부 IP)를 확인하세요.")
|
||||||
|
raise ApiError(f"토스쇼핑 토큰 발급 오류({res.status_code}): {msg}")
|
||||||
|
tok = str(body["access_token"])
|
||||||
|
expires_in = _won(body.get("expires_in")) or 24 * 3600
|
||||||
|
ctx.credentials.set("access_token", tok)
|
||||||
|
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
||||||
|
return tok
|
||||||
|
|
||||||
|
def authenticate(self, ctx: AdapterContext) -> None:
|
||||||
|
super().authenticate(ctx)
|
||||||
|
self._token(ctx)
|
||||||
|
|
||||||
|
def refresh_token(self, ctx: AdapterContext) -> None:
|
||||||
|
self._token(ctx, force=True)
|
||||||
|
|
||||||
|
# ── 호출 ──────────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _json(res: Any) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
body = res.json()
|
||||||
|
except ValueError:
|
||||||
|
return {}
|
||||||
|
return body if isinstance(body, dict) else {"data": body}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||||
|
err = body.get("error")
|
||||||
|
if isinstance(err, dict):
|
||||||
|
parts = [str(err.get(k)) for k in ("errorCode", "errorType", "reason", "message") if err.get(k)]
|
||||||
|
else:
|
||||||
|
parts = [str(body.get(k)) for k in ("error", "error_description", "code", "message") if body.get(k)]
|
||||||
|
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""GET — 호출 간격 유지, 429·TOO_MANY_REQUEST 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더.
|
||||||
|
성공이면 success 내용을 돌려준다(토스쇼핑은 HTTP 200 + resultType FAIL 로도 오류를 준다)."""
|
||||||
|
import httpx # 지연 import
|
||||||
|
|
||||||
|
retried_auth = False
|
||||||
|
for attempt in range(RETRY_429 + 1):
|
||||||
|
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||||
|
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(wait)
|
||||||
|
headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"}
|
||||||
|
try:
|
||||||
|
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"토스쇼핑 API 연결 실패: {type(exc).__name__}") from None
|
||||||
|
finally:
|
||||||
|
self._last_call = time.monotonic()
|
||||||
|
body = self._json(res)
|
||||||
|
err = body.get("error") if isinstance(body.get("error"), dict) else {}
|
||||||
|
limited = res.status_code == 429 or "TOO_MANY" in str(err.get("errorCode") or err.get("errorType") or "")
|
||||||
|
if limited and attempt < RETRY_429:
|
||||||
|
time.sleep(1.0 * (2 ** attempt))
|
||||||
|
continue
|
||||||
|
if res.status_code == 401 and not retried_auth:
|
||||||
|
retried_auth = True
|
||||||
|
self._token(ctx, force=True)
|
||||||
|
continue
|
||||||
|
if res.status_code == 401:
|
||||||
|
raise TokenExpired(f"토스쇼핑 인증 만료·거부(401): {self._err_text(body, res)}")
|
||||||
|
if res.status_code == 403:
|
||||||
|
raise AuthFailed(f"토스쇼핑 권한 거부(403): {self._err_text(body, res)}. 키 발급 때 등록한 IP"
|
||||||
|
"(이 서버 외부 IP)를 확인하세요.")
|
||||||
|
if limited:
|
||||||
|
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
if res.status_code >= 400:
|
||||||
|
raise ApiError(f"토스쇼핑 API 오류({res.status_code}): {self._err_text(body, res)}")
|
||||||
|
if body.get("resultType") == "FAIL":
|
||||||
|
raise ApiError(f"토스쇼핑 API 오류: {self._err_text(body, res)}")
|
||||||
|
success = body.get("success")
|
||||||
|
return success if isinstance(success, dict) else {}
|
||||||
|
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _window_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||||
|
"""조회 기간 [a, b](31일 이하)의 주문상품 전체 — 모든 상태, 커서로 끝까지."""
|
||||||
|
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
cursor = None
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
|
||||||
|
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
cursor = body.get("nextCursor")
|
||||||
|
if not cursor or not rows:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||||
|
"""거래일 기준 [a, b](31일 이하)의 정산 건별 줄 전체(결제·환불·배송비), nextToken 으로 끝까지."""
|
||||||
|
params: dict[str, Any] = {"dateCondition": "TRANSACTION_DATE", "fromDate": a.isoformat(),
|
||||||
|
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = None
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = body.get("nextToken")
|
||||||
|
if not token or not rows:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||||
|
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = None
|
||||||
|
for _ in range(CLAIM_MAX_PAGES):
|
||||||
|
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = body.get("nextToken")
|
||||||
|
if not token or not rows or body.get("hasNext") is False:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _windows(start: date, end: date) -> list[tuple[date, date]]:
|
||||||
|
windows = []
|
||||||
|
a = start
|
||||||
|
while a <= end:
|
||||||
|
b = min(end, a + timedelta(days=WINDOW_DAYS - 1))
|
||||||
|
windows.append((a, b))
|
||||||
|
a = b + timedelta(days=1)
|
||||||
|
return windows
|
||||||
|
|
||||||
|
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""주문 내역(매출) — 31일 구간마다 진행 막대 한 칸(plan 은 부르는 쪽이 주문 + 정산 구간 수로 정한다)."""
|
||||||
|
for a, b in self._windows(start, end):
|
||||||
|
rows = self._window_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from rows
|
||||||
|
|
||||||
|
def _refund_items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""정산 건별(환불이 들어 있음) — 31일 구간마다 진행 막대 한 칸."""
|
||||||
|
for a, b in self._windows(start, end):
|
||||||
|
rows = self._settlement_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from rows
|
||||||
|
|
||||||
|
def _lookback_items(self, ctx: AdapterContext, start: date) -> list[dict[str, Any]]:
|
||||||
|
"""기간 앞 CANCEL_LOOKBACK_DAYS 일의 주문상품 — 다른 날 주문을 기간 안에 취소한 것을 찾는 용도."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for a, b in self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)):
|
||||||
|
rows = self._window_items(ctx, a, b)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
out.extend(rows)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _plan(self, ctx: AdapterContext, start: date, end: date, extra: int = 0) -> None:
|
||||||
|
"""진행 막대: 기간 주문 구간 + 앞 90일 주문 구간 + 클레임 목록 1단계 (+ 원본 확인의 정산 구간)."""
|
||||||
|
back = len(self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)))
|
||||||
|
ctx.progress.plan(len(self._windows(start, end)) + back + 1 + extra, "단계")
|
||||||
|
|
||||||
|
def _claims_step(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||||
|
claims = self._claims(ctx)
|
||||||
|
ctx.progress.step(items=len(claims))
|
||||||
|
return claims
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def collect(self, ctx: AdapterContext, start: date, end: date) -> tuple[int, list[SaleEvent]]:
|
||||||
|
"""매출(주문일) + 환불(환불일, merge_refunds). 주문 내역은 환불 금액·취소 시각에도 쓰여 한 번만 부른다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
self._plan(ctx, start, end)
|
||||||
|
items = list(self._items(ctx, start, end))
|
||||||
|
back = self._lookback_items(ctx, start)
|
||||||
|
claims = self._claims_step(ctx)
|
||||||
|
events: list[SaleEvent] = []
|
||||||
|
for o in group_orders(items, start, end).values():
|
||||||
|
events.extend(self.normalize_order(o))
|
||||||
|
for r in merge_refunds(back + items, claims, start, end):
|
||||||
|
events.extend(self.normalize_refund(r))
|
||||||
|
for ev in events:
|
||||||
|
ev.validate()
|
||||||
|
return len(items) + len(claims), events
|
||||||
|
|
||||||
|
def normalize_refund(self, r: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
oid, day = str(r.get("orderId") or ""), r.get("_day")
|
||||||
|
if not oid or day is None or not r.get("orderProductId"):
|
||||||
|
return []
|
||||||
|
kind = "RETURN" if r.get("type") == "RETURN" else "CANCEL"
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type=kind, external_event_id=f"{EVENT_PREFIX}R{r['orderProductId']}", external_order_id=oid,
|
||||||
|
external_line_id=str(r["orderProductId"]), event_date=day, order_date=r.get("order_day"),
|
||||||
|
amount=-abs(int(r.get("amount") or 0)), product_name=str(r.get("name") or "")[:200],
|
||||||
|
quantity=int(r.get("qty") or 0), order_status="반품 환불" if kind == "RETURN" else "취소 환불",
|
||||||
|
)]
|
||||||
|
|
||||||
|
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
oid, day = str(o.get("orderId") or ""), o.get("_day")
|
||||||
|
if not oid or day is None:
|
||||||
|
return []
|
||||||
|
names = o.get("names") or []
|
||||||
|
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||||
|
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid,
|
||||||
|
order_date=day, payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
|
||||||
|
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
|
||||||
|
discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50],
|
||||||
|
)]
|
||||||
|
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
|
# 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다.
|
||||||
|
super().authenticate(ctx)
|
||||||
|
self._token(ctx, force=True)
|
||||||
|
today = today_kst()
|
||||||
|
body = self._get(ctx, ORDERS_PATH, {"startDate": today.isoformat(), "endDate": today.isoformat(), "limit": 1})
|
||||||
|
n = len(body.get("results") or [])
|
||||||
|
more = " 이상" if body.get("nextCursor") else ""
|
||||||
|
return f"토스쇼핑 API 연결 정상(토큰 발급·주문 조회 확인, 오늘 주문상품 {n}건{more})."
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||||
|
"""기간(최대 31일)을 실제로 불러 항목별 합계·상태별 합계와 날짜별 매출·환불·순 거래액(= 저장되는 값)을 돌려준다.
|
||||||
|
환불은 출처별(클레임 환불 완료·주문 취소 시각·정산 REFUND)로도 나란히 보여 파트너스 화면과 맞춰 볼 수 있게.
|
||||||
|
개인정보 항목은 값 없이 이름만. 저장하지 않는다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||||
|
self._plan(ctx, day, to, extra=len(self._windows(day, to)))
|
||||||
|
try:
|
||||||
|
items = list(self._items(ctx, day, to))
|
||||||
|
back = self._lookback_items(ctx, day)
|
||||||
|
except AdapterError as exc:
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||||
|
{"key": "orders", "label": "주문 내역", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||||
|
by_status: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
for it in items:
|
||||||
|
by_status.setdefault(str(it.get("orderProductStatus") or "?"), []).append(it)
|
||||||
|
probes = [{"key": "orders", "label": "주문 내역(전체 상태, 주문상품 단위)", "path": ORDERS_PATH,
|
||||||
|
"ok": True, "count": len(items), "fields": summary(items)}]
|
||||||
|
for st, rows in sorted(by_status.items()):
|
||||||
|
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
|
||||||
|
+ (" — 매출 제외(결제 전)" if st in EXCLUDED_STATUS else
|
||||||
|
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""),
|
||||||
|
"path": "orderProductStatus", "ok": True, "count": len(rows),
|
||||||
|
"fields": [f for f in summary(rows) if f["sum"] is not None]})
|
||||||
|
claims_err = ""
|
||||||
|
try:
|
||||||
|
claims = self._claims_step(ctx)
|
||||||
|
probes.append({"key": "claims", "label": "클레임 목록(전체 — 날짜 조건 없음)", "path": CLAIMS_PATH, "ok": True,
|
||||||
|
"count": len(claims), "fields": summary(claims)})
|
||||||
|
except AdapterError as exc:
|
||||||
|
claims, claims_err = [], exc.message[:300]
|
||||||
|
probes.append({"key": "claims", "label": "클레임 목록", "path": CLAIMS_PATH, "ok": False, "error": claims_err})
|
||||||
|
settle_err = ""
|
||||||
|
try:
|
||||||
|
settle = list(self._refund_items(ctx, day, to))
|
||||||
|
probes.append({"key": "settlement", "label": "정산 건별(거래일 기준, 결제·환불·배송비 줄 전체 — 참고)",
|
||||||
|
"path": SETTLEMENT_PATH + " (TRANSACTION_DATE)", "ok": True, "count": len(settle),
|
||||||
|
"fields": summary(settle)})
|
||||||
|
except AdapterError as exc:
|
||||||
|
settle, settle_err = [], exc.message[:300]
|
||||||
|
probes.append({"key": "settlement", "label": "정산 건별(참고)", "path": SETTLEMENT_PATH, "ok": False,
|
||||||
|
"error": settle_err})
|
||||||
|
|
||||||
|
refunds = merge_refunds(back + items, claims, day, to) # 저장되는 환불(현재 규칙)
|
||||||
|
# ── 환불 출처별 — 파트너스 화면 "환불"과 맞춰 보는 용도 ──
|
||||||
|
candidates: list[dict[str, Any]] = [
|
||||||
|
{"key": "rule", "label": "적용 규칙(클레임 환불 + 클레임 없는 결제취소)", "rows": [
|
||||||
|
{**r, "note": "반품" if r["type"] == "RETURN" else "취소"}
|
||||||
|
for r in refunds], "error": claims_err},
|
||||||
|
{"key": "claims", "label": "클레임 환불 완료(refundedDt, 금액 order.price)", "rows": claim_rows(claims, day, to),
|
||||||
|
"error": claims_err},
|
||||||
|
{"key": "canceled", "label": f"주문 취소 시각(canceledAt, {CANCEL_LOOKBACK_DAYS}일 전 주문까지)",
|
||||||
|
"rows": cancel_rows(back + items, day, to), "error": ""},
|
||||||
|
{"key": "settlement", "label": "정산 REFUND 상품 줄(거래일) — 참고", "rows": [
|
||||||
|
{**r, "note": "정산 REFUND"} for r in refund_rows(settle, day, to)],
|
||||||
|
"error": settle_err},
|
||||||
|
]
|
||||||
|
for c in candidates:
|
||||||
|
c["days"] = {}
|
||||||
|
for r in c["rows"]:
|
||||||
|
k = r["_day"].isoformat()
|
||||||
|
c["days"][k] = c["days"].get(k, 0) + r["amount"]
|
||||||
|
c["rows"] = [{"date": r["_day"].isoformat(), "orderDate": r["order_day"].isoformat() if r.get("order_day") else "",
|
||||||
|
"orderId": r["orderId"], "orderProductId": r["orderProductId"],
|
||||||
|
"amount": r["amount"], "note": r.get("note") or ""}
|
||||||
|
for r in sorted(c["rows"], key=lambda x: (x["_day"], x["orderId"]))][:200]
|
||||||
|
|
||||||
|
days = []
|
||||||
|
orders = group_orders(items, day, to)
|
||||||
|
d = day
|
||||||
|
while d <= to:
|
||||||
|
day_orders = [o for o in orders.values() if o["_day"] == d]
|
||||||
|
sales = sum(o["amount"] for o in day_orders)
|
||||||
|
refund = sum(r["amount"] for r in refunds if r["_day"] == d)
|
||||||
|
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sales, "claimed": refund,
|
||||||
|
"ship": sales - refund})
|
||||||
|
d += timedelta(days=1)
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"refund_candidates": candidates,
|
||||||
|
"day_cols": {"amount": "매출(주문일)", "claimed": "환불(환불일)", "ship": "순 거래액(저장되는 매출)"},
|
||||||
|
"rule": "순 거래액 = 매출 − 환불. 매출 = 주문일(orderedAt) 기준 주문상품 price(판매가 × 수량) 합(할인 전, "
|
||||||
|
"배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외). 환불 = 클레임 환불 완료(취소·반품, refundedDt) + "
|
||||||
|
"클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 그 주문상품 price. 환불일 기준"}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
|
||||||
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
|
||||||
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
|
||||||
|
- 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨",
|
||||||
|
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -39,8 +41,17 @@ class ShopProgress(Progress):
|
|||||||
self.unit = "단계"
|
self.unit = "단계"
|
||||||
self.status = self.label = self.message = ""
|
self.status = self.label = self.message = ""
|
||||||
self.started_at = self.finished_at = 0.0
|
self.started_at = self.finished_at = 0.0
|
||||||
|
self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
def stop(self) -> bool:
|
||||||
|
"""[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True."""
|
||||||
|
with self._lock:
|
||||||
|
if self.state not in ("waiting", "running"):
|
||||||
|
return False
|
||||||
|
self.stop_requested = True
|
||||||
|
return True
|
||||||
|
|
||||||
# ── 어댑터가 부르는 쪽(Progress) ──
|
# ── 어댑터가 부르는 쪽(Progress) ──
|
||||||
def plan(self, total: int, unit: str = "단계") -> None:
|
def plan(self, total: int, unit: str = "단계") -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -52,11 +63,18 @@ class ShopProgress(Progress):
|
|||||||
|
|
||||||
def check(self) -> None:
|
def check(self) -> None:
|
||||||
if self.cancel_requested and self.state == "running":
|
if self.cancel_requested and self.state == "running":
|
||||||
raise Cancelled("사용자가 업데이트를 취소했습니다.")
|
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
|
||||||
|
"사용자가 업데이트를 취소했습니다.")
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cancel_requested(self) -> bool:
|
def cancel_requested(self) -> bool:
|
||||||
return bool(self.job is not None and self.job.cancel_requested)
|
"""멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지."""
|
||||||
|
return self.stop_requested or bool(self.job is not None and self.job.cancel_requested)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def stopped_only(self) -> bool:
|
||||||
|
"""이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다."""
|
||||||
|
return self.stop_requested and not (self.job is not None and self.job.cancel_requested)
|
||||||
|
|
||||||
def step(self, n: int = 1, *, items: int = 0) -> None:
|
def step(self, n: int = 1, *, items: int = 0) -> None:
|
||||||
self.check()
|
self.check()
|
||||||
@@ -91,7 +109,8 @@ class ShopProgress(Progress):
|
|||||||
|
|
||||||
def cancelled(self) -> None:
|
def cancelled(self) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
|
self.state, self.status = "cancelled", "cancelled"
|
||||||
|
self.message = "중지됨" if self.stopped_only else "취소됨"
|
||||||
self.finished_at = time.time()
|
self.finished_at = time.time()
|
||||||
|
|
||||||
def skip(self, message: str) -> None:
|
def skip(self, message: str) -> None:
|
||||||
@@ -118,7 +137,7 @@ class ShopProgress(Progress):
|
|||||||
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
|
||||||
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
|
||||||
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
|
||||||
"fraction": round(self.fraction(), 4),
|
"stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4),
|
||||||
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,6 +167,14 @@ class SyncJob:
|
|||||||
if not self.finished_at and not self.cancel_requested:
|
if not self.finished_at and not self.cancel_requested:
|
||||||
self.cancel_requested, self.cancelled_by = True, user
|
self.cancel_requested, self.cancelled_by = True, user
|
||||||
|
|
||||||
|
def stop_shop(self, code: str) -> bool:
|
||||||
|
"""쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False."""
|
||||||
|
with self._lock:
|
||||||
|
if self.finished_at:
|
||||||
|
return False
|
||||||
|
shop = next((s for s in self.shops if s.code == code), None)
|
||||||
|
return bool(shop is not None and shop.stop())
|
||||||
|
|
||||||
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
|
||||||
|
|||||||
@@ -115,7 +115,8 @@ def dashboard_page(
|
|||||||
def settings_page(request: Request):
|
def settings_page(request: Request):
|
||||||
from app.main import render_template # noqa: WPS433
|
from app.main import render_template # noqa: WPS433
|
||||||
|
|
||||||
g = common.guard(request, admin=True)
|
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
|
||||||
|
g = common.guard(request)
|
||||||
if not isinstance(g, tuple):
|
if not isinstance(g, tuple):
|
||||||
return g
|
return g
|
||||||
store, user = g
|
store, user = g
|
||||||
@@ -227,6 +228,25 @@ def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
|
|||||||
return JSONResponse({"job": job.snapshot()})
|
return JSONResponse({"job": job.snapshot()})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
|
||||||
|
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
|
||||||
|
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
|
||||||
|
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
from . import jobs # noqa: WPS433
|
||||||
|
|
||||||
|
_, user = common.require_store(request)
|
||||||
|
job = jobs.get_job(job_id)
|
||||||
|
if job is None:
|
||||||
|
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
|
||||||
|
if job.user and job.user != user["email"] and not is_admin(user):
|
||||||
|
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
|
||||||
|
if not job.stop_shop(code):
|
||||||
|
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
|
||||||
|
return JSONResponse({"job": job.snapshot()})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/sync/current")
|
@router.get("/api/sync/current")
|
||||||
def api_sync_current(request: Request) -> JSONResponse:
|
def api_sync_current(request: Request) -> JSONResponse:
|
||||||
common.require_store(request)
|
common.require_store(request)
|
||||||
@@ -251,7 +271,7 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
|||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# JSON API — 관리자(설정)
|
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@router.put("/api/marketplaces/{code}")
|
@router.put("/api/marketplaces/{code}")
|
||||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
@@ -267,7 +287,7 @@ def api_update_marketplace(request: Request, code: str, payload: dict[str, Any]
|
|||||||
|
|
||||||
@router.post("/api/marketplaces/{code}/rates")
|
@router.post("/api/marketplaces/{code}/rates")
|
||||||
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
store, user = common.require_store(request, admin=True)
|
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
|
||||||
try:
|
try:
|
||||||
@@ -288,14 +308,14 @@ def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...
|
|||||||
|
|
||||||
@router.get("/api/marketplaces/{code}/rates")
|
@router.get("/api/marketplaces/{code}/rates")
|
||||||
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
def api_list_rates(request: Request, code: str) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
return JSONResponse({"rates": store.list_rates(code)})
|
return JSONResponse({"rates": store.list_rates(code)})
|
||||||
|
|
||||||
|
|
||||||
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
|
||||||
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
if not store.delete_rate(code, rate_id):
|
if not store.delete_rate(code, rate_id):
|
||||||
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
|
||||||
|
|||||||
@@ -102,9 +102,9 @@ class SyncService:
|
|||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
|
||||||
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||||
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
|
if progress is not None and progress.cancel_requested: # [업데이트 취소]·쇼핑몰 [중지] 뒤 차례가 온 쇼핑몰
|
||||||
progress.cancelled()
|
progress.cancelled()
|
||||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
return {**result, "cancelled": True, "status": "cancelled", "message": progress.message}
|
||||||
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
|
||||||
if run_id is None:
|
if run_id is None:
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
@@ -140,11 +140,13 @@ class SyncService:
|
|||||||
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
|
||||||
"message": f"{upserted}건 반영"}
|
"message": f"{upserted}건 반영"}
|
||||||
except Cancelled:
|
except Cancelled:
|
||||||
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
# 수집 중 취소·중지 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
|
||||||
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
|
# 쇼핑몰 [중지]면 이 쇼핑몰만 멈추고 sync_all 이 다음 쇼핑몰로 넘어간다.
|
||||||
|
stopped = progress is not None and progress.stopped_only
|
||||||
|
self._store.finish_run(run_id, ok=False, error="쇼핑몰 중지" if stopped else "업데이트 취소")
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress.cancelled()
|
progress.cancelled()
|
||||||
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
|
return {**result, "cancelled": True, "status": "cancelled", "message": "중지됨" if stopped else "취소됨"}
|
||||||
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
|
||||||
status, message = self._failure(exc, ctx)
|
status, message = self._failure(exc, ctx)
|
||||||
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
logger.warning("performance sync %s failed: %s %s", code, status, message)
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
|
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
||||||
{% if is_admin %}
|
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
|
||||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
|
|
||||||
{% endif %}
|
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||||
|
|
||||||
{%- macro won(v) -%}
|
{%- macro won(v) -%}
|
||||||
{%- if v is none -%}<span class="perf-na"></span>
|
{%- if v is none -%}<span class="perf-na"></span>
|
||||||
@@ -239,4 +239,4 @@
|
|||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
||||||
|
|
||||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||||
|
|
||||||
@@ -8,7 +8,8 @@
|
|||||||
<section class="perf perf-settings" id="perf-settings">
|
<section class="perf perf-settings" id="perf-settings">
|
||||||
{% include "performance/_tabs.html" %}
|
{% include "performance/_tabs.html" %}
|
||||||
|
|
||||||
{% if not key_info.ok %}
|
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
|
||||||
|
{% if is_admin and not key_info.ok %}
|
||||||
<div class="perf-notice is-warn">
|
<div class="perf-notice is-warn">
|
||||||
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
|
||||||
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
|
||||||
@@ -18,26 +19,31 @@
|
|||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head">
|
<div class="perf-card-head">
|
||||||
<h2 class="perf-h">쇼핑몰 설정</h2>
|
<h2 class="perf-h">쇼핑몰 설정</h2>
|
||||||
|
{% if is_admin %}
|
||||||
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
|
||||||
|
{% else %}
|
||||||
|
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
<div class="erp-table-wrap">
|
<div class="erp-table-wrap">
|
||||||
<table class="perf-table perf-set-table">
|
<table class="perf-table perf-set-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">쇼핑몰</th>
|
<th class="perf-th-label">쇼핑몰</th>
|
||||||
<th>사용</th>
|
{% if is_admin %}<th>사용</th>
|
||||||
<th>매출 집계</th>
|
<th>매출 집계</th>{% endif %}
|
||||||
<th>수수료율</th>
|
<th>수수료율</th>
|
||||||
<th>API 설정</th>
|
{% if is_admin %}<th>API 설정</th>
|
||||||
<th>연결 상태</th>
|
<th>연결 상태</th>{% endif %}
|
||||||
<th>마지막 동기화</th>
|
<th>마지막 동기화</th>
|
||||||
<th></th>
|
{% if is_admin %}<th></th>{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for r in rows %}
|
{% for r in rows %}
|
||||||
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
|
||||||
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
<th class="perf-td-label" scope="row">{{ r.name }}</th>
|
||||||
|
{% if is_admin %}
|
||||||
<td class="perf-center">
|
<td class="perf-center">
|
||||||
<label class="perf-switch" title="사용 여부">
|
<label class="perf-switch" title="사용 여부">
|
||||||
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
|
||||||
@@ -48,11 +54,13 @@
|
|||||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||||
</label>
|
</label>
|
||||||
</td>
|
</td>
|
||||||
|
{% endif %}
|
||||||
<td class="perf-rate-cell">
|
<td class="perf-rate-cell">
|
||||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
||||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
|
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
|
||||||
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
|
||||||
</td>
|
</td>
|
||||||
|
{% if is_admin %}
|
||||||
<td>
|
<td>
|
||||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
||||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||||
@@ -65,11 +73,14 @@
|
|||||||
<i></i>{{ r.status_label }}</span>
|
<i></i>{{ r.status_label }}</span>
|
||||||
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
{% endif %}
|
||||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||||
|
{% if is_admin %}
|
||||||
<td class="perf-nowrap">
|
<td class="perf-nowrap">
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||||
</td>
|
</td>
|
||||||
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -77,10 +88,11 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="perf-foot perf-muted">
|
<p class="perf-foot perf-muted">
|
||||||
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
|
||||||
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
|
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{% if is_admin %}
|
||||||
<div class="perf-grid2">
|
<div class="perf-grid2">
|
||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||||
@@ -123,12 +135,14 @@
|
|||||||
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
||||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
||||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
||||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.</p>
|
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
||||||
|
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.</p>
|
||||||
<div class="perf-sample-form">
|
<div class="perf-sample-form">
|
||||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
||||||
<option value="naver">네이버 스마트스토어</option>
|
<option value="naver">네이버 스마트스토어</option>
|
||||||
<option value="elevenst">11번가</option>
|
<option value="elevenst">11번가</option>
|
||||||
<option value="gsshop">GS샵</option>
|
<option value="gsshop">GS샵</option>
|
||||||
|
<option value="toss">토스쇼핑</option>
|
||||||
</select>
|
</select>
|
||||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
||||||
<span class="perf-muted">~</span>
|
<span class="perf-muted">~</span>
|
||||||
@@ -174,7 +188,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -379,6 +379,279 @@ def test_sync_isolation_redaction_and_dedupe():
|
|||||||
assert r3["skipped"]
|
assert r3["skipped"]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_item(order_id, op_id, ordered_at, price, *, status="PAID", qty=1, dc=0, ship=0, group=None, name="밀폐용기"):
|
||||||
|
"""토스쇼핑 주문 내역 조회 results[] 한 줄(주문상품) — 개인정보 항목 포함(저장 안 되는지 확인용)."""
|
||||||
|
return {"orderId": order_id, "orderProductId": op_id, "orderedAt": ordered_at, "orderProductStatus": status,
|
||||||
|
"productName": name, "optionName": "3개입", "quantity": qty, "price": price, "originPrice": price,
|
||||||
|
"totalDiscountPrice": dc, "tossShoppingDiscount": dc, "tossPayDiscount": 0, "tossPayPoint": 0,
|
||||||
|
"deliveryFee": ship, "deliveryFeeGroupId": group,
|
||||||
|
"ordererName": "홍길동", "ordererPhone": "010-1234-5678", "receiverName": "홍길동",
|
||||||
|
"receiverPhone": "010-1234-5678", "address": "서울시 어딘가", "detailAddress": "101호", "zipCode": "01234",
|
||||||
|
"shippingNote": "문 앞에 두세요 010-9999-8888"}
|
||||||
|
|
||||||
|
|
||||||
|
class _TossCreds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
def set(self, k, v):
|
||||||
|
self[k] = v
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_token_and_connection():
|
||||||
|
"""토스쇼핑: Access Key·Secret Key → OAuth2 토큰(form, scope 고정) → Bearer 로 주문 내역 조회.
|
||||||
|
HTTP 200 + resultType FAIL 도 오류, 401 이면 토큰 한 번 새로 받기. 키·토큰은 오류 문구에 없음."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, AdapterError
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="ACCESS-KEY-1", api_secret="SECRET-KEY-1"))
|
||||||
|
seen = {"posts": [], "gets": []}
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
seen["posts"].append((url, dict(data)))
|
||||||
|
return httpx.Response(200, json={"access_token": f"TOKEN-{len(seen['posts'])}", "expires_in": 31535999,
|
||||||
|
"token_type": "Bearer", "scope": "toss-shopping-fep:write"})
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
seen["gets"].append((url, dict(params), headers["Authorization"]))
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {
|
||||||
|
"results": [_toss_item(1, 11, "2026-09-30T10:00:00", 12000)], "nextCursor": "c2"}})
|
||||||
|
|
||||||
|
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||||
|
try:
|
||||||
|
msg = ts.TossAdapter().test_connection(ctx)
|
||||||
|
assert "연결 정상" in msg and "1건 이상" in msg
|
||||||
|
url, form = seen["posts"][0]
|
||||||
|
assert url == "https://oauth2.cert.toss.im/token"
|
||||||
|
assert form == {"grant_type": "client_credentials", "client_id": "ACCESS-KEY-1",
|
||||||
|
"client_secret": "SECRET-KEY-1", "scope": "toss-shopping-fep:write"}
|
||||||
|
gurl, params, auth = seen["gets"][0]
|
||||||
|
assert gurl == "https://shopping-fep.toss.im/api/v3/shopping-fep/orders/v2" and auth == "Bearer TOKEN-1"
|
||||||
|
assert params["startDate"] == params["endDate"] and params["limit"] == 1
|
||||||
|
assert ctx.credentials["access_token"] == "TOKEN-1" and int(ctx.credentials["access_token_expires_at"]) > 0
|
||||||
|
# 저장된 토큰은 다시 쓴다(매번 발급하지 않음) — 401 이면 한 번만 새로 받는다
|
||||||
|
n_posts = len(seen["posts"])
|
||||||
|
statuses = iter([401, 200])
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
next(statuses), json={"resultType": "SUCCESS", "success": {"results": [], "nextCursor": None}})
|
||||||
|
assert ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) == []
|
||||||
|
assert len(seen["posts"]) == n_posts + 1 and ctx.credentials["access_token"] == f"TOKEN-{n_posts + 1}"
|
||||||
|
# HTTP 200 + resultType FAIL → API 오류
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
200, json={"resultType": "FAIL", "error": {"errorCode": "INVALID_DATE_RANGE", "reason": "조회 기간 초과"}})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1))
|
||||||
|
except AdapterError as exc:
|
||||||
|
assert exc.status == "api_error" and "INVALID_DATE_RANGE" in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("API 오류여야 합니다")
|
||||||
|
# 토큰 발급 거부 → 인증 실패(키는 문구에 없음)
|
||||||
|
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
|
||||||
|
401, json={"error": "invalid_client", "error_description": "client authentication failed"})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter().test_connection(ctx)
|
||||||
|
except AuthFailed as exc:
|
||||||
|
assert "invalid_client" in exc.message and "SECRET-KEY-1" not in exc.message
|
||||||
|
assert "ACCESS-KEY-1" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("인증 실패여야 합니다")
|
||||||
|
# 주문 조회 403(IP 미등록 등) → 인증 실패 + IP 안내, 토큰은 문구에 없음
|
||||||
|
httpx.post = post
|
||||||
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
|
403, json={"resultType": "FAIL", "error": {"errorCode": "FORBIDDEN", "reason": "허용되지 않은 IP"}})
|
||||||
|
try:
|
||||||
|
ts.TossAdapter().test_connection(ctx)
|
||||||
|
except AuthFailed as exc:
|
||||||
|
assert "허용되지 않은 IP" in exc.message and "TOKEN-" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("권한 거부여야 합니다")
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_step(step, order_id, op_id, ts, price, *, qty=1):
|
||||||
|
"""정산 건별 목록 items[] 한 줄 — op_id None = 배송비 줄."""
|
||||||
|
return {"orderId": order_id, "orderProductId": op_id, "transactionTs": ts, "originTransactionTs": "2026-08-31T16:00:00Z",
|
||||||
|
"stepType": step, "orderProductPrice": price, "stockPrice": price // max(1, qty), "quantity": qty,
|
||||||
|
"displayProductName": "밀폐용기", "orderProductStatus": "CANCELED_PAYMENT" if step == "REFUND" else "CONFIRMED_ORDER"}
|
||||||
|
|
||||||
|
|
||||||
|
def _toss_claim(cid, kind, status, order_id, op_id, price, *, refunded=None, created="2026-08-01T10:00:00", qty=1):
|
||||||
|
"""클레임 목록 items[] 한 줄 — refunded = 환불 완료 일시(없으면 미환불). 개인정보·자유 입력 항목 포함."""
|
||||||
|
return {"id": cid, "type": kind, "status": status, "isRefunded": bool(refunded), "refundedDt": refunded,
|
||||||
|
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||||
|
"order": {"id": order_id, "orderProductId": op_id, "price": price, "createdDt": created,
|
||||||
|
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||||
|
"product": {"id": 3, "name": "밀폐용기", "quantity": qty}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_collect_sales():
|
||||||
|
"""토스쇼핑 매출 = 파트너스 "순 거래액" = 매출 − 환불(9/6 화면: 29,600 − 11,900 = 17,700, 9/5 주문을 9/6 취소).
|
||||||
|
매출 = 주문 단위, 주문일(한국 날짜), 주문상품 price 합(할인 전·배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외).
|
||||||
|
환불 = 클레임 환불 완료(취소·반품, refundedDt) + 클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 주문상품 price.
|
||||||
|
기간 앞 90일 주문까지 불러 다른 날 주문의 환불도 잡는다. 31일 구간 + 커서. 구매자 정보는 저장 안 함."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
|
||||||
|
def item(*a, canceled=None, **kw):
|
||||||
|
it = _toss_item(*a, **kw)
|
||||||
|
if canceled:
|
||||||
|
it["canceledAt"] = canceled
|
||||||
|
return it
|
||||||
|
|
||||||
|
pages = {
|
||||||
|
("2026-08-01", None): ([item(1, 11, "2026-08-31T23:30:00+09:00", 20000, qty=2, dc=1000, ship=3000, group=7),
|
||||||
|
item(1, 12, "2026-08-31T23:30:00+09:00", 5000, ship=3000, group=7, name="뚜껑")], "p2"),
|
||||||
|
("2026-08-01", "p2"): ([item(2, 21, "2026-08-31T16:00:00Z", 9900, status="CANCELED_PAYMENT", # 9/1 01:00 KST
|
||||||
|
canceled="2026-08-31T17:30:00Z"), # 9/1 02:30 — 클레임 없음
|
||||||
|
item(3, 31, "2026-08-31T09:00:00", 4000, status="BEFORE_PAYMENT")], None),
|
||||||
|
("2026-09-01", None): ([item(4, 41, "2026-09-01T10:00:00", 15000, status="COMPLETED_RETURN"),
|
||||||
|
item(6, 61, "2026-09-02T10:00:00", 5000, status="CANCELED_PAYMENT",
|
||||||
|
canceled="2026-09-02T11:00:00")], None), # 클레임 환불은 9/5(기간 밖) → 여기선 안 뺌
|
||||||
|
# 기간 앞 90일(5/3~7/31) 조회의 마지막 구간 — 7/15 주문을 8/10 에 취소(클레임 있음)
|
||||||
|
("2026-07-04", None): ([item(5, 51, "2026-07-15T10:00:00", 7000, qty=2, status="CANCELED_PAYMENT",
|
||||||
|
canceled="2026-08-10T09:00:00")], None),
|
||||||
|
}
|
||||||
|
claims = [
|
||||||
|
_toss_claim(1, "RETURN", "COMPLETED", 4, 41, 15000, refunded="2026-09-02T09:00:00"),
|
||||||
|
_toss_claim(2, "CANCEL", "COMPLETED", 5, 51, 3500, refunded="2026-08-10T09:05:00", qty=2), # 금액은 주문 price 7,000
|
||||||
|
_toss_claim(3, "CANCEL", "COMPLETED", 6, 61, 5000, refunded="2026-09-05T10:00:00"), # 기간 밖
|
||||||
|
_toss_claim(4, "CANCEL", "COMPLETED", 8, 81, 4400, refunded="2026-08-15T10:00:00"), # 90일보다 오래된 주문
|
||||||
|
_toss_claim(5, "EXCHANGE", "COMPLETED", 1, 11, 20000, refunded="2026-09-01T10:00:00"), # 교환 → 제외
|
||||||
|
_toss_claim(6, "CANCEL", "REQUESTED", 1, 12, 5000), # 미환불 → 제외
|
||||||
|
]
|
||||||
|
calls, ccalls = [], []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
ccalls.append(params.get("nextToken"))
|
||||||
|
page = claims[:3] if not params.get("nextToken") else claims[3:]
|
||||||
|
tok = None if params.get("nextToken") else "c2"
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": page, "nextToken": tok,
|
||||||
|
"hasNext": tok is not None}})
|
||||||
|
assert not url.endswith("/settlement-steps"), "수집은 정산 건별을 부르지 않는다"
|
||||||
|
calls.append((params["startDate"], params["endDate"], params.get("nextCursor")))
|
||||||
|
rows, cur = pages.get((params["startDate"], params.get("nextCursor")), ([], None))
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": cur}})
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
return httpx.Response(200, json={"access_token": "TOKEN-T", "expires_in": 31535999})
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||||
|
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("toss", date(2026, 8, 1), date(2026, 9, 2))
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
assert r["ok"], r
|
||||||
|
assert [c for c in calls if c[0] >= "2026-08-01"] == [
|
||||||
|
("2026-08-01", "2026-08-31", None), ("2026-08-01", "2026-08-31", "p2"), ("2026-09-01", "2026-09-02", None)]
|
||||||
|
assert [(a, b) for a, b, _ in calls if a < "2026-08-01"] == [
|
||||||
|
("2026-05-03", "2026-06-02"), ("2026-06-03", "2026-07-03"), ("2026-07-04", "2026-07-31")] # 앞 90일
|
||||||
|
assert ccalls == [None, "c2"] # 클레임 목록 끝까지
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "toss"}
|
||||||
|
refunds = {k: v for k, v in ev_.items() if k.startswith("toss:R")}
|
||||||
|
assert set(ev_) - set(refunds) == {"toss:1", "toss:2", "toss:4", "toss:6"} # 결제 전(3)만 제외
|
||||||
|
assert {k: (v["amount"], v["sales_date"], v["event_type"]) for k, v in refunds.items()} == {
|
||||||
|
"toss:R21": (-9900, date(2026, 9, 1), "CANCEL"), # 클레임 없는 결제취소 → canceledAt
|
||||||
|
"toss:R41": (-15000, date(2026, 9, 2), "RETURN"), # 반품 → 클레임 refundedDt
|
||||||
|
"toss:R51": (-7000, date(2026, 8, 10), "CANCEL"), # 앞 90일 주문 — 금액은 주문 price(판매가 × 수량)
|
||||||
|
"toss:R81": (-4400, date(2026, 8, 15), "CANCEL"), # 주문 내역에 없는 오래된 주문 → 클레임 order.price
|
||||||
|
} # R61: 클레임 환불(9/5)이 기간 밖 → canceledAt(9/2)으로 넣지 않음, 교환·미환불 클레임 제외
|
||||||
|
# 환불 사건에도 원래 주문일 — 대시보드 금액 클릭 상세의 "주문일" 열(9/6 화면: 9/5 주문을 9/6 취소)
|
||||||
|
assert {k: v["order_date"] for k, v in refunds.items()} == {
|
||||||
|
"toss:R21": date(2026, 9, 1), "toss:R41": date(2026, 9, 1), "toss:R51": date(2026, 7, 15),
|
||||||
|
"toss:R81": date(2026, 8, 1)}
|
||||||
|
net = {}
|
||||||
|
for v in ev_.values():
|
||||||
|
net[v["sales_date"]] = net.get(v["sales_date"], 0) + v["amount"]
|
||||||
|
assert net == {date(2026, 8, 10): -7000, date(2026, 8, 15): -4400, date(2026, 8, 31): 25000,
|
||||||
|
date(2026, 9, 1): 9900 + 15000 - 9900, date(2026, 9, 2): 5000 - 15000}
|
||||||
|
assert ev_["toss:1"]["amount"] == 25000 and ev_["toss:1"]["discount_amount"] == 1000 # 할인 전·배송비 제외
|
||||||
|
assert ev_["toss:1"]["quantity"] == 3 and ev_["toss:1"]["product_name"] == "밀폐용기 외 1건"
|
||||||
|
assert ev_["toss:1"]["sales_date"] == date(2026, 8, 31)
|
||||||
|
assert ev_["toss:2"]["amount"] == 9900 and ev_["toss:2"]["sales_date"] == date(2026, 9, 1) # UTC → 한국 날짜
|
||||||
|
assert ev_["toss:4"]["amount"] == 15000 and ev_["toss:4"]["order_status"] == "반품완료"
|
||||||
|
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_toss_reconcile_hides_personal():
|
||||||
|
import time as _t
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
||||||
|
access_token_expires_at=str(int(_t.time()) + 99999)))
|
||||||
|
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
||||||
|
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
||||||
|
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
||||||
|
|
||||||
|
# 다른 날(8/20) 주문을 9/10 에 취소 — 기간 앞(90일) 주문 조회에서만 보인다
|
||||||
|
old = {**_toss_item(7, 71, "2026-08-20T10:00:00", 11900, status="CANCELED_PAYMENT"), "canceledAt": "2026-09-10T09:00:00"}
|
||||||
|
claims = [{"id": 1, "type": "RETURN", "status": "COMPLETED", "isRefunded": True, "refundedDt": "2026-09-10T12:00:00",
|
||||||
|
"requestReason": "단순 변심 010-5555-6666", "returnAddress": "서울시 반품동",
|
||||||
|
"order": {"id": 8, "orderProductId": 81, "price": 5000, "createdDt": "2026-08-25T10:00:00",
|
||||||
|
"ordererName": "홍길동", "ordererPhoneNumber": "010-1234-5678"},
|
||||||
|
"product": {"id": 3, "name": "밀폐용기", "quantity": 1}},
|
||||||
|
{"id": 2, "type": "CANCEL", "status": "REQUESTED", "isRefunded": False, "order": {"id": 9, "price": 777}}]
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if url.endswith("/settlement-steps"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": steps, "nextToken": None}})
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": claims, "nextToken": None,
|
||||||
|
"hasNext": False}})
|
||||||
|
found = rows if params["startDate"] >= "2026-09-09" else [old] if params["startDate"] <= "2026-08-20" <= params["endDate"] else []
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||||
|
|
||||||
|
orig = (httpx.get, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, ts.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
rec = ts.TossAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
|
||||||
|
finally:
|
||||||
|
httpx.get, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
allp = rec["probes"][0]
|
||||||
|
assert allp["ok"] and allp["count"] == 2
|
||||||
|
f = {x["name"]: x for x in allp["fields"]}
|
||||||
|
assert f["price"]["sum"] == 29900
|
||||||
|
for k in ("ordererName", "ordererPhone", "address", "zipCode", "shippingNote"):
|
||||||
|
assert f[k]["personal"] and f[k]["sample"] == "", k
|
||||||
|
assert not f["productName"]["personal"] and f["productName"]["sample"] == "밀폐용기"
|
||||||
|
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) and "010-9999-8888" not in repr(rec)
|
||||||
|
# 날짜별: 매출(주문일) · 환불(환불일, 적용 규칙) · 순 거래액 — 9/10 환불 = 반품 클레임 5,000 + 클레임 없는 결제취소 11,900
|
||||||
|
assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 0, "ship": 29900},
|
||||||
|
{"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 16900, "ship": -16900}]
|
||||||
|
assert rec["day_cols"]["ship"].startswith("순 거래액")
|
||||||
|
labels = [p["label"] for p in rec["probes"]]
|
||||||
|
assert any("결제 뒤 취소·반품(매출 포함)" in x for x in labels) and any("정산 건별" in x for x in labels)
|
||||||
|
# 환불 출처별 — 적용 규칙 · 클레임 · 취소 시각 · 정산(참고), 날짜별 합계 + 건별
|
||||||
|
cand = {c["key"]: c for c in rec["refund_candidates"]}
|
||||||
|
assert rec["refund_candidates"][0]["key"] == "rule" and cand["rule"]["days"] == {"2026-09-10": 16900}
|
||||||
|
assert sorted(x["orderId"] for x in cand["rule"]["rows"]) == ["7", "8"]
|
||||||
|
assert cand["settlement"]["days"] == {"2026-09-10": 9900}
|
||||||
|
assert cand["canceled"]["days"] == {"2026-09-10": 11900} and cand["canceled"]["rows"][0]["orderId"] == "7"
|
||||||
|
assert cand["canceled"]["rows"][0]["orderDate"] == "2026-08-20" # 주문일은 따로 열로(메모 X)
|
||||||
|
assert {x["orderId"]: x["orderDate"] for x in cand["rule"]["rows"]} == {"7": "2026-08-20", "8": "2026-08-25"}
|
||||||
|
assert cand["claims"]["days"] == {"2026-09-10": 5000} and len(cand["claims"]["rows"]) == 1 # 환불 안 된 클레임 제외
|
||||||
|
cf = {x["name"]: x for x in next(p for p in rec["probes"] if p["key"] == "claims")["fields"]}
|
||||||
|
assert cf["requestReason"]["personal"] and cf["returnAddress"]["personal"] and cf["order.ordererPhoneNumber"]["personal"]
|
||||||
|
assert "010-5555-6666" not in repr(rec) and "반품동" not in repr(rec)
|
||||||
|
|
||||||
|
|
||||||
def test_not_implemented_and_mock():
|
def test_not_implemented_and_mock():
|
||||||
st = FakeStore()
|
st = FakeStore()
|
||||||
creds = CredentialService(st, lambda: ring())
|
creds = CredentialService(st, lambda: ring())
|
||||||
@@ -1385,6 +1658,68 @@ def test_sync_job_cancel():
|
|||||||
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
|
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_job_stop_shop():
|
||||||
|
"""쇼핑몰별 [중지]: 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, "중지됨") 다음 쇼핑몰로 넘어간다.
|
||||||
|
차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 끝난 쇼핑몰·없는 쇼핑몰은 중지 못 함."""
|
||||||
|
import bcrypt
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
from app.modules.performance.adapters import naver as nv
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
|
||||||
|
job = jobs.create_job(user="king@x", start=None, end=None)
|
||||||
|
naver_days = []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
if "commerce.naver.com" in url:
|
||||||
|
naver_days.append(params["from"][:10])
|
||||||
|
if len(naver_days) == 1:
|
||||||
|
assert job.stop_shop("gsshop") # 차례가 안 온 GS샵을 미리 중지
|
||||||
|
if len(naver_days) == 2:
|
||||||
|
assert job.stop_shop("naver") # 둘째 날을 받는 도중 네이버 중지
|
||||||
|
rows = [_naver_item("A" + naver_days[-1], "P" + naver_days[-1], naver_days[-1], 10000)]
|
||||||
|
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
|
||||||
|
if url.endswith("/claims"):
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"items": [], "nextToken": None}})
|
||||||
|
found = [_toss_item(1, 11, "2026-09-09T10:00:00", 12000)] if params["startDate"] == "2026-09-09" else []
|
||||||
|
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": found, "nextCursor": None}})
|
||||||
|
|
||||||
|
def post(url, data=None, timeout=None, headers=None):
|
||||||
|
return httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
st.markets = [m for m in st.markets if m["code"] in ("naver", "gsshop", "toss")]
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "naver"),
|
||||||
|
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "gsshop"),
|
||||||
|
{"vendor_code": "1047142", "api_key": "0123456789abcdef0123456789ABCDEF"})
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
|
||||||
|
st.events[("naver", "SALE", "naver:OLD")] = {"amount": 5000, "is_sample": False, "sales_date": date(2026, 9, 10)}
|
||||||
|
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC)
|
||||||
|
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = post, get, 0, 0
|
||||||
|
try:
|
||||||
|
res = SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 12), user="king@x", job=job)
|
||||||
|
finally:
|
||||||
|
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC, ts.CALL_INTERVAL_SEC = orig
|
||||||
|
job.finish()
|
||||||
|
by = {r["code"]: r for r in res}
|
||||||
|
assert naver_days == ["2026-09-09", "2026-09-10"] # 중지 뒤 네이버는 더 부르지 않음
|
||||||
|
assert by["naver"]["cancelled"] and by["naver"]["message"] == "중지됨"
|
||||||
|
assert by["gsshop"]["cancelled"] and by["gsshop"]["message"] == "중지됨" # 미리 중지 → 차례에 건너뜀
|
||||||
|
assert by["toss"]["ok"] and by["toss"]["upserted"] == 1 # 다음 쇼핑몰은 계속
|
||||||
|
assert ("naver", "SALE", "naver:OLD") in st.events and not any(k[0] == "naver" and k[2] != "naver:OLD" for k in st.events)
|
||||||
|
assert ("toss", "SALE", "toss:1") in st.events
|
||||||
|
snap = job.snapshot()
|
||||||
|
shops = {s["code"]: s for s in snap["shops"]}
|
||||||
|
assert shops["naver"]["state"] == "cancelled" and shops["naver"]["message"] == "중지됨" and shops["naver"]["stop_requested"]
|
||||||
|
assert shops["toss"]["state"] == "done" and not snap["cancel_requested"]
|
||||||
|
assert "naver" not in st.status # 연결 상태 안 바뀜
|
||||||
|
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||||
n = 0
|
n = 0
|
||||||
|
|||||||
+708
-24
@@ -13,8 +13,10 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
from datetime import date, datetime
|
import uuid
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
from datetime import time as dtime
|
from datetime import time as dtime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -1840,6 +1842,20 @@ class ProjectStore:
|
|||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
return self._table_exists(conn, "goal_years")
|
return self._table_exists(conn, "goal_years")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _goal_quarters(conn: Any) -> bool:
|
||||||
|
"""마이그레이션 017(분기) 적용 여부 — goal_cells 월 칸 CHECK 가 16(4분기)까지 받는가."""
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT pg_get_constraintdef(c.oid) AS d FROM pg_constraint c "
|
||||||
|
"WHERE c.conname = 'goal_cells_month_check' AND c.conrelid = 'goal_cells'::regclass"
|
||||||
|
).fetchone()
|
||||||
|
return bool(row) and "16" in str(row["d"])
|
||||||
|
|
||||||
|
def goals_halves_enabled(self) -> bool:
|
||||||
|
"""상·하반기 글 칸·월 칸 병합(마이그레이션 014) 적용 여부."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return self._table_exists(conn, "goal_cell_merges")
|
||||||
|
|
||||||
def list_goal_years(self) -> list[int]:
|
def list_goal_years(self) -> list[int]:
|
||||||
"""목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable."""
|
"""목표를 만든 연도(최근 연도 먼저). 013 미적용이면 UndefinedTable."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
@@ -1871,25 +1887,35 @@ class ProjectStore:
|
|||||||
(src["year"],),
|
(src["year"],),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
plan = []
|
plan = []
|
||||||
|
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||||
for a in areas:
|
for a in areas:
|
||||||
labels = conn.execute(
|
labels = conn.execute(
|
||||||
"SELECT label FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id",
|
"SELECT label" + (", label_cont" if groups else "") + " FROM goal_rows "
|
||||||
|
"WHERE area_id = %s ORDER BY sort_order, id",
|
||||||
(a["id"],),
|
(a["id"],),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
plan.append((a["name"], a["color"], tuple(r["label"] for r in labels) or ("",)))
|
plan.append((a["name"], a["color"],
|
||||||
|
tuple((r["label"], bool(r.get("label_cont"))) for r in labels) or (("", False),)))
|
||||||
else:
|
else:
|
||||||
plan = list(store.DEFAULT_GOAL_AREAS)
|
plan = [(n, c, tuple((lb, False) for lb in labels)) for n, c, labels in store.DEFAULT_GOAL_AREAS]
|
||||||
|
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||||
for i, (name, color, labels) in enumerate(plan):
|
for i, (name, color, labels) in enumerate(plan):
|
||||||
aid = conn.execute(
|
aid = conn.execute(
|
||||||
"INSERT INTO goal_areas (year, name, color, sort_order) "
|
"INSERT INTO goal_areas (year, name, color, sort_order) "
|
||||||
"VALUES (%s, %s, %s, %s) RETURNING id",
|
"VALUES (%s, %s, %s, %s) RETURNING id",
|
||||||
(y, name, color, i),
|
(y, name, color, i),
|
||||||
).fetchone()["id"]
|
).fetchone()["id"]
|
||||||
for j, label in enumerate(labels):
|
for j, (label, cont) in enumerate(labels):
|
||||||
conn.execute(
|
if groups:
|
||||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)",
|
conn.execute(
|
||||||
(aid, label, j),
|
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, %s, %s)",
|
||||||
)
|
(aid, label, cont and j > 0, j),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, %s)",
|
||||||
|
(aid, label, j),
|
||||||
|
)
|
||||||
|
|
||||||
def delete_goal_year(self, *, year: int) -> None:
|
def delete_goal_year(self, *, year: int) -> None:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
@@ -1913,7 +1939,11 @@ class ProjectStore:
|
|||||||
"""한 해 목표 표 전체. 연도가 없으면 None.
|
"""한 해 목표 표 전체. 연도가 없으면 None.
|
||||||
|
|
||||||
metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}}
|
metrics = {"sales": {"target": {1: 12.0, ...}, "actual": {...}}, "roas": {...}}
|
||||||
areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", ...}}]}]
|
areas = [{id, name, color, rows: [{id, label, cells: {0: "연간 글", 1: "1월 글", 13: "상반기 글", ...},
|
||||||
|
merges: {시작 칸: (가로 칸 수, 세로 줄 수)}}]}]
|
||||||
|
halves = 마이그레이션 014 적용 여부(기간 글 칸·병합 — 이름은 예전 그대로, 지금은 분기 칸)
|
||||||
|
quarters = 마이그레이션 017 적용 여부(2·4분기 칸 15·16 저장)
|
||||||
|
rect = 마이그레이션 015 적용 여부(세로 병합·연간/반기 칸 병합·주간 회의록)
|
||||||
"""
|
"""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
head = conn.execute(
|
head = conn.execute(
|
||||||
@@ -1928,8 +1958,9 @@ class ProjectStore:
|
|||||||
"SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id",
|
"SELECT id, name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id",
|
||||||
(year,),
|
(year,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
groups = self._column_exists(conn, "goal_rows", "label_cont")
|
||||||
row_rows = conn.execute(
|
row_rows = conn.execute(
|
||||||
"SELECT r.id, r.area_id, r.label FROM goal_rows r "
|
"SELECT r.id, r.area_id, r.label" + (", r.label_cont" if groups else "") + " FROM goal_rows r "
|
||||||
"JOIN goal_areas a ON a.id = r.area_id WHERE a.year = %s "
|
"JOIN goal_areas a ON a.id = r.area_id WHERE a.year = %s "
|
||||||
"ORDER BY r.sort_order, r.id",
|
"ORDER BY r.sort_order, r.id",
|
||||||
(year,),
|
(year,),
|
||||||
@@ -1940,6 +1971,15 @@ class ProjectStore:
|
|||||||
"WHERE a.year = %s",
|
"WHERE a.year = %s",
|
||||||
(year,),
|
(year,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
halves = self._table_exists(conn, "goal_cell_merges")
|
||||||
|
rect = halves and self._column_exists(conn, "goal_cell_merges", "row_span")
|
||||||
|
quarters = halves and self._goal_quarters(conn)
|
||||||
|
merge_rows = conn.execute(
|
||||||
|
"SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "") + " FROM goal_cell_merges m "
|
||||||
|
"JOIN goal_rows r ON r.id = m.row_id JOIN goal_areas a ON a.id = r.area_id "
|
||||||
|
"WHERE a.year = %s",
|
||||||
|
(year,),
|
||||||
|
).fetchall() if halves else []
|
||||||
metrics: dict[str, dict[str, dict[int, float]]] = {
|
metrics: dict[str, dict[str, dict[int, float]]] = {
|
||||||
m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS
|
m: {k: {} for k in store.GOAL_KINDS} for m in store.GOAL_METRICS
|
||||||
}
|
}
|
||||||
@@ -1948,10 +1988,16 @@ class ProjectStore:
|
|||||||
cells: dict[int, dict[int, str]] = {}
|
cells: dict[int, dict[int, str]] = {}
|
||||||
for c in cell_rows:
|
for c in cell_rows:
|
||||||
cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"]
|
cells.setdefault(int(c["row_id"]), {})[int(c["month"])] = c["body"]
|
||||||
|
merges: dict[int, dict[int, tuple[int, int]]] = {}
|
||||||
|
for g in merge_rows:
|
||||||
|
merges.setdefault(int(g["row_id"]), {})[int(g["start_month"])] = (
|
||||||
|
int(g["span"]), int(g.get("row_span") or 1))
|
||||||
rows_by_area: dict[int, list[dict[str, Any]]] = {}
|
rows_by_area: dict[int, list[dict[str, Any]]] = {}
|
||||||
for r in row_rows:
|
for r in row_rows:
|
||||||
|
rid = int(r["id"])
|
||||||
rows_by_area.setdefault(int(r["area_id"]), []).append(
|
rows_by_area.setdefault(int(r["area_id"]), []).append(
|
||||||
{"id": int(r["id"]), "label": r["label"], "cells": cells.get(int(r["id"]), {})}
|
{"id": rid, "label": r["label"], "cells": cells.get(rid, {}),
|
||||||
|
"merges": merges.get(rid, {}), "label_cont": bool(r.get("label_cont"))}
|
||||||
)
|
)
|
||||||
areas = [
|
areas = [
|
||||||
{"id": int(a["id"]), "name": a["name"], "color": a["color"],
|
{"id": int(a["id"]), "name": a["name"], "color": a["color"],
|
||||||
@@ -1959,7 +2005,8 @@ class ProjectStore:
|
|||||||
for a in area_rows
|
for a in area_rows
|
||||||
]
|
]
|
||||||
return {"year": int(head["year"]), "sales_unit": head["sales_unit"],
|
return {"year": int(head["year"]), "sales_unit": head["sales_unit"],
|
||||||
"metrics": metrics, "areas": areas}
|
"metrics": metrics, "areas": areas, "halves": halves, "rect": rect, "groups": groups,
|
||||||
|
"quarters": quarters}
|
||||||
|
|
||||||
def set_goal_metric(
|
def set_goal_metric(
|
||||||
self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = ""
|
self, *, year: int, metric: str, kind: str, month: int, value: float | None, updated_by: str = ""
|
||||||
@@ -2050,20 +2097,103 @@ class ProjectStore:
|
|||||||
self._move_goal_item("goal_areas", "year", area_id, direction)
|
self._move_goal_item("goal_areas", "year", area_id, direction)
|
||||||
|
|
||||||
def move_goal_row(self, *, row_id: int, direction: int) -> None:
|
def move_goal_row(self, *, row_id: int, direction: int) -> None:
|
||||||
|
"""줄 순서 바꾸기 — 세로로 병합된 칸에 걸린 줄(자신 또는 바꿀 이웃)은 옮기지 않는다(엑셀처럼 병합을 먼저 해제)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()
|
||||||
|
if me is None:
|
||||||
|
raise KeyError(row_id)
|
||||||
|
ids, merges, _ = self._area_geometry(conn, int(me["area_id"]))
|
||||||
|
i = ids.index(row_id)
|
||||||
|
j = i + (1 if direction > 0 else -1)
|
||||||
|
if 0 <= j < len(ids) and any(g["r1"] > g["r0"] and (g["r0"] <= i <= g["r1"] or g["r0"] <= j <= g["r1"])
|
||||||
|
for g in merges):
|
||||||
|
raise ValueError("세로로 병합된 칸에 걸린 줄은 옮길 수 없습니다. 병합을 해제한 뒤 옮기세요.")
|
||||||
|
if 0 <= j < len(ids):
|
||||||
|
conts = self._label_conts(int(me["area_id"]), ids)
|
||||||
|
in_group = lambda k: conts[k] or (k + 1 < len(ids) and conts[k + 1]) # noqa: E731
|
||||||
|
if in_group(i) or in_group(j):
|
||||||
|
raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.")
|
||||||
self._move_goal_item("goal_rows", "area_id", row_id, direction)
|
self._move_goal_item("goal_rows", "area_id", row_id, direction)
|
||||||
|
|
||||||
def add_goal_row(self, *, area_id: int, label: str = "") -> int:
|
def _label_conts(self, area_id: int, ids: list[int]) -> list[bool]:
|
||||||
lb = store.validate_goal_row_label(label)
|
"""영역 줄 순서(ids)대로 label_cont — 016 미적용이면 모두 False."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s", (area_id,)).fetchone():
|
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||||
raise KeyError(area_id)
|
return [False] * len(ids)
|
||||||
rid = conn.execute(
|
got = {int(r["id"]): bool(r["label_cont"]) for r in conn.execute(
|
||||||
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, "
|
"SELECT id, label_cont FROM goal_rows WHERE area_id = %s", (area_id,)).fetchall()}
|
||||||
"(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) "
|
return [got.get(i, False) for i in ids]
|
||||||
"RETURNING id",
|
|
||||||
(area_id, lb, area_id),
|
def add_goal_row(
|
||||||
).fetchone()["id"]
|
self, *, area_id: int, label: str = "", ref_row_id: int | None = None, place: str = "below",
|
||||||
return int(rid)
|
same_label: bool = False,
|
||||||
|
) -> int:
|
||||||
|
"""줄 추가 — 기준 줄(ref_row_id)이 있으면 그 줄 위(place="above")/아래("below")에, 없으면 영역 맨 끝에.
|
||||||
|
|
||||||
|
same_label(3열에서 추가, 016) = 새 줄을 기준 줄과 **같은 항목 칸(2열)** 안에 넣는다: 아래면 새 줄이 묶음에 이어 붙고
|
||||||
|
(label_cont), 위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다."""
|
||||||
|
lb = store.validate_goal_row_label(label)
|
||||||
|
if place not in ("above", "below"):
|
||||||
|
raise ValueError("place 는 above 또는 below 입니다.")
|
||||||
|
if same_label and ref_row_id is None:
|
||||||
|
raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.")
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
if not conn.execute(
|
||||||
|
"SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)
|
||||||
|
).fetchone():
|
||||||
|
raise KeyError(area_id)
|
||||||
|
if ref_row_id is None:
|
||||||
|
rid = conn.execute(
|
||||||
|
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, "
|
||||||
|
"(SELECT COALESCE(MAX(sort_order), -1) + 1 FROM goal_rows WHERE area_id = %s)) "
|
||||||
|
"RETURNING id",
|
||||||
|
(area_id, lb, area_id),
|
||||||
|
).fetchone()["id"]
|
||||||
|
return int(rid)
|
||||||
|
ids = [int(r["id"]) for r in conn.execute(
|
||||||
|
"SELECT id FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (area_id,)
|
||||||
|
).fetchall()]
|
||||||
|
if ref_row_id not in ids:
|
||||||
|
raise KeyError(ref_row_id)
|
||||||
|
if same_label:
|
||||||
|
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||||
|
raise store.GoalMigration016Needed()
|
||||||
|
ref = conn.execute("SELECT label, label_cont FROM goal_rows WHERE id = %s", (ref_row_id,)).fetchone()
|
||||||
|
if place == "above" and not ref["label_cont"]:
|
||||||
|
# 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다
|
||||||
|
rid = int(conn.execute(
|
||||||
|
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, %s, false, 0) "
|
||||||
|
"RETURNING id", (area_id, ref["label"]),
|
||||||
|
).fetchone()["id"])
|
||||||
|
conn.execute("UPDATE goal_rows SET label = '', label_cont = true WHERE id = %s", (ref_row_id,))
|
||||||
|
else:
|
||||||
|
rid = int(conn.execute(
|
||||||
|
"INSERT INTO goal_rows (area_id, label, label_cont, sort_order) VALUES (%s, '', true, 0) "
|
||||||
|
"RETURNING id", (area_id,),
|
||||||
|
).fetchone()["id"])
|
||||||
|
else:
|
||||||
|
rid = int(conn.execute(
|
||||||
|
"INSERT INTO goal_rows (area_id, label, sort_order) VALUES (%s, %s, 0) RETURNING id",
|
||||||
|
(area_id, lb),
|
||||||
|
).fetchone()["id"])
|
||||||
|
i = ids.index(ref_row_id) + (1 if place == "below" else 0)
|
||||||
|
# 따로 추가(2열 메뉴·+)는 화면이 묶음의 맨 위(위에)·맨 아래(아래) 줄을 기준으로 보내 묶음 밖에 들어간다
|
||||||
|
# 세로 병합 안쪽(시작 줄 아래 ~ 마지막 줄)에 끼우면 엑셀처럼 그 병합이 한 줄 늘어난다
|
||||||
|
if self._table_exists(conn, "goal_cell_merges") and self._column_exists(
|
||||||
|
conn, "goal_cell_merges", "row_span"):
|
||||||
|
_, merges, _ = self._area_geometry(conn, area_id)
|
||||||
|
for g in merges:
|
||||||
|
if g["r0"] < i <= g["r1"]:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_cell_merges SET row_span = row_span + 1 "
|
||||||
|
"WHERE row_id = %s AND start_month = %s",
|
||||||
|
(g["row_id"], g["start"]),
|
||||||
|
)
|
||||||
|
ids.insert(i, rid)
|
||||||
|
for n, x in enumerate(ids):
|
||||||
|
conn.execute("UPDATE goal_rows SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
return rid
|
||||||
|
|
||||||
def update_goal_row(self, *, row_id: int, label: str) -> None:
|
def update_goal_row(self, *, row_id: int, label: str) -> None:
|
||||||
lb = store.validate_goal_row_label(label)
|
lb = store.validate_goal_row_label(label)
|
||||||
@@ -2086,14 +2216,79 @@ class ProjectStore:
|
|||||||
).fetchone()["n"]
|
).fetchone()["n"]
|
||||||
if n <= 1:
|
if n <= 1:
|
||||||
raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.")
|
raise ValueError("업무 영역의 마지막 줄은 지울 수 없습니다. 영역을 삭제하세요.")
|
||||||
|
# 세로 병합에 가려진 줄이면 그 병합이 한 줄 준다(시작 줄을 지우면 병합도 같이 지워진다 — CASCADE)
|
||||||
|
if self._table_exists(conn, "goal_cell_merges") and self._column_exists(
|
||||||
|
conn, "goal_cell_merges", "row_span"):
|
||||||
|
ids, merges, _ = self._area_geometry(conn, int(me["area_id"]))
|
||||||
|
i = ids.index(row_id)
|
||||||
|
for g in merges:
|
||||||
|
if g["r0"] < i <= g["r1"]:
|
||||||
|
if g["span"] * (g["row_span"] - 1) >= 2:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_cell_merges SET row_span = row_span - 1 "
|
||||||
|
"WHERE row_id = %s AND start_month = %s",
|
||||||
|
(g["row_id"], g["start"]),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s",
|
||||||
|
(g["row_id"], g["start"]),
|
||||||
|
)
|
||||||
|
if self._column_exists(conn, "goal_rows", "label_cont"):
|
||||||
|
# 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면)
|
||||||
|
me2 = conn.execute("SELECT label, label_cont, sort_order FROM goal_rows WHERE id = %s",
|
||||||
|
(row_id,)).fetchone()
|
||||||
|
if not me2["label_cont"]:
|
||||||
|
nxt = conn.execute(
|
||||||
|
"SELECT id, label, label_cont FROM goal_rows WHERE area_id = %s AND id <> %s "
|
||||||
|
"AND (sort_order, id) > (%s, %s) ORDER BY sort_order, id LIMIT 1",
|
||||||
|
(me["area_id"], row_id, me2["sort_order"], row_id),
|
||||||
|
).fetchone()
|
||||||
|
if nxt and nxt["label_cont"]:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_rows SET label_cont = false, label = CASE WHEN label = '' THEN %s ELSE label END "
|
||||||
|
"WHERE id = %s", (me2["label"], nxt["id"]),
|
||||||
|
)
|
||||||
conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,))
|
conn.execute("DELETE FROM goal_rows WHERE id = %s", (row_id,))
|
||||||
|
|
||||||
|
def split_goal_label(self, *, row_id: int) -> int:
|
||||||
|
"""항목 칸 나누기 — row_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
if not self._column_exists(conn, "goal_rows", "label_cont"):
|
||||||
|
raise store.GoalMigration016Needed()
|
||||||
|
me = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s FOR UPDATE", (row_id,)).fetchone()
|
||||||
|
if me is None:
|
||||||
|
raise KeyError(row_id)
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, label_cont FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (me["area_id"],)
|
||||||
|
).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
n = 0
|
||||||
|
for r in rows[ids.index(row_id) + 1:]:
|
||||||
|
if not r["label_cont"]:
|
||||||
|
break
|
||||||
|
conn.execute("UPDATE goal_rows SET label_cont = false WHERE id = %s", (r["id"],))
|
||||||
|
n += 1
|
||||||
|
return n
|
||||||
|
|
||||||
def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None:
|
def set_goal_cell(self, *, row_id: int, month: int, body: str, updated_by: str = "") -> None:
|
||||||
m = store.validate_goal_month(month, allow_year=True)
|
m = store.validate_goal_month(month, allow_year=True)
|
||||||
text = store.validate_goal_text(body)
|
text = store.validate_goal_text(body)
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
|
if not conn.execute("SELECT 1 FROM goal_rows WHERE id = %s", (row_id,)).fetchone():
|
||||||
raise KeyError(row_id)
|
raise KeyError(row_id)
|
||||||
|
halves = self._table_exists(conn, "goal_cell_merges")
|
||||||
|
if m > 12 and not halves:
|
||||||
|
raise store.GoalMigration014Needed()
|
||||||
|
if m in store.GOAL_Q_NEW and not self._goal_quarters(conn):
|
||||||
|
raise store.GoalMigration017Needed()
|
||||||
|
if halves:
|
||||||
|
# 병합에 가려진 칸(글은 왼쪽 위 칸에만 둔다) — 다른 창에서 병합된 뒤의 늦은 저장
|
||||||
|
area_id = conn.execute("SELECT area_id FROM goal_rows WHERE id = %s", (row_id,)).fetchone()["area_id"]
|
||||||
|
ids, merges, _ = self._area_geometry(conn, int(area_id))
|
||||||
|
if self._covered_by(merges, ids.index(row_id), store.GOAL_COL_ORDER.index(m)):
|
||||||
|
raise ValueError("병합된 칸입니다. 새로고침해 주세요.")
|
||||||
if not text:
|
if not text:
|
||||||
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m))
|
conn.execute("DELETE FROM goal_cells WHERE row_id = %s AND month = %s", (row_id, m))
|
||||||
else:
|
else:
|
||||||
@@ -2104,6 +2299,495 @@ class ProjectStore:
|
|||||||
(row_id, m, text, store.norm_str(updated_by, lower=True)),
|
(row_id, m, text, store.norm_str(updated_by, lower=True)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ── 엑셀식 사각형 병합 ─────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _column_exists(conn: Any, table: str, column: str) -> bool:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
|
||||||
|
"AND table_name = %s AND column_name = %s",
|
||||||
|
(table, column),
|
||||||
|
).fetchone()
|
||||||
|
return row is not None
|
||||||
|
|
||||||
|
def _area_geometry(self, conn: Any, area_id: int) -> tuple[list[int], list[dict[str, Any]], bool]:
|
||||||
|
"""업무 영역 하나의 병합 배치 — (줄 id 순서, 병합 목록, 세로 병합(015) 가능 여부).
|
||||||
|
병합 = {row_id, start, span, row_span, r0, r1(줄 순번), c0, c1(화면 칸 순번)}. 줄 범위는 영역 끝에서 자른다."""
|
||||||
|
ids = [int(r["id"]) for r in conn.execute(
|
||||||
|
"SELECT id FROM goal_rows WHERE area_id = %s ORDER BY sort_order, id", (area_id,)
|
||||||
|
).fetchall()]
|
||||||
|
if not self._table_exists(conn, "goal_cell_merges"):
|
||||||
|
return ids, [], False
|
||||||
|
rect = self._column_exists(conn, "goal_cell_merges", "row_span")
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT m.row_id, m.start_month, m.span" + (", m.row_span" if rect else "")
|
||||||
|
+ " FROM goal_cell_merges m JOIN goal_rows r ON r.id = m.row_id WHERE r.area_id = %s",
|
||||||
|
(area_id,),
|
||||||
|
).fetchall()
|
||||||
|
merges = []
|
||||||
|
for g in rows:
|
||||||
|
rid, start = int(g["row_id"]), int(g["start_month"])
|
||||||
|
if rid not in ids or start not in store.GOAL_COL_ORDER:
|
||||||
|
continue
|
||||||
|
r0 = ids.index(rid)
|
||||||
|
span, rs = int(g["span"]), int(g.get("row_span") or 1) if rect else 1
|
||||||
|
c0 = store.GOAL_COL_ORDER.index(start)
|
||||||
|
merges.append({"row_id": rid, "start": start, "span": span, "row_span": rs, "r0": r0,
|
||||||
|
"r1": min(len(ids) - 1, r0 + rs - 1), "c0": c0,
|
||||||
|
"c1": min(len(store.GOAL_COL_ORDER) - 1, c0 + span - 1)})
|
||||||
|
return ids, merges, rect
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _covered_by(merges: list[dict[str, Any]], ri: int, ci: int) -> dict[str, Any] | None:
|
||||||
|
"""(줄 순번, 칸 순번)을 가리는 병합(시작 칸 자신은 빼고)."""
|
||||||
|
for g in merges:
|
||||||
|
if g["r0"] <= ri <= g["r1"] and g["c0"] <= ci <= g["c1"] and (ri, ci) != (g["r0"], g["c0"]):
|
||||||
|
return g
|
||||||
|
return None
|
||||||
|
|
||||||
|
def merge_goal_rect(
|
||||||
|
self, *, area_id: int, row_from: Any, row_to: Any, col_from: Any, col_to: Any, updated_by: str = ""
|
||||||
|
) -> dict[str, int]:
|
||||||
|
"""업무 영역 칸을 엑셀처럼 사각형으로 합친다 → {row_id(왼쪽 위 줄), start, span, row_span}.
|
||||||
|
|
||||||
|
줄은 같은 영역 안 연속된 줄, 칸은 화면 순서(연간·1~3월·1분기·…·10~12월·4분기) — 가로는 같은 분기 월 칸끼리만.
|
||||||
|
걸친 기존 병합은 통째로 흡수(엑셀이 선택을 넓히듯). 글은 범위 안 칸들의 글을 왼쪽 위부터 줄·칸 순서대로
|
||||||
|
줄바꿈으로 이어 왼쪽 위 칸에 두고, 나머지 칸 글은 지운다(글을 잃지 않게)."""
|
||||||
|
who = store.norm_str(updated_by, lower=True)
|
||||||
|
try:
|
||||||
|
rf, rt = int(row_from), int(row_to)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("병합할 줄이 올바르지 않습니다.")
|
||||||
|
store.validate_goal_rect_cols(col_from, col_to) # 칸 번호 검사(묶음 검사는 넓힌 뒤 다시)
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
if not self._table_exists(conn, "goal_cell_merges"):
|
||||||
|
raise store.GoalMigration014Needed()
|
||||||
|
if not conn.execute("SELECT 1 FROM goal_areas WHERE id = %s FOR UPDATE", (area_id,)).fetchone():
|
||||||
|
raise KeyError(area_id)
|
||||||
|
ids, merges, rect = self._area_geometry(conn, area_id)
|
||||||
|
if rf not in ids or rt not in ids:
|
||||||
|
raise KeyError(rf if rf not in ids else rt)
|
||||||
|
r0, r1 = sorted((ids.index(rf), ids.index(rt)))
|
||||||
|
c0, c1 = sorted((store.GOAL_COL_ORDER.index(int(col_from)), store.GOAL_COL_ORDER.index(int(col_to))))
|
||||||
|
grown = True
|
||||||
|
while grown: # 걸친 병합을 통째로 품을 때까지 넓힌다
|
||||||
|
grown = False
|
||||||
|
for g in merges:
|
||||||
|
if g["r0"] <= r1 and g["r1"] >= r0 and g["c0"] <= c1 and g["c1"] >= c0:
|
||||||
|
n = (min(r0, g["r0"]), max(r1, g["r1"]), min(c0, g["c0"]), max(c1, g["c1"]))
|
||||||
|
if n != (r0, r1, c0, c1):
|
||||||
|
r0, r1, c0, c1 = n
|
||||||
|
grown = True
|
||||||
|
start, span = store.validate_goal_rect_cols(store.GOAL_COL_ORDER[c0], store.GOAL_COL_ORDER[c1])
|
||||||
|
row_span = r1 - r0 + 1
|
||||||
|
if span * row_span < 2:
|
||||||
|
raise ValueError("두 칸 이상 골라야 병합할 수 있습니다.")
|
||||||
|
if (row_span > 1 or start == store.GOAL_YEAR or start in store.GOAL_COL_QUARTER) and not rect:
|
||||||
|
raise store.GoalMigration015Needed()
|
||||||
|
if start in store.GOAL_Q_NEW and not self._goal_quarters(conn):
|
||||||
|
raise store.GoalMigration017Needed()
|
||||||
|
rows_in = ids[r0:r1 + 1]
|
||||||
|
cols_in = list(store.GOAL_COL_ORDER[c0:c1 + 1])
|
||||||
|
bodies = {(int(c["row_id"]), int(c["month"])): str(c["body"]).strip() for c in conn.execute(
|
||||||
|
"SELECT row_id, month, body FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)",
|
||||||
|
(rows_in, cols_in),
|
||||||
|
).fetchall()}
|
||||||
|
text = store.validate_goal_text("\n".join(
|
||||||
|
bodies[(r, m)] for r in rows_in for m in cols_in if bodies.get((r, m))
|
||||||
|
))
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM goal_cell_merges WHERE row_id = ANY(%s) AND start_month = ANY(%s)",
|
||||||
|
(rows_in, cols_in),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM goal_cells WHERE row_id = ANY(%s) AND month = ANY(%s)", (rows_in, cols_in),
|
||||||
|
)
|
||||||
|
anchor = rows_in[0]
|
||||||
|
if text:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_cells (row_id, month, body, updated_by) VALUES (%s,%s,%s,%s)",
|
||||||
|
(anchor, start, text, who),
|
||||||
|
)
|
||||||
|
if rect:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_cell_merges (row_id, start_month, span, row_span, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(anchor, start, span, row_span, who),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_cell_merges (row_id, start_month, span, updated_by) VALUES (%s, %s, %s, %s)",
|
||||||
|
(anchor, start, span, who),
|
||||||
|
)
|
||||||
|
return {"row_id": anchor, "start": start, "span": span, "row_span": row_span}
|
||||||
|
|
||||||
|
def unmerge_goal_cells(self, *, row_id: int, start: int) -> None:
|
||||||
|
"""병합 해제 — 글은 시작 월 칸에 그대로 남는다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not self._table_exists(conn, "goal_cell_merges"):
|
||||||
|
raise store.GoalMigration014Needed()
|
||||||
|
row = conn.execute(
|
||||||
|
"DELETE FROM goal_cell_merges WHERE row_id = %s AND start_month = %s RETURNING row_id",
|
||||||
|
(row_id, start),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(row_id)
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → 그 달 주차별 회의록
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
_MEETING_ITEM_COLS = ("id, week_start, section, section_color, label, content, target_amount, result_amount, "
|
||||||
|
"status, marketplace_code, carry_from, sort_order")
|
||||||
|
|
||||||
|
def meetings_enabled(self) -> bool:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return self._table_exists(conn, "goal_meetings")
|
||||||
|
|
||||||
|
def _require_meetings(self, conn: Any) -> None:
|
||||||
|
if not self._table_exists(conn, "goal_meetings"):
|
||||||
|
raise store.GoalMigration015Needed()
|
||||||
|
|
||||||
|
def _meeting_keys(self, conn: Any) -> bool:
|
||||||
|
"""마이그레이션 018 — goal_meeting_items.line_key(주가 바뀌어도 같은 줄을 가리키는 연결키) 적용 여부.
|
||||||
|
적용되면 한 번만 확인한다(되돌리는 마이그레이션은 없다)."""
|
||||||
|
if getattr(self, "_meeting_keys_ok", False):
|
||||||
|
return True
|
||||||
|
ok = self._column_exists(conn, "goal_meeting_items", "line_key")
|
||||||
|
if ok:
|
||||||
|
self._meeting_keys_ok = True
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def _meeting_cols(self, conn: Any) -> str:
|
||||||
|
return self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _meeting_item(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out = dict(r)
|
||||||
|
out["id"] = int(out["id"])
|
||||||
|
out["week_start"] = out["week_start"].isoformat()
|
||||||
|
for k in ("target_amount", "result_amount", "carry_from"):
|
||||||
|
out[k] = int(out[k]) if out.get(k) is not None else None
|
||||||
|
if out.get("line_key") is not None:
|
||||||
|
out["line_key"] = str(out["line_key"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def meeting_weeks(self, *, start: date, end: date) -> list[str]:
|
||||||
|
"""기간 안에 회의록이 있는 주(월요일) 목록."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not self._table_exists(conn, "goal_meetings"):
|
||||||
|
return []
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT week_start FROM goal_meetings WHERE week_start BETWEEN %s AND %s ORDER BY week_start",
|
||||||
|
(start, end),
|
||||||
|
).fetchall()
|
||||||
|
return [r["week_start"].isoformat() for r in rows]
|
||||||
|
|
||||||
|
def get_meeting(self, *, week_start: date) -> dict[str, Any] | None:
|
||||||
|
"""한 주 회의록 — 머리(금주 목표·참석자·메모) + 줄(지난주 줄 prev 포함). 없으면 None.
|
||||||
|
|
||||||
|
"지난주"는 **정확히 7일 전 주(week_start − 7)** 만이다(몇 주 전 회의록을 지난주로 보이지 않게).
|
||||||
|
· prev_meeting = 그 주 회의록 머리(전주 목표), 그 주 회의록이 없으면 None.
|
||||||
|
· 줄의 prev = 그 주 회의록에서 **같은 연결키(line_key, 마이그레이션 018)** 의 줄 — 생성 순서·이름 변경·
|
||||||
|
순서 이동과 무관하다. 018 미적용이면 예전 carry_from 을 쓰되 가리키는 줄이 정확히 7일 전 주일 때만.
|
||||||
|
"""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
self._require_meetings(conn)
|
||||||
|
cols = self._meeting_cols(conn)
|
||||||
|
keyed = self._meeting_keys(conn)
|
||||||
|
head = conn.execute(
|
||||||
|
"SELECT week_start, week_target, attendees, notes, updated_by, updated_at "
|
||||||
|
"FROM goal_meetings WHERE week_start = %s", (week_start,),
|
||||||
|
).fetchone()
|
||||||
|
if head is None:
|
||||||
|
return None
|
||||||
|
prev_week = week_start - timedelta(days=7)
|
||||||
|
items = conn.execute(
|
||||||
|
f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s "
|
||||||
|
"ORDER BY sort_order, id", (week_start,),
|
||||||
|
).fetchall()
|
||||||
|
prev_head = conn.execute(
|
||||||
|
"SELECT week_start, week_target FROM goal_meetings WHERE week_start = %s", (prev_week,),
|
||||||
|
).fetchone()
|
||||||
|
prev_rows = conn.execute(
|
||||||
|
f"SELECT {cols} FROM goal_meeting_items WHERE week_start = %s", (prev_week,),
|
||||||
|
).fetchall() if prev_head else []
|
||||||
|
by_key = {str(r["line_key"]): r for r in prev_rows if r.get("line_key") is not None} if keyed else {}
|
||||||
|
by_id = {int(r["id"]): r for r in prev_rows}
|
||||||
|
out_items = []
|
||||||
|
for r in items:
|
||||||
|
it = self._meeting_item(r)
|
||||||
|
if keyed:
|
||||||
|
p = by_key.get(it.get("line_key") or "")
|
||||||
|
else:
|
||||||
|
p = by_id.get(it["carry_from"]) if it["carry_from"] is not None else None
|
||||||
|
it["prev"] = self._meeting_item(p) if p is not None else None
|
||||||
|
out_items.append(it)
|
||||||
|
return {
|
||||||
|
"week_start": head["week_start"].isoformat(),
|
||||||
|
"week_target": int(head["week_target"]) if head["week_target"] is not None else None,
|
||||||
|
"attendees": head["attendees"], "notes": head["notes"], "updated_by": head["updated_by"],
|
||||||
|
"updated_at": head["updated_at"].astimezone(KST).isoformat(timespec="minutes") if head["updated_at"] else "",
|
||||||
|
"items": out_items,
|
||||||
|
"prev_meeting": {"week_start": prev_head["week_start"].isoformat(),
|
||||||
|
"week_target": int(prev_head["week_target"]) if prev_head["week_target"] is not None
|
||||||
|
else None} if prev_head else None,
|
||||||
|
"line_keys": keyed,
|
||||||
|
}
|
||||||
|
|
||||||
|
def create_meeting(self, *, week_start: date, sections: list[tuple[str, str]], created_by: str = "") -> bool:
|
||||||
|
"""회의록 만들기 — 이미 있으면 False. 줄(구역·이름·색·쇼핑몰 연결·순서)을 글 없이 이어받을 원본:
|
||||||
|
① 앞선 가장 가까운 회의록(평소 순서), ② 앞선 회의록이 없으면 뒤에 있는 가장 가까운 회의록
|
||||||
|
(다음 주를 먼저 만들고 앞 주를 나중에 만든 경우 — 다음 주 줄이 이 주 줄을 "지난주"로 찾게),
|
||||||
|
③ 둘 다 없으면 sections(목표 표 업무 영역 이름·색)마다 기본 양식 줄(store.MEETING_TEMPLATE).
|
||||||
|
이어받은 줄은 원본 줄의 연결키(line_key, 018)를 그대로 갖는다 → 생성 순서와 무관하게 7일 전 주의 같은 키 줄이
|
||||||
|
"지난주"가 된다. 새 줄(양식·줄 추가)은 새 키. carry_from 은 앞선 원본 줄일 때만 기록(이력, 화면 연결에는 안 씀)."""
|
||||||
|
ws = store.validate_week_start(week_start)
|
||||||
|
who = store.norm_str(created_by, lower=True)
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
keyed = self._meeting_keys(conn)
|
||||||
|
ins = conn.execute(
|
||||||
|
"INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) "
|
||||||
|
"ON CONFLICT (week_start) DO NOTHING RETURNING week_start",
|
||||||
|
(ws, who, who),
|
||||||
|
).fetchone()
|
||||||
|
if ins is None:
|
||||||
|
return False
|
||||||
|
src_cols = "id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
||||||
|
src_items: list[dict[str, Any]] = []
|
||||||
|
src_is_prev = True
|
||||||
|
for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)):
|
||||||
|
# 줄이 하나라도 있는 가장 가까운 회의록(빈 회의록은 건너뜀)
|
||||||
|
src = conn.execute(
|
||||||
|
f"SELECT m.week_start FROM goal_meetings m WHERE m.week_start {cmp_} %s "
|
||||||
|
"AND EXISTS (SELECT 1 FROM goal_meeting_items i WHERE i.week_start = m.week_start) "
|
||||||
|
f"ORDER BY m.week_start {order} LIMIT 1",
|
||||||
|
(ws,),
|
||||||
|
).fetchone()
|
||||||
|
if src:
|
||||||
|
src_items = conn.execute(
|
||||||
|
f"SELECT {src_cols} FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id",
|
||||||
|
(src["week_start"],),
|
||||||
|
).fetchall()
|
||||||
|
src_is_prev = is_prev
|
||||||
|
break
|
||||||
|
if src_items:
|
||||||
|
for n, r in enumerate(src_items):
|
||||||
|
key = str(r["line_key"]) if keyed and r.get("line_key") is not None else str(uuid.uuid4())
|
||||||
|
carry = r["id"] if src_is_prev else None
|
||||||
|
if keyed:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||||
|
"marketplace_code, carry_from, sort_order, updated_by, line_key) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n,
|
||||||
|
who, key),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||||
|
"marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
n = 0
|
||||||
|
for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]:
|
||||||
|
for label in store.MEETING_TEMPLATE.get(name, ("",)):
|
||||||
|
if keyed:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||||
|
"marketplace_code, sort_order, updated_by, line_key) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(ws, name, color, label, store.guess_meeting_market(name, label), n, who,
|
||||||
|
str(uuid.uuid4())),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, "
|
||||||
|
"marketplace_code, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(ws, name, color, label, store.guess_meeting_market(name, label), n, who),
|
||||||
|
)
|
||||||
|
n += 1
|
||||||
|
return True
|
||||||
|
|
||||||
|
def delete_meeting(self, *, week_start: date) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
self._require_meetings(conn)
|
||||||
|
row = conn.execute(
|
||||||
|
"DELETE FROM goal_meetings WHERE week_start = %s RETURNING week_start", (week_start,)
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(str(week_start))
|
||||||
|
|
||||||
|
def update_meeting(self, *, week_start: date, fields: dict[str, Any], updated_by: str = "") -> None:
|
||||||
|
"""머리 칸 — week_target(금주 목표 매출, 원) · attendees(참석자) · notes(결정 사항·메모)."""
|
||||||
|
sets: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if "week_target" in fields:
|
||||||
|
v = store.validate_meeting_amount(fields["week_target"])
|
||||||
|
if v is not None and v < 0:
|
||||||
|
raise ValueError("금주 목표는 0 이상이어야 합니다.")
|
||||||
|
sets.append("week_target = %s")
|
||||||
|
params.append(v)
|
||||||
|
if "attendees" in fields:
|
||||||
|
sets.append("attendees = %s")
|
||||||
|
params.append(store.validate_meeting_text(fields["attendees"], limit=3000, what="참석자"))
|
||||||
|
if "notes" in fields:
|
||||||
|
sets.append("notes = %s")
|
||||||
|
params.append(store.validate_meeting_text(fields["notes"], what="메모"))
|
||||||
|
if not sets:
|
||||||
|
return
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
self._require_meetings(conn)
|
||||||
|
row = conn.execute(
|
||||||
|
f"UPDATE goal_meetings SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
|
||||||
|
"WHERE week_start = %s RETURNING week_start",
|
||||||
|
(*params, store.norm_str(updated_by, lower=True), week_start),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(str(week_start))
|
||||||
|
|
||||||
|
def add_meeting_item(
|
||||||
|
self, *, week_start: date, section: str, section_color: str = "", label: str = "",
|
||||||
|
ref_item_id: int | None = None, place: str = "below", updated_by: str = "",
|
||||||
|
) -> int:
|
||||||
|
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역)."""
|
||||||
|
sec = store.norm_str(section)
|
||||||
|
if not sec or len(sec) > store.MEETING_LABEL_MAX:
|
||||||
|
raise ValueError("구역 이름을 입력하세요(50자 이하).")
|
||||||
|
lb = store.validate_meeting_text(label, limit=store.MEETING_LABEL_MAX, what="줄 이름")
|
||||||
|
if place not in ("above", "below"):
|
||||||
|
raise ValueError("place 는 above 또는 below 입니다.")
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
if not conn.execute(
|
||||||
|
"SELECT 1 FROM goal_meetings WHERE week_start = %s FOR UPDATE", (week_start,)
|
||||||
|
).fetchone():
|
||||||
|
raise KeyError(str(week_start))
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, section, section_color FROM goal_meeting_items WHERE week_start = %s "
|
||||||
|
"ORDER BY sort_order, id", (week_start,),
|
||||||
|
).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
color = store.norm_str(section_color) or next(
|
||||||
|
(r["section_color"] for r in rows if r["section"] == sec), "")
|
||||||
|
if ref_item_id is not None:
|
||||||
|
if ref_item_id not in ids:
|
||||||
|
raise KeyError(ref_item_id)
|
||||||
|
i = ids.index(ref_item_id) + (1 if place == "below" else 0)
|
||||||
|
else:
|
||||||
|
same = [n for n, r in enumerate(rows) if r["section"] == sec]
|
||||||
|
i = same[-1] + 1 if same else len(ids)
|
||||||
|
# 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다
|
||||||
|
keyed = self._meeting_keys(conn)
|
||||||
|
new_id = int(conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
|
||||||
|
"sort_order, updated_by" + (", line_key" if keyed else "") + ") VALUES (%s,%s,%s,%s,%s,0,%s"
|
||||||
|
+ (",%s" if keyed else "") + ") RETURNING id",
|
||||||
|
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
|
||||||
|
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ())),
|
||||||
|
).fetchone()["id"])
|
||||||
|
ids.insert(i, new_id)
|
||||||
|
for n, x in enumerate(ids):
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
return new_id
|
||||||
|
|
||||||
|
def update_meeting_item(self, *, item_id: int, fields: dict[str, Any], updated_by: str = "") -> dict[str, Any]:
|
||||||
|
"""줄 칸 — label · content(이번주 할 일) · target_amount · result_amount(그 주 결과, 원) · status(평가) ·
|
||||||
|
marketplace_code(실적 쇼핑몰 연결 — 결과 자동). 저장된 줄을 돌려준다."""
|
||||||
|
sets: list[str] = []
|
||||||
|
params: list[Any] = []
|
||||||
|
if "label" in fields:
|
||||||
|
sets.append("label = %s")
|
||||||
|
params.append(store.validate_meeting_text(fields["label"], limit=store.MEETING_LABEL_MAX, what="줄 이름"))
|
||||||
|
if "content" in fields:
|
||||||
|
sets.append("content = %s")
|
||||||
|
params.append(store.validate_meeting_text(fields["content"]))
|
||||||
|
for k in ("target_amount", "result_amount"):
|
||||||
|
if k in fields:
|
||||||
|
v = store.validate_meeting_amount(fields[k])
|
||||||
|
if k == "target_amount" and v is not None and v < 0:
|
||||||
|
raise ValueError("목표 금액은 0 이상이어야 합니다.")
|
||||||
|
sets.append(f"{k} = %s")
|
||||||
|
params.append(v)
|
||||||
|
if "status" in fields:
|
||||||
|
sets.append("status = %s")
|
||||||
|
params.append(store.validate_meeting_status(fields["status"]))
|
||||||
|
if "marketplace_code" in fields:
|
||||||
|
code = store.norm_str(fields["marketplace_code"], lower=True)
|
||||||
|
if len(code) > 30 or not re.fullmatch(r"[a-z0-9_]*", code):
|
||||||
|
raise ValueError("쇼핑몰 코드가 올바르지 않습니다.")
|
||||||
|
sets.append("marketplace_code = %s")
|
||||||
|
params.append(code)
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
self._require_meetings(conn)
|
||||||
|
if sets:
|
||||||
|
row = conn.execute(
|
||||||
|
f"UPDATE goal_meeting_items SET {', '.join(sets)}, updated_by = %s, updated_at = now() "
|
||||||
|
f"WHERE id = %s RETURNING {self._MEETING_ITEM_COLS}",
|
||||||
|
(*params, store.norm_str(updated_by, lower=True), item_id),
|
||||||
|
).fetchone()
|
||||||
|
else:
|
||||||
|
row = conn.execute(
|
||||||
|
f"SELECT {self._MEETING_ITEM_COLS} FROM goal_meeting_items WHERE id = %s", (item_id,),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
return self._meeting_item(row)
|
||||||
|
|
||||||
|
def delete_meeting_item(self, *, item_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
self._require_meetings(conn)
|
||||||
|
row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
|
||||||
|
def move_meeting_item(self, *, item_id: int, direction: int) -> None:
|
||||||
|
"""같은 구역 안에서 한 칸 위/아래."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
me = conn.execute(
|
||||||
|
"SELECT week_start, section FROM goal_meeting_items WHERE id = %s", (item_id,)
|
||||||
|
).fetchone()
|
||||||
|
if me is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, section FROM goal_meeting_items WHERE week_start = %s ORDER BY sort_order, id "
|
||||||
|
"FOR UPDATE", (me["week_start"],),
|
||||||
|
).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
i = ids.index(item_id)
|
||||||
|
j = i + (1 if direction > 0 else -1)
|
||||||
|
if not 0 <= j < len(ids) or rows[j]["section"] != me["section"]:
|
||||||
|
return
|
||||||
|
ids[i], ids[j] = ids[j], ids[i]
|
||||||
|
for n, x in enumerate(ids):
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
|
||||||
|
def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
|
||||||
|
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not self._table_exists(conn, "goal_years"):
|
||||||
|
return {"sales_unit": "", "sales_target": None, "sales_actual": None, "roas_target": None}
|
||||||
|
head = conn.execute("SELECT sales_unit FROM goal_years WHERE year = %s", (year,)).fetchone()
|
||||||
|
vals = {(r["metric"], r["kind"]): float(r["value"]) for r in conn.execute(
|
||||||
|
"SELECT metric, kind, value FROM goal_metrics WHERE year = %s AND month = %s", (year, month),
|
||||||
|
).fetchall()}
|
||||||
|
return {"sales_unit": head["sales_unit"] if head else "", "sales_target": vals.get(("sales", "target")),
|
||||||
|
"sales_actual": vals.get(("sales", "actual")), "roas_target": vals.get(("roas", "target"))}
|
||||||
|
|
||||||
|
def goal_area_sections(self, *, year: int) -> list[tuple[str, str]]:
|
||||||
|
"""그 해 목표 표의 업무 영역(이름, 색) — 첫 회의록 구역. 없으면 빈 목록(기본 양식 구역)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if not self._table_exists(conn, "goal_areas"):
|
||||||
|
return []
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT name, color FROM goal_areas WHERE year = %s ORDER BY sort_order, id", (year,)
|
||||||
|
).fetchall()
|
||||||
|
return [(r["name"], r["color"]) for r in rows]
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 직렬화
|
# 직렬화
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import logging
|
|||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import date
|
from datetime import date, timedelta
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -2514,6 +2514,10 @@ def inbox_page(request: Request) -> HTMLResponse:
|
|||||||
# 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용
|
# 조회: project 권한자 전원 · 입력/구조 변경: 관리자(is_admin) 전용
|
||||||
# ────────────────────────────────────────────────────────────
|
# ────────────────────────────────────────────────────────────
|
||||||
_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)."
|
_GOALS_MIGRATION_MSG = "연간 목표 기능이 아직 준비되지 않았습니다(DB 마이그레이션 013 필요)."
|
||||||
|
_GOALS_014_MSG = "분기 칸과 칸 병합은 DB 마이그레이션 014 가 필요합니다."
|
||||||
|
_GOALS_017_MSG = "2·4분기 칸은 DB 마이그레이션 017 이 필요합니다."
|
||||||
|
_GOALS_015_MSG = "세로 병합·연간/반기 칸 병합과 주간 회의록은 DB 마이그레이션 015 가 필요합니다."
|
||||||
|
_GOALS_016_MSG = "같은 항목 칸 안에 줄 추가(3열)는 DB 마이그레이션 016 이 필요합니다."
|
||||||
|
|
||||||
|
|
||||||
def _fmt_goal_num(v: float | None) -> str:
|
def _fmt_goal_num(v: float | None) -> str:
|
||||||
@@ -2525,10 +2529,74 @@ def _fmt_goal_num(v: float | None) -> str:
|
|||||||
return f"{v:,.2f}".rstrip("0").rstrip(".")
|
return f"{v:,.2f}".rstrip("0").rstrip(".")
|
||||||
|
|
||||||
|
|
||||||
|
def _goal_label(metric: str, v: float | None) -> str:
|
||||||
|
"""지표 칸 표기 — 로아스는 % 단위(499 → "499%"). 입력칸도 이 표기로 보이고, 저장 때 % 는 떼고 읽는다."""
|
||||||
|
s = _fmt_goal_num(v)
|
||||||
|
return f"{s}%" if s and metric == "roas" else s
|
||||||
|
|
||||||
|
|
||||||
|
def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
|
||||||
|
"""업무 영역 줄마다 칸 배치(row["layout"]) — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 … 4분기 순서, 엑셀식 사각형 병합.
|
||||||
|
|
||||||
|
병합(row["merges"] = {시작 칸: (가로 칸 수, 세로 줄 수)})의 시작 칸은 {"span", "rspan"}(colspan/rowspan),
|
||||||
|
병합에 가려진 칸은 빼고 그린다. 칸 = {"m", "kind": year|month|quarter, "h"(분기 1~4), "span", "rspan", "now"}.
|
||||||
|
가로는 같은 분기 월 칸 안(예전 반기 병합이 분기를 넘으면 여기서 잘림), 세로는 영역 끝까지로 자른다.
|
||||||
|
겹치는 병합(있을 수 없지만)은 나중 것을 무시."""
|
||||||
|
order = store.GOAL_COL_ORDER
|
||||||
|
covered: set[tuple[int, int]] = set()
|
||||||
|
anchors: dict[tuple[int, int], tuple[int, int]] = {}
|
||||||
|
for ri, row in enumerate(rows):
|
||||||
|
for start, (span, rspan) in sorted((row.get("merges") or {}).items()):
|
||||||
|
if start not in order:
|
||||||
|
continue
|
||||||
|
ci = order.index(start)
|
||||||
|
cols = [c for c in range(ci, min(len(order), ci + span))
|
||||||
|
if store.goal_col_group(order[c]) == store.goal_col_group(start)]
|
||||||
|
rr = list(range(ri, min(len(rows), ri + max(1, rspan))))
|
||||||
|
cells = {(r, c) for r in rr for c in cols}
|
||||||
|
if (ri, ci) in covered or cells & set(anchors) - {(ri, ci)} or cells & covered:
|
||||||
|
continue
|
||||||
|
anchors[(ri, ci)] = (len(cols), len(rr))
|
||||||
|
covered |= cells - {(ri, ci)}
|
||||||
|
for ri, row in enumerate(rows):
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for ci, m in enumerate(order):
|
||||||
|
if (ri, ci) in covered:
|
||||||
|
continue
|
||||||
|
span, rspan = anchors.get((ri, ci), (1, 1))
|
||||||
|
kind = "year" if m == store.GOAL_YEAR else "quarter" if m in store.GOAL_COL_QUARTER else "month"
|
||||||
|
h = 0 if kind == "year" else store.GOAL_COL_QUARTER[m] if kind == "quarter" else store.goal_quarter_of(m)
|
||||||
|
out.append({"m": m, "kind": kind, "h": h, "span": span, "rspan": rspan,
|
||||||
|
"now": kind == "month" and m <= this_month <= m + span - 1})
|
||||||
|
row["layout"] = out
|
||||||
|
|
||||||
|
|
||||||
|
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||||
|
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
|
||||||
|
영역 첫 줄은 늘 묶음 첫 줄."""
|
||||||
|
for k, row in enumerate(rows):
|
||||||
|
if k == 0 or not row.get("label_cont"):
|
||||||
|
row["label_cont"] = False
|
||||||
|
n = 1
|
||||||
|
while k + n < len(rows) and rows[k + n].get("label_cont"):
|
||||||
|
n += 1
|
||||||
|
row["label_span"] = n
|
||||||
|
else:
|
||||||
|
row["label_span"] = 0
|
||||||
|
|
||||||
|
|
||||||
def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
||||||
"""목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400."""
|
"""목표 DB 호출 공통 — 013 미적용 503, 없는 대상 404, 입력 오류 400."""
|
||||||
try:
|
try:
|
||||||
return fn(*args, **kwargs)
|
return fn(*args, **kwargs)
|
||||||
|
except store.GoalMigration014Needed:
|
||||||
|
raise HTTPException(status_code=503, detail=_GOALS_014_MSG)
|
||||||
|
except store.GoalMigration015Needed:
|
||||||
|
raise HTTPException(status_code=503, detail=_GOALS_015_MSG)
|
||||||
|
except store.GoalMigration016Needed:
|
||||||
|
raise HTTPException(status_code=503, detail=_GOALS_016_MSG)
|
||||||
|
except store.GoalMigration017Needed:
|
||||||
|
raise HTTPException(status_code=503, detail=_GOALS_017_MSG)
|
||||||
except UndefinedTable:
|
except UndefinedTable:
|
||||||
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
|
raise HTTPException(status_code=503, detail=_GOALS_MIGRATION_MSG)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
@@ -2562,11 +2630,15 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
|||||||
admin = is_admin(user)
|
admin = is_admin(user)
|
||||||
enabled = st.goals_enabled()
|
enabled = st.goals_enabled()
|
||||||
board = st.get_goal_board(year=year) if enabled else None
|
board = st.get_goal_board(year=year) if enabled else None
|
||||||
if board:
|
|
||||||
for m in board["metrics"].values():
|
|
||||||
for kind in list(m):
|
|
||||||
m[kind + "_label"] = {mo: _fmt_goal_num(v) for mo, v in m[kind].items()}
|
|
||||||
today = today_kst()
|
today = today_kst()
|
||||||
|
this_month = today.month if today.year == year else 0
|
||||||
|
if board:
|
||||||
|
for metric, m in board["metrics"].items():
|
||||||
|
for kind in list(m):
|
||||||
|
m[kind + "_label"] = {mo: _goal_label(metric, v) for mo, v in m[kind].items()}
|
||||||
|
for area in board["areas"]:
|
||||||
|
_goal_area_layout(area["rows"], this_month)
|
||||||
|
_goal_label_spans(area["rows"])
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
"project/goals.html",
|
"project/goals.html",
|
||||||
@@ -2588,7 +2660,10 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
|||||||
"goal_year": year,
|
"goal_year": year,
|
||||||
"board": board,
|
"board": board,
|
||||||
"months": list(range(1, 13)),
|
"months": list(range(1, 13)),
|
||||||
"this_month": today.month if today.year == year else 0,
|
# 분기 — (분기, 그 분기 월, 분기 글 칸 번호, 이름). 분기 칸은 그 분기 월 바로 오른쪽
|
||||||
|
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기")
|
||||||
|
for q in (1, 2, 3, 4)],
|
||||||
|
"this_month": this_month,
|
||||||
"goal_area_colors": list(store.GOAL_AREA_COLORS),
|
"goal_area_colors": list(store.GOAL_AREA_COLORS),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -2631,7 +2706,7 @@ def api_set_goal_metric(request: Request, year: int, payload: dict[str, Any] = B
|
|||||||
kind=str(payload.get("kind") or ""), month=payload.get("month"),
|
kind=str(payload.get("kind") or ""), month=payload.get("month"),
|
||||||
value=value, updated_by=user["email"],
|
value=value, updated_by=user["email"],
|
||||||
)
|
)
|
||||||
return JSONResponse({"ok": True, "value": value, "label": _fmt_goal_num(value)})
|
return JSONResponse({"ok": True, "value": value, "label": _goal_label(str(payload.get("metric") or ""), value)})
|
||||||
|
|
||||||
|
|
||||||
@router.post("/api/goals/{year}/areas")
|
@router.post("/api/goals/{year}/areas")
|
||||||
@@ -2671,7 +2746,15 @@ def api_move_goal_area(request: Request, area_id: int, payload: dict[str, Any] =
|
|||||||
def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_add_goal_row(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
_require_admin(request)
|
_require_admin(request)
|
||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""))
|
# ref_row_id + place(above|below) 가 있으면 그 줄 위/아래에, 없으면 영역 맨 끝에
|
||||||
|
ref = payload.get("ref_row_id")
|
||||||
|
try:
|
||||||
|
ref_id = int(ref) if ref not in (None, "") else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="ref_row_id 가 올바르지 않습니다.")
|
||||||
|
rid = _goal_call(st.add_goal_row, area_id=area_id, label=payload.get("label", ""),
|
||||||
|
ref_row_id=ref_id, place=payload.get("place") or "below",
|
||||||
|
same_label=bool(payload.get("same_label")))
|
||||||
return JSONResponse({"ok": True, "id": rid}, status_code=201)
|
return JSONResponse({"ok": True, "id": rid}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
@@ -2691,6 +2774,15 @@ def api_delete_goal_row(request: Request, row_id: int) -> JSONResponse:
|
|||||||
return JSONResponse({"ok": True})
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/rows/{row_id}/split-label")
|
||||||
|
def api_split_goal_label(request: Request, row_id: int) -> JSONResponse:
|
||||||
|
"""항목 칸 나누기 — 묶음 첫 줄 아래 이어 붙은 줄들을 각자 항목 칸으로(016)."""
|
||||||
|
_require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
n = _goal_call(st.split_goal_label, row_id=row_id)
|
||||||
|
return JSONResponse({"ok": True, "split": n})
|
||||||
|
|
||||||
|
|
||||||
@router.post("/api/goals/rows/{row_id}/move")
|
@router.post("/api/goals/rows/{row_id}/move")
|
||||||
def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
_require_admin(request)
|
_require_admin(request)
|
||||||
@@ -2703,7 +2795,8 @@ def api_move_goal_row(request: Request, row_id: int, payload: dict[str, Any] = B
|
|||||||
def api_set_goal_cell(
|
def api_set_goal_cell(
|
||||||
request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...)
|
request: Request, row_id: int, month: int, payload: dict[str, Any] = Body(...)
|
||||||
) -> JSONResponse:
|
) -> JSONResponse:
|
||||||
"""업무 영역 칸 글 — month 0 = 연간, 1~12 = 월. 빈 글 = 지움."""
|
"""업무 영역 칸 글 — month 0 = 연간, 1~12 = 월, 분기 칸 13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기
|
||||||
|
(014, 15·16 은 017). 빈 글 = 지움."""
|
||||||
user = _require_admin(request)
|
user = _require_admin(request)
|
||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
_goal_call(
|
_goal_call(
|
||||||
@@ -2711,3 +2804,482 @@ def api_set_goal_cell(
|
|||||||
body=payload.get("body", ""), updated_by=user["email"],
|
body=payload.get("body", ""), updated_by=user["email"],
|
||||||
)
|
)
|
||||||
return JSONResponse({"ok": True})
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/areas/{area_id}/merge")
|
||||||
|
def api_merge_goal_rect(request: Request, area_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""엑셀식 병합 {row_from, row_to(줄 id), col_from, col_to(칸 번호 0·1~12·13~16)} — 같은 영역 안 사각형,
|
||||||
|
가로는 같은 분기 월 칸끼리. 걸친 병합은 흡수, 글은 왼쪽 위부터 이어서 왼쪽 위 칸에."""
|
||||||
|
user = _require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
res = _goal_call(
|
||||||
|
st.merge_goal_rect, area_id=area_id, row_from=payload.get("row_from"), row_to=payload.get("row_to"),
|
||||||
|
col_from=payload.get("col_from"), col_to=payload.get("col_to"), updated_by=user["email"],
|
||||||
|
)
|
||||||
|
return JSONResponse({"ok": True, **res})
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/goals/rows/{row_id}/merge/{start}")
|
||||||
|
def api_unmerge_goal_cells(request: Request, row_id: int, start: int) -> JSONResponse:
|
||||||
|
"""병합 해제 — 글은 왼쪽 위(시작) 칸에 남는다(엑셀과 같음)."""
|
||||||
|
_require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
_goal_call(st.unmerge_goal_cells, row_id=row_id, start=start)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 주간 회의록 (마이그레이션 015) — 목표 표 월 머리 → /project/goals/{연도}/meetings/{월}?week=월요일
|
||||||
|
# 주 = 월요일~일요일. 지난주 목표·결과 리뷰 → 월 목표 달성을 위한 이번주 목표·할 일.
|
||||||
|
# 쇼핑몰 연결(유통 줄) 결과·전주/금주 매출·월 누적은 실적 모듈(performance_db)에서 읽기만 한다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _perf_sales(request: Request) -> Any:
|
||||||
|
"""실적 모듈 저장소(읽기 전용). 없거나 오류면 None — 회의록은 직접 입력만으로도 동작한다."""
|
||||||
|
return getattr(request.app.state, "performance_store", None)
|
||||||
|
|
||||||
|
|
||||||
|
class _MeetingPerf:
|
||||||
|
"""회의록이 읽는 실적(읽기 전용) — 값과 상태를 따로 둔다. 조회 장애를 0 원으로 바꾸지 않는다.
|
||||||
|
|
||||||
|
state: ``off``(실적 모듈 미연결) · ``error``(쇼핑몰 목록 조회 실패) · ``empty``(매출 집계 쇼핑몰 없음) · ``ok``.
|
||||||
|
``sum``/``total`` 은 알 수 없으면 None(목록 장애·매출 조회 실패), 정상 조회 결과 0 건이면 0.
|
||||||
|
매출 조회가 실패할 때마다 ``failures`` 가 늘어난다(부분 실패 — 머리 숫자마다 따로 미확인)."""
|
||||||
|
|
||||||
|
def __init__(self, perf: Any) -> None:
|
||||||
|
self.perf = perf
|
||||||
|
self.markets: list[dict[str, Any]] = []
|
||||||
|
self.failures = 0
|
||||||
|
if perf is None:
|
||||||
|
self.state = "off"
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
self.markets = [m for m in perf.list_marketplaces() if m.get("enabled")]
|
||||||
|
self.state = "ok"
|
||||||
|
except Exception: # noqa: BLE001 — 실적 DB 장애가 회의록을 막지 않게
|
||||||
|
logger.warning("performance marketplaces unavailable for meeting", exc_info=True)
|
||||||
|
self.state = "error"
|
||||||
|
self.names = {m["code"]: m["name"] for m in self.markets}
|
||||||
|
self.sales_codes = [m["code"] for m in self.markets if m.get("include_in_sales")]
|
||||||
|
if self.state == "ok" and not self.sales_codes:
|
||||||
|
self.state = "empty"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def readable(self) -> bool:
|
||||||
|
"""쇼핑몰 목록을 읽었는가(ok·empty) — 연결 쇼핑몰이 "사용 중이 아님"을 판단할 수 있는가."""
|
||||||
|
return self.state in ("ok", "empty")
|
||||||
|
|
||||||
|
def sum(self, start: date, end: date, codes: list[str]) -> dict[str, int] | None:
|
||||||
|
"""기간 쇼핑몰별 매출 합(원, 취소·반품 차감 = 대시보드 총매출과 같은 값). 알 수 없으면 None."""
|
||||||
|
if not self.readable:
|
||||||
|
return None
|
||||||
|
if not codes or end < start:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
out: dict[str, int] = {}
|
||||||
|
for (_, code), amount in self.perf.daily_amounts(start, end, codes).items():
|
||||||
|
out[code] = out.get(code, 0) + int(amount)
|
||||||
|
return out
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
self.failures += 1
|
||||||
|
logger.warning("performance sales unavailable for meeting", exc_info=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def total(self, start: date, end: date) -> int | None:
|
||||||
|
"""매출 집계 쇼핑몰 합계. 매출 집계 쇼핑몰이 없으면(empty) None — 0 원으로 보이지 않게."""
|
||||||
|
if self.state != "ok":
|
||||||
|
return None
|
||||||
|
r = self.sum(start, end, self.sales_codes)
|
||||||
|
return None if r is None else sum(r.values())
|
||||||
|
|
||||||
|
def freshness(self) -> dict[str, Any] | None:
|
||||||
|
"""매출 집계 쇼핑몰별 마지막 갱신 성공 시각(실적 모듈 perf_connection_status — 서버가 기록한 값만).
|
||||||
|
oldest = 가장 오래된 쇼핑몰 기준(자료가 적어도 이 시각까지는 갱신됨), never = 한 번도 성공 못 한 쇼핑몰."""
|
||||||
|
if self.state != "ok" or not hasattr(self.perf, "statuses"):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
stats = self.perf.statuses() or {}
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.warning("performance statuses unavailable for meeting", exc_info=True)
|
||||||
|
return None
|
||||||
|
shops, never = [], []
|
||||||
|
for code in self.sales_codes:
|
||||||
|
t = (stats.get(code) or {}).get("last_success_sync_at")
|
||||||
|
if t:
|
||||||
|
shops.append({"name": self.names.get(code, code), "at": str(t)})
|
||||||
|
else:
|
||||||
|
never.append(self.names.get(code, code))
|
||||||
|
oldest = min((s["at"] for s in shops), default="")
|
||||||
|
return {"shops": shops, "never": never, "oldest": oldest}
|
||||||
|
|
||||||
|
|
||||||
|
def _kst_short(iso: str) -> str:
|
||||||
|
"""'2026-10-01T14:20:00+09:00' → '10/01 14:20'(서버가 준 시각을 한국시간으로)."""
|
||||||
|
if not iso:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
from datetime import datetime # noqa: WPS433
|
||||||
|
|
||||||
|
d = datetime.fromisoformat(str(iso))
|
||||||
|
if d.tzinfo is not None:
|
||||||
|
d = d.astimezone(KST)
|
||||||
|
return d.strftime("%m/%d %H:%M")
|
||||||
|
except ValueError:
|
||||||
|
return str(iso)[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: date) -> dict[str, Any]:
|
||||||
|
"""회의록 화면 데이터 — 머리(월 목표·누적·남은 주 필요 매출·전주/금주 목표·결과) + 줄(지난주 리뷰 포함).
|
||||||
|
|
||||||
|
"지난주"는 정확히 7일 전 주(prev_week)만 — 머리 전주 목표·전주 결과·줄의 지난주 칸·결과·달성률이 같은 주다
|
||||||
|
(db.get_meeting 이 7일 전 주 회의록에서 같은 연결키 줄만 prev 로 준다). 실적은 _MeetingPerf — 알 수 없는 값은
|
||||||
|
None + head.unknown 에 이름(0 원·0% 로 보이지 않게, 그 값에 기대는 달성률·필요 매출도 계산하지 않는다)."""
|
||||||
|
today = today_kst()
|
||||||
|
meeting = st.get_meeting(week_start=week)
|
||||||
|
targets = st.goal_month_targets(year=year, month=month)
|
||||||
|
mult = store.sales_unit_multiplier(targets["sales_unit"])
|
||||||
|
perf = _MeetingPerf(_perf_sales(request))
|
||||||
|
names = perf.names
|
||||||
|
week_end = week + timedelta(days=6)
|
||||||
|
prev_start, prev_end = week - timedelta(days=7), week - timedelta(days=1)
|
||||||
|
first = date(year, month, 1)
|
||||||
|
last = date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
|
||||||
|
unknown: list[str] = []
|
||||||
|
|
||||||
|
def total(key: str, a: date, b: date) -> int | None:
|
||||||
|
v = perf.total(a, min(b, today))
|
||||||
|
if v is None and perf.state in ("error", "ok"):
|
||||||
|
unknown.append(key) # 목록 장애(error) 또는 이 기간 매출 조회 실패(ok 인데 None)
|
||||||
|
return v
|
||||||
|
|
||||||
|
# 월 누적 = 이 주 앞까지(지난주 일요일까지) — 남은 목표를 이번 주 포함 남은 주로 나눠 "주당 필요 매출"
|
||||||
|
mtd_end = min(last, today, prev_end)
|
||||||
|
month_target_won = int(round(targets["sales_target"] * mult)) if targets["sales_target"] is not None and mult else None
|
||||||
|
mtd = total("mtd", first, mtd_end) if mtd_end >= first else 0 # 1주차 앞에는 지난 날이 없다(정말 0)
|
||||||
|
weeks_left = sum(1 for mon, _ in store.month_weeks(year, month) if mon >= week)
|
||||||
|
pm = meeting.get("prev_meeting") if meeting else None # 정확히 7일 전 주 회의록이어야 "전주 목표"
|
||||||
|
need = None
|
||||||
|
if month_target_won is not None and mtd is not None and weeks_left:
|
||||||
|
need = max(0, month_target_won - mtd) // weeks_left
|
||||||
|
fresh = perf.freshness()
|
||||||
|
head = {
|
||||||
|
"sales_unit": targets["sales_unit"], "sales_target": targets["sales_target"],
|
||||||
|
"roas_target": targets["roas_target"], "month_target_won": month_target_won,
|
||||||
|
"mtd": mtd, "mtd_end": mtd_end.isoformat() if mtd_end >= first else "", "weeks_left": weeks_left,
|
||||||
|
"need_per_week": need,
|
||||||
|
"prev_target": pm["week_target"] if pm and pm["week_start"] == prev_start.isoformat() else None,
|
||||||
|
"prev_exists": bool(pm and pm["week_start"] == prev_start.isoformat()),
|
||||||
|
"prev_result": total("prev_result", prev_start, prev_end) if prev_start <= today else None,
|
||||||
|
"week_result": total("week_result", week, week_end) if week <= today else None,
|
||||||
|
# perf = 실적 모듈 연결 여부(예전 뜻 그대로 — 갱신 상자·안내 문구 조건), 조회 성공 여부는 perf_state·unknown
|
||||||
|
"perf": perf.state != "off",
|
||||||
|
"perf_state": perf.state,
|
||||||
|
"unknown": unknown,
|
||||||
|
"fresh_oldest": _kst_short(fresh["oldest"]) if fresh else "",
|
||||||
|
"fresh_tip": ("매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — " +
|
||||||
|
" · ".join(f"{s['name']} {_kst_short(s['at'])}" for s in fresh["shops"]) +
|
||||||
|
(f" · 갱신 성공 기록 없음: {', '.join(fresh['never'])}" if fresh["never"] else "")) if fresh else "",
|
||||||
|
}
|
||||||
|
if meeting:
|
||||||
|
# 줄마다 지난주 결과 — 쇼핑몰 연결이면 그 주 실적(자동), 아니면 직접 입력한 결과(지난주 줄에 저장)
|
||||||
|
all_codes = [m["code"] for m in perf.markets]
|
||||||
|
by_week: dict[str, dict[str, int] | None] = {}
|
||||||
|
|
||||||
|
def week_sales(ws: str) -> dict[str, int] | None:
|
||||||
|
"""그 주(월~일, 오늘까지) 쇼핑몰별 실적 — 조회 실패면 None(시작 전 주는 부르지 않는다)."""
|
||||||
|
if ws not in by_week:
|
||||||
|
a = date.fromisoformat(ws)
|
||||||
|
by_week[ws] = perf.sum(a, min(a + timedelta(days=6), today), all_codes)
|
||||||
|
return by_week[ws]
|
||||||
|
|
||||||
|
for it in meeting["items"]:
|
||||||
|
prev = it.get("prev")
|
||||||
|
if not prev:
|
||||||
|
continue
|
||||||
|
auto = None
|
||||||
|
code = prev.get("marketplace_code") or ""
|
||||||
|
a = date.fromisoformat(prev["week_start"])
|
||||||
|
prev["period"] = f"{a.month}/{a.day}~{(a + timedelta(days=6)).month}/{(a + timedelta(days=6)).day}"
|
||||||
|
prev["not_started"] = bool(code) and a > today
|
||||||
|
# 쇼핑몰 목록을 못 읽었으면 연결 쇼핑몰이 사용 중인지 알 수 없다 → 결과 미확인(직접 입력 칸·0 으로 바꾸지 않음)
|
||||||
|
prev["auto_error"] = bool(code) and not prev["not_started"] and perf.state == "error"
|
||||||
|
# 실적 모듈에서 사용 중이 아닌 쇼핑몰(설정에서 사용 OFF·없는 코드)은 늘 0 이라 자동으로 보지 않고 직접 입력
|
||||||
|
prev["market_off"] = bool(code) and perf.state != "error" and code not in names
|
||||||
|
if code and perf.readable and not prev["not_started"] and not prev["market_off"]:
|
||||||
|
got = week_sales(prev["week_start"])
|
||||||
|
if got is None:
|
||||||
|
prev["auto_error"] = True
|
||||||
|
else:
|
||||||
|
auto = got.get(code, 0)
|
||||||
|
prev["auto_result"] = auto
|
||||||
|
prev["result"] = auto if auto is not None else (None if prev["auto_error"] else prev.get("result_amount"))
|
||||||
|
prev["market_name"] = names.get(code, code)
|
||||||
|
for it in meeting["items"]:
|
||||||
|
code = it["marketplace_code"]
|
||||||
|
it["market_name"] = names.get(code, code) if code else ""
|
||||||
|
it["market_off"] = bool(code) and perf.state != "error" and code not in names
|
||||||
|
it["market_unknown"] = bool(code) and perf.state == "error"
|
||||||
|
# 이번 주 진행 중 실적(쇼핑몰 연결 줄) — 정량 목표 칸 아래에 "이번주 실적"
|
||||||
|
it["week_auto"], it["week_error"] = None, False
|
||||||
|
if code and week <= today and not it["market_off"]:
|
||||||
|
got = week_sales(meeting["week_start"]) if perf.readable else None
|
||||||
|
if got is None:
|
||||||
|
it["week_error"] = perf.state != "off"
|
||||||
|
else:
|
||||||
|
it["week_auto"] = got.get(code, 0)
|
||||||
|
p = it.get("prev")
|
||||||
|
it["rate"] = (round(p["result"] / p["target_amount"] * 100, 1)
|
||||||
|
if p and p.get("result") is not None and p.get("target_amount") else None)
|
||||||
|
# 구역 묶음 — 이어진 같은 구역 줄을 한 덩어리로(표의 구역 칸 rowspan)
|
||||||
|
sections: list[dict[str, Any]] = []
|
||||||
|
for it in meeting["items"]:
|
||||||
|
if not sections or sections[-1]["name"] != it["section"]:
|
||||||
|
sections.append({"name": it["section"], "color": it["section_color"], "rows": []})
|
||||||
|
sections[-1]["rows"].append(it) # 키 이름 rows — 템플릿의 sec.items 는 dict.items 메서드가 된다
|
||||||
|
meeting["sections"] = sections
|
||||||
|
prev_items = [it["prev"] for it in meeting["items"] if it.get("prev")]
|
||||||
|
head["prev_items_target"] = sum(p["target_amount"] or 0 for p in prev_items) if prev_items else None
|
||||||
|
return {"meeting": meeting, "head": head,
|
||||||
|
"markets": [{"code": m["code"], "name": m["name"]} for m in perf.markets]}
|
||||||
|
|
||||||
|
|
||||||
|
def _month_plan(st: Any, year: int, month: int) -> list[dict[str, Any]] | None:
|
||||||
|
"""회의록 위 "N월 계획" — 연간 목표 표의 그 달 열 글을 업무 영역별로(빈 칸은 뺌). 목표 표가 없으면 None.
|
||||||
|
가로 병합(예: 9~10월 칸)에 적은 글도 그 달 계획으로, 세로 병합은 한 번만. 항목 이름이 묶인 줄(016)은 묶음 이름."""
|
||||||
|
try:
|
||||||
|
board = st.get_goal_board(year=year) if st.goals_enabled() else None
|
||||||
|
except Exception: # noqa: BLE001 — 목표 표를 못 읽어도 회의록은 열린다
|
||||||
|
logger.warning("goal board unavailable for meeting plan", exc_info=True)
|
||||||
|
return None
|
||||||
|
if not board:
|
||||||
|
return None
|
||||||
|
out = []
|
||||||
|
for area in board["areas"]:
|
||||||
|
rows = area["rows"]
|
||||||
|
_goal_area_layout(rows, 0)
|
||||||
|
_goal_label_spans(rows)
|
||||||
|
items, label = [], ""
|
||||||
|
for row in rows:
|
||||||
|
if not row.get("label_cont"):
|
||||||
|
label = row.get("label") or ""
|
||||||
|
cell = next((c for c in row["layout"] if c["kind"] == "month" and c["m"] <= month <= c["m"] + c["span"] - 1), None)
|
||||||
|
text = (row["cells"].get(cell["m"], "") if cell else "").strip()
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
rng = f"{cell['m']}~{cell['m'] + cell['span'] - 1}월" if cell["span"] > 1 else ""
|
||||||
|
items.append({"label": label, "text": text, "range": rng})
|
||||||
|
if items:
|
||||||
|
out.append({"name": area["name"], "color": area["color"], "lines": items}) # 키 lines — 템플릿의 a.items 는 dict.items 메서드
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _meet_members() -> list[dict[str, str]]:
|
||||||
|
"""회의 참석자 후보 = 전체 멤버(project 모듈 권한 보유 등록 사용자) — 이름·이메일·사진."""
|
||||||
|
try:
|
||||||
|
from app.main import user_store # noqa: WPS433
|
||||||
|
from app.store import has_module # noqa: WPS433
|
||||||
|
|
||||||
|
out = [{"email": u["email"], "name": u.get("name") or u["email"].split("@")[0], "avatar": u.get("picture") or ""}
|
||||||
|
for u in user_store.list_all() if has_module(u, "project")]
|
||||||
|
except Exception: # noqa: BLE001 — 사용자 목록이 없어도 회의록은 열린다
|
||||||
|
logger.warning("meeting members unavailable", exc_info=True)
|
||||||
|
return []
|
||||||
|
return sorted(out, key=lambda m: m["name"])
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_attendees(text: str, members: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||||
|
"""참석자 칸(쉼표로 이은 이메일 — 예전엔 자유 입력 글자) → 칩 목록. 멤버 이메일이면 이름·사진, 아니면 글자 그대로."""
|
||||||
|
by_email = {m["email"].lower(): m for m in members}
|
||||||
|
out, seen = [], set()
|
||||||
|
for tok in str(text or "").replace("\n", ",").split(","):
|
||||||
|
t = tok.strip()
|
||||||
|
if not t or t.lower() in seen:
|
||||||
|
continue
|
||||||
|
seen.add(t.lower())
|
||||||
|
m = by_email.get(t.lower())
|
||||||
|
out.append({"key": m["email"] if m else t, "email": m["email"] if m else "", "name": m["name"] if m else t,
|
||||||
|
"avatar": m["avatar"] if m else ""})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/goals/{year}/meetings/{month}", response_class=HTMLResponse)
|
||||||
|
def goal_meeting_page(request: Request, year: int, month: int, week: str | None = None) -> HTMLResponse:
|
||||||
|
"""주간 회의록 — 그 달과 겹치는 주(월~일) 탭, 주마다 회의록 하나. 입력은 관리자만(목표 표와 같음)."""
|
||||||
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _store(request)
|
||||||
|
if st is None:
|
||||||
|
return _render_config_needed(request, user)
|
||||||
|
if not 2000 <= year <= 2100 or not 1 <= month <= 12:
|
||||||
|
raise HTTPException(status_code=404, detail="연도·월이 올바르지 않습니다.")
|
||||||
|
weeks = store.month_weeks(year, month)
|
||||||
|
today = today_kst()
|
||||||
|
sel = None
|
||||||
|
if week:
|
||||||
|
try:
|
||||||
|
sel = store.validate_week_start(week)
|
||||||
|
except ValueError:
|
||||||
|
sel = None
|
||||||
|
if sel is not None and (sel.year, sel.month) != (year, month):
|
||||||
|
# 다른 달의 주(주는 월요일이 속한 달의 것) — 그 달 회의록 주소로
|
||||||
|
return RedirectResponse(url=f"/project/goals/{sel.year}/meetings/{sel.month}?week={sel.isoformat()}",
|
||||||
|
status_code=303)
|
||||||
|
if sel is None or sel not in [w for w, _ in weeks]:
|
||||||
|
sel = next((w for w, e in weeks if w <= today <= e), weeks[0][0])
|
||||||
|
enabled = st.meetings_enabled()
|
||||||
|
cal = store.calendar_weeks(year, month)
|
||||||
|
existing = set(st.meeting_weeks(start=cal[0][0], end=cal[-1][0])) if enabled else set()
|
||||||
|
view = _meeting_view(request, st, year=year, month=month, week=sel) if enabled else {}
|
||||||
|
members = _meet_members()
|
||||||
|
admin = is_admin(user)
|
||||||
|
return render_template(
|
||||||
|
request,
|
||||||
|
"project/goal_meeting.html",
|
||||||
|
{
|
||||||
|
"user": user,
|
||||||
|
"is_admin": admin,
|
||||||
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
|
"nav_projects": _nav_projects(st, user, admin),
|
||||||
|
"goal_years": _goal_years_nav(st),
|
||||||
|
"goal_year_active": year,
|
||||||
|
"my_open_total": _my_open_count(st, user),
|
||||||
|
"mention_unread": _safe_mention_unread(st, user),
|
||||||
|
"page_title": f"{year}년 {month}월 주간 회의록",
|
||||||
|
"page_subtitle": "지난주 리뷰와 이번주 목표",
|
||||||
|
"force_sidebar_collapsed": True,
|
||||||
|
"color_palette": list(store.COLOR_PALETTE),
|
||||||
|
"project_icons": list(store.PROJECT_ICONS),
|
||||||
|
"goal_year": year,
|
||||||
|
"goal_month": month,
|
||||||
|
"meetings_enabled": enabled,
|
||||||
|
"weeks": [{"start": w.isoformat(), "end": e.isoformat(), "n": i + 1, "label": f"{w.month}/{w.day}~{e.month}/{e.day}",
|
||||||
|
"has": w.isoformat() in existing, "now": w <= today <= e,
|
||||||
|
# 작은 달력(월요일 시작) 한 줄 — 날짜·그 달 여부·오늘·요일(5 토, 6 일)·공휴일
|
||||||
|
"days": [{"d": (w + timedelta(days=k)).day, "iso": (w + timedelta(days=k)).isoformat(),
|
||||||
|
"in": (w + timedelta(days=k)).month == month, "today": w + timedelta(days=k) == today,
|
||||||
|
"wd": k, "hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
|
||||||
|
for k in range(7)]}
|
||||||
|
for i, (w, e) in enumerate(weeks)],
|
||||||
|
# 작은 달력 — 그 달 날짜가 든 주 전부(앞뒤 달에 속한 주는 흐리게, 누르면 그 달 회의록)
|
||||||
|
"cal_weeks": [{"start": w.isoformat(), "own": (w.year, w.month) == (year, month),
|
||||||
|
"href": (f"?week={w.isoformat()}" if (w.year, w.month) == (year, month)
|
||||||
|
else f"/project/goals/{w.year}/meetings/{w.month}?week={w.isoformat()}"),
|
||||||
|
"title": (f"{next(i + 1 for i, (x, _) in enumerate(weeks) if x == w)}주차"
|
||||||
|
if (w.year, w.month) == (year, month) else f"{w.month}월 주")
|
||||||
|
+ f" ({w.month}/{w.day}~{e.month}/{e.day})",
|
||||||
|
"has": w.isoformat() in existing,
|
||||||
|
"days": [{"d": (w + timedelta(days=k)).day, "in": (w + timedelta(days=k)).month == month,
|
||||||
|
"today": w + timedelta(days=k) == today, "wd": k,
|
||||||
|
"hol": store.KR_HOLIDAYS.get((w + timedelta(days=k)).isoformat(), "")}
|
||||||
|
for k in range(7)]}
|
||||||
|
for w, e in store.calendar_weeks(year, month)],
|
||||||
|
"week": sel.isoformat(),
|
||||||
|
"week_n": next(i + 1 for i, (w, _) in enumerate(weeks) if w == sel),
|
||||||
|
"week_end": (sel + timedelta(days=6)).isoformat(),
|
||||||
|
"prev_week": (sel - timedelta(days=7)).isoformat(),
|
||||||
|
"prev_week_end": (sel - timedelta(days=1)).isoformat(),
|
||||||
|
# 주차를 열면 다시 받을 매출 기간(실적 모듈 매출 업데이트) — 지난주 월요일 ~ 이번 주 일요일(오늘까지)
|
||||||
|
"sync_from": (sel - timedelta(days=7)).isoformat() if sel - timedelta(days=7) <= today else "",
|
||||||
|
"sync_to": min(sel + timedelta(days=6), today).isoformat(),
|
||||||
|
# 쇼핑몰 매출 갱신(실적 모듈 POST /performance/api/sync)은 실적 모듈 권한자만 — 없으면 화면이 부르지 않는다
|
||||||
|
"can_sync": has_module(user, "performance"),
|
||||||
|
"meeting_status": store.MEETING_STATUS,
|
||||||
|
"meet_members": members,
|
||||||
|
"month_plan": _month_plan(st, year, month),
|
||||||
|
"attendee_list": _parse_attendees((view.get("meeting") or {}).get("attendees", ""), members),
|
||||||
|
**view,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/goals/meetings/{week_start}")
|
||||||
|
def api_get_meeting(request: Request, week_start: str, year: int, month: int) -> JSONResponse:
|
||||||
|
"""회의록 다시 읽기(저장 뒤 머리 숫자·달성률 갱신용) — 화면과 같은 계산."""
|
||||||
|
_require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
if not 1 <= month <= 12:
|
||||||
|
raise HTTPException(status_code=400, detail="월이 올바르지 않습니다.")
|
||||||
|
view = _goal_call(_meeting_view, request, st, year=year, month=month, week=ws)
|
||||||
|
return JSONResponse(view)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meetings/{week_start}")
|
||||||
|
def api_create_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""회의록 만들기(관리자) — 앞선 회의록 줄을 이어받거나, 처음이면 그 해 목표 표 업무 영역 + 기본 양식 줄."""
|
||||||
|
user = _require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
year = _goal_call(store.validate_goal_year, payload.get("year") or ws.year)
|
||||||
|
created = _goal_call(st.create_meeting, week_start=ws, sections=st.goal_area_sections(year=year),
|
||||||
|
created_by=user["email"])
|
||||||
|
return JSONResponse({"ok": True, "created": created}, status_code=201 if created else 200)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/goals/meetings/{week_start}")
|
||||||
|
def api_update_meeting(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
user = _require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
fields = {k: payload[k] for k in ("week_target", "attendees", "notes") if k in payload}
|
||||||
|
_goal_call(st.update_meeting, week_start=ws, fields=fields, updated_by=user["email"])
|
||||||
|
out: dict[str, Any] = {"ok": True}
|
||||||
|
if "week_target" in fields: # 화면이 서버 확정값(원 정수)으로 칸을 맞춘다
|
||||||
|
out["week_target"] = store.validate_meeting_amount(fields["week_target"])
|
||||||
|
return JSONResponse(out)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/goals/meetings/{week_start}")
|
||||||
|
def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
|
||||||
|
_require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
_goal_call(st.delete_meeting, week_start=ws)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meetings/{week_start}/items")
|
||||||
|
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""줄 추가 {section, label?, ref_item_id?, place?: above|below} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝)."""
|
||||||
|
user = _require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
ref = payload.get("ref_item_id")
|
||||||
|
try:
|
||||||
|
ref_id = int(ref) if ref not in (None, "") else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="ref_item_id 가 올바르지 않습니다.")
|
||||||
|
item_id = _goal_call(
|
||||||
|
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
|
||||||
|
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
|
||||||
|
)
|
||||||
|
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/goals/meeting-items/{item_id}")
|
||||||
|
def api_update_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""줄 칸 하나 — label·content·target_amount·result_amount·status·marketplace_code. 전주 결과·평가는
|
||||||
|
이번 회의 화면에서 지난주 줄(prev)의 result_amount·status 로 저장한다."""
|
||||||
|
user = _require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
keys = ("label", "content", "target_amount", "result_amount", "status", "marketplace_code")
|
||||||
|
item = _goal_call(st.update_meeting_item, item_id=item_id,
|
||||||
|
fields={k: payload[k] for k in keys if k in payload}, updated_by=user["email"])
|
||||||
|
return JSONResponse({"ok": True, "item": item})
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/goals/meeting-items/{item_id}")
|
||||||
|
def api_delete_meeting_item(request: Request, item_id: int) -> JSONResponse:
|
||||||
|
_require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
_goal_call(st.delete_meeting_item, item_id=item_id)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meeting-items/{item_id}/move")
|
||||||
|
def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
_require_admin(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ DB 없이 단위 테스트 가능한 순수 함수만 둔다(malaysia.store 패
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
|
from datetime import date, timedelta
|
||||||
from html.parser import HTMLParser
|
from html.parser import HTMLParser
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -356,7 +357,7 @@ def validate_time(t: Any) -> str | None:
|
|||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스
|
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스(단위 %)
|
||||||
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
|
||||||
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
|
||||||
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
|
||||||
@@ -386,17 +387,54 @@ def validate_goal_year(y: Any) -> int:
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration014Needed(RuntimeError):
|
||||||
|
"""기간(분기) 글 칸·월 칸 병합은 마이그레이션 014(goal_cell_merges) 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration017Needed(RuntimeError):
|
||||||
|
"""2·4분기 글 칸(15·16)은 마이그레이션 017(분기) 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
|
||||||
|
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
|
||||||
|
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
|
||||||
|
GOAL_QUARTER_COL: dict[int, int] = {1: 13, 2: 15, 3: 14, 4: 16}
|
||||||
|
GOAL_COL_QUARTER: dict[int, int] = {c: q for q, c in GOAL_QUARTER_COL.items()}
|
||||||
|
GOAL_Q_NEW: tuple[int, ...] = (15, 16) # 017 이 있어야 저장되는 분기 칸
|
||||||
|
GOAL_MAX_COL = 16
|
||||||
|
|
||||||
|
|
||||||
|
def goal_quarter_of(month: int) -> int:
|
||||||
|
"""1~3월 → 1분기, 4~6월 → 2분기, 7~9월 → 3분기, 10~12월 → 4분기."""
|
||||||
|
return (int(month) - 1) // 3 + 1
|
||||||
|
|
||||||
|
|
||||||
def validate_goal_month(m: Any, *, allow_year: bool = False) -> int:
|
def validate_goal_month(m: Any, *, allow_year: bool = False) -> int:
|
||||||
"""1~12월. allow_year 이면 0(연간)도 허용."""
|
"""1~12월. allow_year 이면 업무 영역 글 칸 — 0(연간)·13~16(분기 칸, GOAL_QUARTER_COL)도 허용."""
|
||||||
try:
|
try:
|
||||||
v = int(m)
|
v = int(m)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
raise ValueError("월이 올바르지 않습니다.")
|
raise ValueError("월이 올바르지 않습니다.")
|
||||||
if not ((0 if allow_year else 1) <= v <= 12):
|
if not ((0 if allow_year else 1) <= v <= (GOAL_MAX_COL if allow_year else 12)):
|
||||||
raise ValueError("월이 올바르지 않습니다.")
|
raise ValueError("월이 올바르지 않습니다.")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def validate_goal_merge(start: Any, end: Any) -> tuple[int, int]:
|
||||||
|
"""월 칸 병합 범위(start~end 월, 2칸 이상) — 분기를 넘지 않는다."""
|
||||||
|
try:
|
||||||
|
s, e = int(start), int(end)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("병합할 월이 올바르지 않습니다.")
|
||||||
|
if s > e:
|
||||||
|
s, e = e, s
|
||||||
|
if not (1 <= s and e <= 12) or s == e:
|
||||||
|
raise ValueError("병합은 1~12월 안에서 2칸 이상 골라야 합니다.")
|
||||||
|
if goal_quarter_of(s) != goal_quarter_of(e):
|
||||||
|
raise ValueError("분기(1~3·4~6·7~9·10~12월)를 넘어 병합할 수 없습니다.")
|
||||||
|
return s, e
|
||||||
|
|
||||||
|
|
||||||
def validate_goal_value(v: Any) -> float | None:
|
def validate_goal_value(v: Any) -> float | None:
|
||||||
"""지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움)."""
|
"""지표 숫자 — '1,234.5' 같은 쉼표·공백·% 는 떼고 읽는다. 빈값은 None(=지움)."""
|
||||||
s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "")
|
s = norm_str(v).replace(",", "").replace("%", "").replace(" ", "")
|
||||||
@@ -442,6 +480,171 @@ def validate_goal_text(body: Any) -> str:
|
|||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
# ── 엑셀식 사각형 병합(마이그레이션 015) ──────────────────────────────
|
||||||
|
class GoalMigration015Needed(RuntimeError):
|
||||||
|
"""세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class GoalMigration016Needed(RuntimeError):
|
||||||
|
"""항목 칸(2열) 묶음(같은 항목 칸 안에 줄 추가)은 마이그레이션 016 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
# 업무 영역 글 칸의 화면 순서 — 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 · 7~9월 · 3분기 · 10~12월 · 4분기
|
||||||
|
GOAL_COL_ORDER: tuple[int, ...] = (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
|
||||||
|
|
||||||
|
|
||||||
|
def goal_col_group(m: int) -> str:
|
||||||
|
"""병합 가능 묶음 — 가로 병합은 같은 묶음 안에서만(연간·분기 칸은 혼자, 월은 같은 분기끼리)."""
|
||||||
|
if m == GOAL_YEAR:
|
||||||
|
return "year"
|
||||||
|
if m in GOAL_COL_QUARTER:
|
||||||
|
return f"q{GOAL_COL_QUARTER[m]}"
|
||||||
|
return f"months{goal_quarter_of(m)}"
|
||||||
|
|
||||||
|
|
||||||
|
def validate_goal_rect_cols(col_from: Any, col_to: Any) -> tuple[int, int]:
|
||||||
|
"""병합할 칸 범위(화면 순서의 양 끝 칸 번호) → (시작 칸 번호, 가로 칸 수).
|
||||||
|
가로로 여러 칸이면 같은 분기의 월 칸끼리만 — 연간·분기 칸은 세로로만 합칠 수 있다."""
|
||||||
|
try:
|
||||||
|
a, b = int(col_from), int(col_to)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("병합할 칸이 올바르지 않습니다.")
|
||||||
|
if a not in GOAL_COL_ORDER or b not in GOAL_COL_ORDER:
|
||||||
|
raise ValueError("병합할 칸이 올바르지 않습니다.")
|
||||||
|
ia, ib = sorted((GOAL_COL_ORDER.index(a), GOAL_COL_ORDER.index(b)))
|
||||||
|
cols = GOAL_COL_ORDER[ia:ib + 1]
|
||||||
|
if len({goal_col_group(m) for m in cols}) > 1:
|
||||||
|
raise ValueError("연간·분기 칸은 세로로만, 월 칸은 같은 분기 안에서만 합칠 수 있습니다.")
|
||||||
|
return cols[0], len(cols)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 주간 회의록(마이그레이션 015) — 월 머리를 누르면 그 달 주차별 회의록 ──────────
|
||||||
|
MEETING_STATUS: dict[str, str] = {"": "", "done": "완료", "partial": "일부", "miss": "미달"}
|
||||||
|
MEETING_TEXT_MAX = 4000
|
||||||
|
MEETING_LABEL_MAX = 50
|
||||||
|
# 첫 회의록(이전 주 회의록이 없을 때)의 구역별 줄 — 사용자 회의록 양식(2026-10). 목표 표의 업무 영역 이름과 같으면
|
||||||
|
# 그 줄들로, 없는 구역은 빈 줄 하나. 다음 주부터는 지난주 회의록 줄을 그대로 이어받는다.
|
||||||
|
MEETING_TEMPLATE: dict[str, tuple[str, ...]] = {
|
||||||
|
"상품": ("상품1", "상품2", "상품3", "상품4", "상품5"),
|
||||||
|
"마케팅": ("메타", "구글", "네이버", "기타.신규"),
|
||||||
|
"컨텐츠": ("내용1", "내용2", "내용3", "내용4", "내용5"),
|
||||||
|
"유통": ("신규 인플루언서", "콜라보", "쿠팡", "네이버", "gs", "토스", "애터미", "해외", "오프라인", "기타"),
|
||||||
|
}
|
||||||
|
# 유통 줄 이름 → 실적 모듈 쇼핑몰 코드(그 주 결과를 실적에서 자동으로). 첫 단어 기준, 소문자 비교.
|
||||||
|
MEETING_MARKET_GUESS: tuple[tuple[str, str], ...] = (
|
||||||
|
("쿠팡", "coupang"), ("네이버", "naver"), ("스마트스토어", "naver"), ("gs", "gsshop"), ("토스", "toss"),
|
||||||
|
("11번가", "elevenst"), ("카페24", "cafe24"), ("자사몰", "cafe24"), ("롯데", "lotteon"), ("지마켓", "gmarket"),
|
||||||
|
("g마켓", "gmarket"), ("카카오", "kakao"), ("오늘의집", "ohouse"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def guess_meeting_market(section: str, label: str) -> str:
|
||||||
|
"""유통 구역 줄 이름으로 실적 쇼핑몰 코드 추측(없으면 ""). 마케팅의 "네이버"(광고)는 연결하지 않는다."""
|
||||||
|
if norm_str(section) != "유통":
|
||||||
|
return ""
|
||||||
|
lb = norm_str(label).lower()
|
||||||
|
for word, code in MEETING_MARKET_GUESS:
|
||||||
|
if lb.startswith(word):
|
||||||
|
return code
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def week_monday(d: date) -> date:
|
||||||
|
return d - timedelta(days=d.weekday())
|
||||||
|
|
||||||
|
|
||||||
|
def month_last_day(year: int, month: int) -> date:
|
||||||
|
return date(year + (month == 12), month % 12 + 1, 1) - timedelta(days=1)
|
||||||
|
|
||||||
|
|
||||||
|
def month_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||||
|
"""그 달의 주(월요일~일요일) 목록 — **1주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||||
|
(2026-10-01 사용자 기준). 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 주는 9월 마지막 주.
|
||||||
|
월간 목표·누적은 이와 따로 늘 1일~말일."""
|
||||||
|
first = date(year, month, 1)
|
||||||
|
last = month_last_day(year, month)
|
||||||
|
out, mon = [], first + timedelta(days=(7 - first.weekday()) % 7)
|
||||||
|
while mon <= last:
|
||||||
|
out.append((mon, mon + timedelta(days=6)))
|
||||||
|
mon += timedelta(days=7)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def calendar_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||||
|
"""작은 달력용 — 그 달 날짜가 하나라도 든 주(월요일 시작) 전부(1일이 든 주부터 말일이 든 주까지)."""
|
||||||
|
first, last = date(year, month, 1), month_last_day(year, month)
|
||||||
|
out, mon = [], week_monday(first)
|
||||||
|
while mon <= last:
|
||||||
|
out.append((mon, mon + timedelta(days=6)))
|
||||||
|
mon += timedelta(days=7)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def validate_week_start(v: Any) -> date:
|
||||||
|
try:
|
||||||
|
d = date.fromisoformat(str(v).strip()[:10])
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||||
|
if d.weekday() != 0:
|
||||||
|
raise ValueError("주 시작일은 월요일이어야 합니다.")
|
||||||
|
if not 2000 <= d.year <= 2100:
|
||||||
|
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def _korean_amount(s: str) -> float:
|
||||||
|
""""1억2천만"·"3천만"·"1.5억"·"120만"·"3천5백" → 숫자. 단위 없는 숫자는 그대로. 틀리면 ValueError."""
|
||||||
|
def small(t: str) -> float: # 만 아래 자리 — 천·백·십
|
||||||
|
val = 0.0
|
||||||
|
for unit, mul in (("천", 1_000), ("백", 100), ("십", 10)):
|
||||||
|
if unit in t:
|
||||||
|
a, t = t.split(unit, 1)
|
||||||
|
val += (float(a) if a else 1.0) * mul
|
||||||
|
return val + (float(t) if t else 0.0)
|
||||||
|
|
||||||
|
total, rest = 0.0, s
|
||||||
|
for unit, mul in (("억", 100_000_000), ("만", 10_000)):
|
||||||
|
if unit in rest:
|
||||||
|
a, rest = rest.split(unit, 1)
|
||||||
|
total += (small(a) if a else 1.0) * mul
|
||||||
|
return total + small(rest)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_amount(v: Any) -> int | None:
|
||||||
|
"""금액(원) — 쉼표·공백·"원" 은 떼고, "120만"·"1.5억"·"3천만"·"1억2천만" 도 읽는다. 빈값은 None(=지움)."""
|
||||||
|
s = norm_str(v).replace(",", "").replace(" ", "").rstrip("원")
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
f = _korean_amount(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"금액은 숫자로 입력하세요(예: 1,200,000 · 120만 · 1.5억 · 3천만): {v}")
|
||||||
|
if f != f or abs(f) >= 1e15:
|
||||||
|
raise ValueError(f"금액 범위를 벗어났습니다: {v}")
|
||||||
|
return int(round(f))
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_text(v: Any, *, limit: int = MEETING_TEXT_MAX, what: str = "내용") -> str:
|
||||||
|
s = str(v or "").replace("\r\n", "\n").strip()
|
||||||
|
if len(s) > limit:
|
||||||
|
raise ValueError(f"{what}은(는) {limit}자까지 쓸 수 있습니다.")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def validate_meeting_status(v: Any) -> str:
|
||||||
|
s = norm_str(v)
|
||||||
|
if s not in MEETING_STATUS:
|
||||||
|
raise ValueError("평가 값이 올바르지 않습니다.")
|
||||||
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def sales_unit_multiplier(unit: str) -> int | None:
|
||||||
|
"""목표 표의 매출 단위 글자 → 원 배수("백만원" → 1,000,000). 모르는 단위면 None(원 환산 안 함)."""
|
||||||
|
u = norm_str(unit).replace(" ", "").rstrip("원") or ""
|
||||||
|
table = {"": 1, "천": 1_000, "만": 10_000, "십만": 100_000, "백만": 1_000_000, "천만": 10_000_000, "억": 100_000_000}
|
||||||
|
return table.get(u)
|
||||||
|
|
||||||
|
|
||||||
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
||||||
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,300 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||||
|
|
||||||
|
{%- macro won(v) -%}{% if v is not none %}{{ "{:,}".format(v) }}{% endif %}{%- endmacro -%}
|
||||||
|
{%- macro num(v) -%}{% if v is not none %}{% if v == v | int %}{{ "{:,}".format(v | int) }}{% else %}{{ "{:,.2f}".format(v) }}{% endif %}{% endif %}{%- endmacro -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=월요일).
|
||||||
|
주(월~일)마다 회의록 하나: 머리(월 목표·지난주까지 누적·주당 필요 매출, 전주 목표·결과, 금주 목표·현재)
|
||||||
|
+ 구역(목표 표 업무 영역)별 줄 — 이번주 할 일·정량 목표 | 전주 할 일·목표·결과·달성률·평가.
|
||||||
|
전주 칸은 지난 회의록의 같은 줄(carry_from). 쇼핑몰 연결 줄의 결과·전주/금주 매출·누적은 실적 모듈에서 자동.
|
||||||
|
입력은 관리자만(칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015 (goal_meetings·goal_meeting_items). #}
|
||||||
|
<div class="pj-wrap pj-inbox-view pj-goal-view pj-meet-view" data-me="{{ (user.email if user else '') | lower }}">
|
||||||
|
<div class="pj-layout">
|
||||||
|
{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}
|
||||||
|
|
||||||
|
<section class="pj-main">
|
||||||
|
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력 #}
|
||||||
|
<div class="pj-meet-headgrid">
|
||||||
|
<div class="pj-meet-headleft">
|
||||||
|
<div class="pj-meet-title">
|
||||||
|
{# 연간 목표로 — 눈에 잘 띄는 큰 버튼(예전 ← 화살표 대신) #}
|
||||||
|
<a class="pj-meet-goalbtn" href="/project/goals/{{ goal_year }}" title="{{ goal_year }}년 연간 목표로"><span class="material-symbols-outlined">flag</span><span>{{ goal_year }}년 목표</span></a>
|
||||||
|
<h2 class="pj-goal-title">{{ goal_year }}년 {{ goal_month }}월 주간 회의록</h2>
|
||||||
|
{% set pm = goal_month - 1 if goal_month > 1 else 12 %}{% set py = goal_year if goal_month > 1 else goal_year - 1 %}
|
||||||
|
{% set nm = goal_month + 1 if goal_month < 12 else 1 %}{% set ny = goal_year if goal_month < 12 else goal_year + 1 %}
|
||||||
|
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ py }}/meetings/{{ pm }}">‹ {{ pm }}월</a>
|
||||||
|
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ ny }}/meetings/{{ nm }}">{{ nm }}월 ›</a>
|
||||||
|
{% if meeting %}
|
||||||
|
<span class="pj-meet-title-acts">
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
|
||||||
|
{% if is_admin %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>
|
||||||
|
{% else %}<span class="pj-goal-note">회의록은 관리자만 입력할 수 있습니다.</span>{% endif %}
|
||||||
|
</span>
|
||||||
|
{% endif %}
|
||||||
|
{# 주차 탭 — 주 = 월요일~일요일, 1주차 = 그 달 첫 월요일이 있는 주(주는 월요일이 속한 달). 점 = 회의록 있음 #}
|
||||||
|
<nav class="pj-meet-weeks" aria-label="주차">
|
||||||
|
{% for w in weeks %}
|
||||||
|
<a class="pj-meet-week{% if w.start == week %} is-on{% endif %}{% if w.now %} is-now{% endif %}"
|
||||||
|
href="?week={{ w.start }}" title="{{ w.n }}주차 {{ w.label }}">
|
||||||
|
{# 날짜는 짧게 — 같은 달이면 끝 월 생략(10/5~11), 달이 넘어가면 10/26~11/1 #}
|
||||||
|
{% set ws = w.start.split('-') %}{% set we = w.end.split('-') %}
|
||||||
|
<b>{{ w.n }}주차</b><span>{{ ws[1] | int }}/{{ ws[2] | int }}~{% if we[1] != ws[1] %}{{ we[1] | int }}/{% endif %}{{ we[2] | int }}</span>
|
||||||
|
{% if w.has %}<i class="pj-meet-dot" title="회의록 있음"></i>{% endif %}
|
||||||
|
{% if w.now %}<em>이번 주</em>{% endif %}
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
{# 이 달 계획 — 연간 목표 표의 그 달 열 글(업무 영역별, router._month_plan) #}
|
||||||
|
{% if month_plan is not none %}
|
||||||
|
<section class="pj-meet-plan">
|
||||||
|
<div class="pj-meet-plan-head"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</div>
|
||||||
|
{% if month_plan %}
|
||||||
|
<div class="pj-meet-plan-grid">
|
||||||
|
{% for a in month_plan %}
|
||||||
|
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
|
||||||
|
<b class="pj-meet-plan-name">{{ a.name }}</b>
|
||||||
|
{% for it in a.lines %}
|
||||||
|
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{# 작은 달력 — 월요일 시작(주 = 월~일), 보고 있는 주는 영역 표시, 줄을 누르면 그 주 회의록. 점 = 회의록 있음.
|
||||||
|
1주차 = 그 달 첫 월요일이 있는 주 — 1일 앞쪽 날짜가 든 주는 앞 달 주(흐리게, 누르면 앞 달 회의록). #}
|
||||||
|
<div class="pj-meet-cal" aria-label="{{ goal_month }}월 달력">
|
||||||
|
<div class="pj-meet-cal-head">{{ goal_year }}년 {{ goal_month }}월</div>
|
||||||
|
<div class="pj-meet-cal-wd"><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span><span class="is-sun">일</span></div>
|
||||||
|
{% for w in cal_weeks %}
|
||||||
|
<a class="pj-meet-cal-row{% if w.start == week %} is-on{% endif %}{% if not w.own %} is-other{% endif %}" href="{{ w.href }}"
|
||||||
|
title="{{ w.title }}{% if w.has %} · 회의록 있음{% endif %}{% if not w.own %} — 이 주는 {{ w.title.split('월')[0] }}월 회의록{% endif %}">
|
||||||
|
{% for d in w.days %}<span class="pj-meet-cal-d{% if not d.in %} is-out{% endif %}{% if d.today %} is-today{% endif %}{% if d.wd == 5 %} is-sat{% endif %}{% if d.wd == 6 or d.hol %} is-sun{% endif %}"{% if d.hol %} title="{{ d.hol }}"{% endif %}>{{ d.d }}</span>{% endfor %}
|
||||||
|
{% if w.has %}<i class="pj-meet-cal-dot"></i>{% endif %}
|
||||||
|
</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pj-view pj-meet-pane" id="pj-meet-pane" data-week="{{ week }}" data-year="{{ goal_year }}"
|
||||||
|
data-month="{{ goal_month }}" data-admin="{{ 'true' if is_admin else 'false' }}">
|
||||||
|
|
||||||
|
{% if not meetings_enabled %}
|
||||||
|
<div class="pj-empty">주간 회의록이 아직 준비되지 않았습니다(DB 마이그레이션 015 필요).</div>
|
||||||
|
{% elif not meeting %}
|
||||||
|
<div class="pj-empty pj-goal-empty">
|
||||||
|
<p>{{ week_n }}주차({{ week }} ~ {{ week_end }}) 회의록이 아직 없습니다.</p>
|
||||||
|
{% if is_admin %}
|
||||||
|
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목·쇼핑몰 연결)을 이어받아, 지난주 할 일·목표·결과를 나란히 리뷰할 수 있습니다.
|
||||||
|
처음이면 {{ goal_year }}년 목표 표의 업무 영역과 기본 양식 줄로 시작합니다.</p>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-meet-create">{{ week_n }}주차 회의록 만들기</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
{% set h = head %}
|
||||||
|
{% set edit = is_admin %}
|
||||||
|
{% set unk = h.unknown or [] %}
|
||||||
|
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
|
||||||
|
{# ── 숫자 — 한 줄 막대(월 목표 대비 누적·남은 주 필요 매출 | 전주 리뷰 | 금주 목표) ── #}
|
||||||
|
<div class="pj-meet-kpibar">
|
||||||
|
<div class="pj-meet-kpis">
|
||||||
|
<div class="pj-meet-kpi">
|
||||||
|
<span class="pj-meet-kpi-label">월 목표 매출</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">목표 표에 없음</span>{% endif %}</span>
|
||||||
|
{% if h.month_target_won is not none and h.sales_unit and h.sales_unit != '원' %}<span class="pj-meet-kpi-sub">= {{ won(h.month_target_won) }}원</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||||
|
<span class="pj-meet-kpi-label">월 누적 실적 <small>(지난주까지)</small></span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ won(h.mtd) }}<small>원</small>{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
{% if h.month_target_won and h.mtd is not none %}<span class="pj-meet-kpi-sub">달성 {{ "%.1f" | format(h.mtd / h.month_target_won * 100) }}%</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi is-accent" title="월 목표 − 누적을 이번 주 포함 남은 주로 나눈 값">
|
||||||
|
<span class="pj-meet-kpi-label">주당 필요 <small>(남은 {{ h.weeks_left }}주)</small></span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.need_per_week is not none %}{{ won(h.need_per_week) }}<small>원</small>{% elif 'mtd' in unk and h.month_target_won is not none %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi">
|
||||||
|
<span class="pj-meet-kpi-label">목표 ROAS</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.roas_target is not none %}{{ num(h.roas_target) }}<small>%</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpis is-week">
|
||||||
|
<div class="pj-meet-kpi">
|
||||||
|
<span class="pj-meet-kpi-label">전주 목표</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.prev_target is not none %}{{ won(h.prev_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||||
|
<span class="pj-meet-kpi-label">전주 결과 <small>({{ prev_week[5:] | replace('-', '/') }}~ 실적)</small></span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.prev_result is not none %}{{ won(h.prev_result) }}<small>원</small>{% elif 'prev_result' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi">
|
||||||
|
<span class="pj-meet-kpi-label">전주 달성률</span>
|
||||||
|
{% if h.prev_target and h.prev_result is not none %}{% set r = h.prev_result / h.prev_target * 100 %}
|
||||||
|
<span class="pj-meet-kpi-val {{ 'is-good' if r >= 100 else 'is-low' }}">{{ "%.1f" | format(r) }}<small>%</small></span>
|
||||||
|
{% elif h.prev_target and 'prev_result' in unk %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
|
||||||
|
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi is-input">
|
||||||
|
<span class="pj-meet-kpi-label">금주 목표</span>
|
||||||
|
{% if edit %}
|
||||||
|
<span class="pj-meet-kpi-val"><input type="text" class="pj-meet-amount" id="pj-meet-target" inputmode="decimal"
|
||||||
|
autocomplete="off" placeholder="{{ won(h.need_per_week) if h.need_per_week is not none else '예: 30,000,000' }}"
|
||||||
|
value="{{ won(meeting.week_target) }}" /><small>원</small></span>
|
||||||
|
{% else %}
|
||||||
|
<span class="pj-meet-kpi-val">{% if meeting.week_target is not none %}{{ won(meeting.week_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
{% endif %}
|
||||||
|
<span class="pj-meet-sub-slot">{% if h.need_per_week is not none %}<span class="pj-meet-kpi-sub">필요 {{ won(h.need_per_week) }}원</span>{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||||
|
<span class="pj-meet-kpi-label">금주 현재 실적</span>
|
||||||
|
<span class="pj-meet-kpi-val">{% if h.week_result is not none %}{{ won(h.week_result) }}<small>원</small>{% elif 'week_result' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||||
|
{% if meeting.week_target and h.week_result is not none %}<span class="pj-meet-kpi-sub">목표의 {{ "%.1f" | format(h.week_result / meeting.week_target * 100) }}%</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난주 월요일 ~ 이번 주 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
|
||||||
|
(project.js initMeetingSync, 같은 주는 10분에 한 번). 정상이면 아무것도 보이지 않는다(2026-10-01 요청 — 큰 상태 줄 없음).
|
||||||
|
실패·일부 실패면 이 작은 안내 + [다시 시도], 실적 권한이 없으면 부르지 않고 한 줄 설명. 마지막 갱신 성공 시각은 서버 기록(data-fresh). #}
|
||||||
|
{% if h.perf and sync_from %}<div id="pj-meet-sync" class="pj-meet-syncnote" hidden role="status" aria-live="polite"
|
||||||
|
data-from="{{ sync_from }}" data-to="{{ sync_to }}" data-can="{{ '1' if can_sync else '0' }}" data-fresh="{{ h.fresh_oldest }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">sync_problem</span><span class="pj-meet-sync-text"></span>
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-sync-btn" hidden>다시 시도</button>
|
||||||
|
</div>{% endif %}
|
||||||
|
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적·쇼핑몰 자동 결과는 비어 있습니다(결과는 직접 입력).</p>
|
||||||
|
{% elif h.perf_state == 'error' %}<p class="pj-goal-note pj-meet-perf-warn">실적 모듈 쇼핑몰 목록을 읽지 못해 실적·누적·쇼핑몰 자동 결과를 <b>미확인</b>으로 표시합니다(0 원이 아님). 회의록 입력은 그대로 됩니다.</p>
|
||||||
|
{% elif h.perf_state == 'empty' %}<p class="pj-goal-note">실적 모듈에 매출 집계 쇼핑몰이 없어 실적·누적은 비어 있습니다.</p>
|
||||||
|
{% elif unk %}<p class="pj-goal-note pj-meet-perf-warn">일부 실적을 읽지 못했습니다 — <b>미확인</b> 칸은 0 원이 아니라 알 수 없는 값입니다.</p>{% endif %}
|
||||||
|
|
||||||
|
{# 참석자 — 전체 멤버에서 고른다(칩, [참석자] = 고르기 창). 저장은 이메일을 쉼표로 이어서, 예전 자유 입력 글자도 칩으로 #}
|
||||||
|
<div class="pj-meet-attend">
|
||||||
|
<span class="pj-meet-attend-label">참석자</span>
|
||||||
|
<div class="pj-meet-attend-chips" id="pj-meet-attend"{% if edit %} data-edit="1"{% endif %}>
|
||||||
|
{% for a in attendee_list %}<span class="pj-meet-chip" data-key="{{ a.key }}" data-name="{{ a.name }}" data-avatar="{{ a.avatar }}"{% if not a.email %} title="멤버가 아닌 글자(예전 입력)"{% endif %}>
|
||||||
|
{%- if a.avatar %}<img class="pj-avatar" src="{{ a.avatar }}" alt="" referrerpolicy="no-referrer">{% else %}<span class="pj-meet-chip-ini">{{ a.name[:1] }}</span>{% endif %}<span>{{ a.name }}</span>
|
||||||
|
{%- if edit %}<button type="button" class="pj-meet-chip-x" title="빼기" aria-label="{{ a.name }} 빼기">×</button>{% endif %}</span>{% endfor %}
|
||||||
|
{% if edit %}<button type="button" class="pj-meet-attend-add" id="pj-meet-attend-add"><span class="material-symbols-outlined">person_add</span>참석자</button>
|
||||||
|
{% elif not attendee_list %}<span class="pj-muted">—</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
|
||||||
|
<table class="pj-meet-table" id="pj-meet-table">
|
||||||
|
{# table-layout: fixed 는 첫 줄(묶음 머리, colspan)로 너비를 정하므로 열 너비는 colgroup 으로 #}
|
||||||
|
<colgroup>
|
||||||
|
{# is-this / is-prev — 순서 바꾸기(project.js initMeetOrder)가 이 묶음으로 열을 옮긴다 #}
|
||||||
|
<col class="pj-meet-w-sec" /><col class="pj-meet-w-label" /><col class="is-this" /><col class="pj-meet-w-amt is-this" />
|
||||||
|
<col class="is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-rate is-prev" /><col class="pj-meet-w-eval is-prev" />
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr class="pj-meet-group">
|
||||||
|
{# 이번주 ↔ 지난주 리뷰 순서 바꾸기 — 보는 사람마다 브라우저에 기억(localStorage pj_meet_order:{이메일}) #}
|
||||||
|
<th colspan="2" class="pj-meet-order-cell"><button type="button" class="pj-meet-order-btn" id="pj-meet-order"
|
||||||
|
title="이번주와 지난주 리뷰의 순서 바꾸기(내 화면에 기억)"><span class="material-symbols-outlined">swap_horiz</span>순서 바꾸기</button></th>
|
||||||
|
<th colspan="2" class="is-this">이번주 ({{ week[5:] | replace('-', '/') }} ~ {{ week_end[5:] | replace('-', '/') }})</th>
|
||||||
|
{# 지난주 = 정확히 7일 전 주 — 줄의 지난주 칸·결과·달성률도 이 주 회의록의 같은 줄(연결키)만 #}
|
||||||
|
<th colspan="5" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th class="pj-meet-c-sec">구역</th>
|
||||||
|
<th class="pj-meet-c-label">항목</th>
|
||||||
|
<th class="pj-meet-c-text">이번주 할 일 · 행사</th>
|
||||||
|
<th class="pj-meet-c-amt">정량 목표</th>
|
||||||
|
<th class="pj-meet-c-text is-prev">지난주 할 일</th>
|
||||||
|
<th class="pj-meet-c-amt is-prev">지난주 목표</th>
|
||||||
|
<th class="pj-meet-c-amt is-prev">결과</th>
|
||||||
|
<th class="pj-meet-c-rate is-prev">달성률</th>
|
||||||
|
<th class="pj-meet-c-eval is-prev">평가</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
{% for sec in meeting.sections %}
|
||||||
|
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
|
||||||
|
{% for it in sec.rows %}
|
||||||
|
{% set p = it.prev %}
|
||||||
|
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}" data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
||||||
|
{% if loop.first %}
|
||||||
|
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
|
||||||
|
{% if edit %}<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
||||||
|
</th>
|
||||||
|
{% endif %}
|
||||||
|
<th class="pj-meet-c-label">
|
||||||
|
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||||
|
{% if it.market_unknown %}<span class="pj-meet-market is-unknown" title="실적 모듈 쇼핑몰 목록을 읽지 못해 이 연결의 실적을 확인할 수 없습니다">{{ it.market_name }} · 미확인</span>
|
||||||
|
{% elif it.market_off %}<span class="pj-meet-market is-off" title="실적 모듈에서 사용 중인 쇼핑몰이 아닙니다(실적 설정에서 사용 OFF 이거나 없는 쇼핑몰) — 결과는 직접 입력">{{ it.market_name }} · 실적 미사용</span>
|
||||||
|
{% elif it.market_name %}<span class="pj-meet-market" title="결과를 실적 모듈 {{ it.market_name }} 매출에서 자동으로">{{ it.market_name }}</span>{% endif %}
|
||||||
|
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
||||||
|
</th>
|
||||||
|
<td class="pj-meet-c-text">
|
||||||
|
{% if edit %}<textarea class="pj-meet-text" rows="1" data-field="content" placeholder="이번주 할 일·행사">{{ it.content }}</textarea>
|
||||||
|
{% else %}<div class="pj-meet-ro">{{ it.content }}</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="pj-meet-c-amt">
|
||||||
|
{% if edit %}<input type="text" class="pj-meet-amount" data-field="target_amount" inputmode="decimal" autocomplete="off" value="{{ won(it.target_amount) }}" />
|
||||||
|
{% else %}{{ won(it.target_amount) }}{% endif %}
|
||||||
|
{# 이번주 실적 — data-auto = 실적(서버), % 는 화면이 서버 확정 정량 목표(tr data-target-amount)로 다시 계산(project.js paintMeetWeek) #}
|
||||||
|
<span class="pj-meet-week-slot" data-auto="{{ it.week_auto if it.week_auto is not none else '' }}"{% if it.week_error %} data-err="1"{% endif %} data-name="{{ it.market_name }}">{% if it.week_auto is not none %}<span class="pj-meet-week-auto" title="실적 모듈 {{ it.market_name }} 이번 주({{ week[5:] | replace('-', '/') }}~ 오늘까지) 매출">이번주 실적 {{ won(it.week_auto) }}{% if it.target_amount %} · {{ "%.0f" | format(it.week_auto / it.target_amount * 100) }}%{% endif %}</span>{% elif it.week_error %}<span class="pj-meet-week-auto is-unknown" title="실적 조회 실패">이번주 실적 미확인</span>{% endif %}</span>
|
||||||
|
</td>
|
||||||
|
{% if p %}
|
||||||
|
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{{ p.content }}</div></td>
|
||||||
|
<td class="pj-meet-c-amt is-prev">{{ won(p.target_amount) }}</td>
|
||||||
|
<td class="pj-meet-c-amt is-prev pj-meet-c-result">
|
||||||
|
{% if p.not_started %}
|
||||||
|
<span class="pj-muted" title="지난 회의록의 주({{ p.period }})가 아직 시작되지 않았습니다">진행 전</span>
|
||||||
|
{% elif p.auto_error %}
|
||||||
|
<span class="pj-meet-unknown" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출을 읽지 못했습니다 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>
|
||||||
|
{% elif p.auto_result is not none %}
|
||||||
|
<span class="pj-meet-auto" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출(자동){% if not p.auto_result %} — 0 이면 그 기간 실적이 아직 없습니다(실적 화면 [매출 업데이트]){% endif %}">{{ won(p.auto_result) }}</span>
|
||||||
|
{% elif edit %}<input type="text" class="pj-meet-amount" data-field="result_amount" data-target="prev" inputmode="decimal" autocomplete="off" value="{{ won(p.result_amount) }}" placeholder="결과" />
|
||||||
|
{% else %}{{ won(p.result_amount) }}{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="pj-meet-c-rate is-prev" data-rate>{% if it.rate is not none %}<span class="{{ 'is-good' if it.rate >= 100 else 'is-low' }}">{{ it.rate }}%</span>{% endif %}</td>
|
||||||
|
<td class="pj-meet-c-eval is-prev">
|
||||||
|
{% if edit %}
|
||||||
|
<select class="pj-meet-eval" data-field="status" data-target="prev" data-v="{{ p.status }}">
|
||||||
|
{% for k, v in meeting_status.items() %}<option value="{{ k }}"{% if k == p.status %} selected{% endif %}>{{ v or '—' }}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
{% else %}<span class="pj-meet-eval-ro" data-v="{{ p.status }}">{{ meeting_status[p.status] or '—' }}</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
{% else %}
|
||||||
|
<td class="pj-meet-c-text is-prev is-none" colspan="5"><span class="pj-muted">{% if h.prev_exists %}지난주 회의록에 없는 줄{% else %}지난주({{ prev_week[5:] | replace('-', '/') }}~) 회의록 없음{% endif %}</span></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
{% endfor %}
|
||||||
|
</table>
|
||||||
|
{% if edit %}
|
||||||
|
<div class="pj-goal-foot">
|
||||||
|
<button type="button" class="pj-btn" id="pj-meet-sec-new">+ 구역 추가</button>
|
||||||
|
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 금액은 원 단위(120만·1.5억도 됨). 항목을 우클릭하거나 ⋯ 를 누르면
|
||||||
|
줄 추가·순서·삭제·쇼핑몰 연결(결과를 실적에서 자동). 지난주 결과·평가는 지난 회의록 줄에 저장됩니다.</span>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="pj-meet-notes">
|
||||||
|
<h3>결정 사항 · 메모</h3>
|
||||||
|
{% if edit %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
|
||||||
|
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if markets %}<script>window.PJ_MEET_MARKETS = {{ markets | tojson }};</script>{% endif %}
|
||||||
|
<script>window.PJ_MEET_MEMBERS = {{ (meet_members or []) | tojson }};</script>
|
||||||
|
{% include "project/_side_modals.html" %}
|
||||||
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
|
{% endblock %}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
|
|
||||||
<section class="pj-main">
|
<section class="pj-main">
|
||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>{{ goal_year }}년 목표</h2>
|
<h2 class="pj-goal-title">{{ goal_year }}년 목표</h2>
|
||||||
{% if board %}
|
{% if board %}
|
||||||
<div class="pj-goal-head-acts">
|
<div class="pj-goal-head-acts">
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
@@ -51,8 +51,10 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
{% set sm = board.metrics.sales %}
|
{% set sm = board.metrics.sales %}
|
||||||
{% set rm = board.metrics.roas %}
|
{% set rm = board.metrics.roas %}
|
||||||
|
{# 월 칸은 pj-goal-m + data-h(분기 1~4) — 분기 접기(initGoals)가 이걸로 숨긴다.
|
||||||
|
분기 칸 클래스는 예전 이름 pj-goal-half-col 그대로(연간 칸처럼 굵게·회색 합계) #}
|
||||||
{% macro num_cell(metric, kind, labels, mo) -%}
|
{% macro num_cell(metric, kind, labels, mo) -%}
|
||||||
<td class="pj-goal-numtd{% if mo == this_month %} is-now{% endif %}">
|
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
|
||||||
{%- if is_admin -%}
|
{%- if is_admin -%}
|
||||||
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
||||||
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||||
@@ -63,88 +65,111 @@
|
|||||||
</td>
|
</td>
|
||||||
{%- endmacro %}
|
{%- endmacro %}
|
||||||
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
||||||
data-admin="{{ 'true' if is_admin else 'false' }}">
|
data-admin="{{ 'true' if is_admin else 'false' }}"
|
||||||
|
data-halves="{{ 'true' if board.halves else 'false' }}">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
|
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
|
||||||
<th class="pj-goal-c1"><span class="pj-goal-colresize" data-col="c1" title="끌어서 너비 조절"></span></th>
|
<th class="pj-goal-c1"><span class="pj-goal-colresize" data-col="c1" title="끌어서 너비 조절"></span></th>
|
||||||
<th class="pj-goal-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
|
<th class="pj-goal-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
|
||||||
<th class="pj-goal-year-col">연간</th>
|
{# 연간·월·분기 칸도 머리 칸 오른쪽 끝을 끌어 너비 조절(data-col: y · m1~m12 · q1~q4) #}
|
||||||
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
|
<th class="pj-goal-year-col" data-col="y">연간<span class="pj-goal-colresize" data-col="y" title="끌어서 너비 조절"></span></th>
|
||||||
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{# 월 이름을 누르면 그 달 주간 회의록(/goals/{연도}/meetings/{월}) #}
|
||||||
|
{% for mo in hmonths %}<th class="pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-col="m{{ mo }}"><a class="pj-goal-mlabel pj-goal-mlink" href="/project/goals/{{ goal_year }}/meetings/{{ mo }}" title="{{ mo }}월 주간 회의록">{{ mo }}월</a><span class="pj-goal-colresize" data-col="m{{ mo }}" title="끌어서 너비 조절"></span></th>{% endfor %}
|
||||||
|
{# 분기 칸 — 머리 칸 아무 곳이나 누르면 그 분기의 월 칸을 접었다 편다(localStorage pj_goal_fold_q).
|
||||||
|
아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘, 누르면 펼침).
|
||||||
|
분기 색(data-h → --qc)은 머리 위 색 띠(월 가늘게·분기 두껍게)와 분기 열 옅은 음영 #}
|
||||||
|
<th class="pj-goal-half-col pj-goal-fold-th" data-h="{{ h }}" data-col="q{{ h }}">
|
||||||
|
<button type="button" class="pj-goal-fold" data-h="{{ h }}" aria-expanded="true"
|
||||||
|
data-label="{{ hmonths[0] }}~{{ hmonths[-1] }}월"
|
||||||
|
title="{{ hmonths[0] }}~{{ hmonths[-1] }}월 접기"><svg class="pj-goal-fold-ic" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" aria-hidden="true"><rect x="1.75" y="1.75" width="12.5" height="12.5" rx="3"/><path d="M5 8h6"/><path class="pj-goal-fold-v" d="M8 5v6"/></svg></button>{{ hname }}
|
||||||
|
<span class="pj-goal-colresize" data-col="q{{ h }}" title="끌어서 너비 조절"></span>
|
||||||
|
</th>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
{# ── 숫자 지표 ── #}
|
{# ── 숫자 지표 — 연간·분기 칸은 화면에서 계산(매출 합계·달성률, 로아스 매출 가중 평균), 로아스는 % 단위 ── #}
|
||||||
<tbody class="pj-goal-kpi">
|
<tbody class="pj-goal-kpi">
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c1" rowspan="3">매출</th>
|
<th class="pj-goal-c1" rowspan="3">매출</th>
|
||||||
<th class="pj-goal-c2">목표</th>
|
<th class="pj-goal-c2">목표</th>
|
||||||
<td class="pj-goal-sum" data-metric="sales" data-kind="target"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="target" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("sales", "target", sm.target_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c2">실적</th>
|
<th class="pj-goal-c2">실적</th>
|
||||||
<td class="pj-goal-sum" data-metric="sales" data-kind="actual"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="sales" data-kind="actual" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("sales", "actual", sm.actual_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="sales" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr class="pj-goal-rate-row">
|
<tr class="pj-goal-rate-row">
|
||||||
<th class="pj-goal-c2">달성</th>
|
<th class="pj-goal-c2">달성</th>
|
||||||
<td class="pj-goal-rate" data-month="0"></td>
|
<td class="pj-goal-rate pj-goal-year-col" data-month="0"></td>
|
||||||
{% for mo in months %}<td class="pj-goal-rate{% if mo == this_month %} is-now{% endif %}" data-month="{{ mo }}"></td>{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}<td class="pj-goal-rate pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ h }}" data-month="{{ mo }}"></td>{% endfor %}
|
||||||
|
<td class="pj-goal-rate pj-goal-half-col" data-month="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c1" rowspan="2">로아스</th>
|
<th class="pj-goal-c1" rowspan="2">로아스</th>
|
||||||
<th class="pj-goal-c2">목표</th>
|
<th class="pj-goal-c2">목표</th>
|
||||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
{# 로아스 연간·분기 = 월 매출로 가중한 평균(광고비 = 매출 ÷ 로아스로 환산) — project.js recompute #}
|
||||||
{% for mo in months %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="target" data-scope="0"></td>
|
||||||
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("roas", "target", rm.target_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="target" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="pj-goal-c2">실적</th>
|
<th class="pj-goal-c2">실적</th>
|
||||||
<td class="pj-goal-sum pj-goal-sum-na"></td>
|
<td class="pj-goal-sum pj-goal-year-col" data-metric="roas" data-kind="actual" data-scope="0"></td>
|
||||||
{% for mo in months %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
{% for h, hmonths, hm, hname in quarters %}
|
||||||
|
{% for mo in hmonths %}{{ num_cell("roas", "actual", rm.actual_label, mo) }}{% endfor %}
|
||||||
|
<td class="pj-goal-sum pj-goal-half-col" data-metric="roas" data-kind="actual" data-scope="{{ hm }}" data-h="{{ h }}"></td>
|
||||||
|
{% endfor %}
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|
||||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
|
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(관리자) ── #}
|
||||||
{% for area in board.areas %}
|
{% for area in board.areas %}
|
||||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" data-color="{{ area.color }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||||
{% for row in area.rows %}
|
{% for row in area.rows %}
|
||||||
<tr data-row-id="{{ row.id }}">
|
<tr data-row-id="{{ row.id }}">
|
||||||
{% if loop.first %}
|
{% if loop.first %}
|
||||||
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
||||||
<span class="pj-goal-area-text">{{ area.name }}</span>
|
{# 구역 메뉴(색·위로·아래로·줄 추가·영역 삭제) — 우클릭 또는 ⋮ 버튼(키보드 Tab → Enter/Space, 터치 탭). project.js areaMenuItems #}
|
||||||
{% if is_admin %}
|
<span class="pj-goal-area-text"{% if is_admin %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
|
||||||
<span class="pj-goal-tools">
|
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-rename" data-name="{{ area.name }}" title="이름 바꾸기">✎</button>
|
aria-label="{{ area.name }} 구역 메뉴" title="구역 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-color" data-color="{{ area.color }}" title="색 바꾸기"><span class="material-symbols-outlined">palette</span></button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-up" title="위로">↑</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-down" title="아래로">↓</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-add" title="줄 추가">+</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="area-del" data-name="{{ area.name }}" title="영역 삭제">×</button>
|
|
||||||
</span>
|
|
||||||
{% endif %}
|
|
||||||
</th>
|
</th>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<th class="pj-goal-c2 pj-goal-row-label">
|
{# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #}
|
||||||
<span class="pj-goal-row-text">{{ row.label }}</span>
|
{% if not row.label_cont %}
|
||||||
{% if is_admin %}
|
<th class="pj-goal-c2 pj-goal-row-label"{% if (row.label_span or 1) > 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}">
|
||||||
<span class="pj-goal-tools">
|
<span class="pj-goal-row-text"{% if is_admin %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-rename" data-label="{{ row.label }}" title="줄 이름 바꾸기">✎</button>
|
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
|
||||||
{% if area.rows | length > 1 %}
|
aria-label="{{ (row.label or '이름 없는') }} 줄 메뉴" title="줄 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-up" title="위로">↑</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-down" title="아래로">↓</button>
|
|
||||||
<button type="button" class="pj-icon-btn" data-goal-act="row-del" data-label="{{ row.label }}" title="줄 삭제">×</button>
|
|
||||||
{% endif %}
|
|
||||||
</span>
|
|
||||||
{% endif %}
|
|
||||||
</th>
|
</th>
|
||||||
{% for mo in [0] + months %}
|
{% endif %}
|
||||||
<td class="pj-goal-texttd{% if mo == 0 %} pj-goal-year-col{% endif %}{% if mo == this_month %} is-now{% endif %}">
|
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
|
||||||
{%- if is_admin -%}
|
{% for c in row.layout %}
|
||||||
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ mo }}"
|
{% set editable = is_admin and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
|
||||||
placeholder="{{ '연간 목표' if mo == 0 else '' }}">{{ row.cells.get(mo, '') }}</textarea>
|
{% set merged = c.span > 1 or c.rspan > 1 %}
|
||||||
|
<td class="pj-goal-texttd {{ 'pj-goal-m' if c.kind == 'month' else ('pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col') }}{% if merged %} is-merged{% endif %}{% if c.now %} is-now{% endif %}"
|
||||||
|
{% if c.kind in ('month', 'quarter') %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
|
||||||
|
{%- if c.span > 1 %} colspan="{{ c.span }}" style="--span: {{ c.span }}"{% endif %}{% if c.rspan > 1 %} rowspan="{{ c.rspan }}"{% endif %}>
|
||||||
|
{%- if editable -%}
|
||||||
|
<textarea class="pj-goal-text" rows="1" data-row="{{ row.id }}" data-month="{{ c.m }}"
|
||||||
|
placeholder="{{ '연간 목표' if c.m == 0 else ((c.h ~ '분기 목표') if c.kind == 'quarter' else '') }}">{{ row.cells.get(c.m, '') }}</textarea>
|
||||||
{%- else -%}
|
{%- else -%}
|
||||||
<div class="pj-goal-text-ro">{{ row.cells.get(mo, '') }}</div>
|
<div class="pj-goal-text-ro">{{ row.cells.get(c.m, '') }}</div>
|
||||||
{%- endif -%}
|
{%- endif -%}
|
||||||
</td>
|
</td>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
@@ -156,7 +181,9 @@
|
|||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
<div class="pj-goal-foot">
|
<div class="pj-goal-foot">
|
||||||
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
||||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다.</span>
|
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
|
||||||
|
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
|
||||||
|
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -169,5 +196,5 @@
|
|||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
|
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -89,10 +89,25 @@
|
|||||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||||
<li><b>목표</b> — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 —
|
<li><b>목표</b> — 누르면 바로 아래에 연도가 펼쳐집니다. 연도를 누르면 오른쪽에 그해 전체 목표가 한 표로 나옵니다 —
|
||||||
맨 위에 <b>매출</b>(목표·실적·달성률)과 <b>로아스</b>(목표·실적)를 달마다, 그 아래에 <b>업무 영역</b>(상품·마케팅·컨텐츠·유통 등)별로
|
맨 위에 <b>매출</b>(목표·실적·달성률)과 <b>로아스</b>(목표·실적, 단위 %)를 달마다, 그 아래에 <b>업무 영역</b>(상품·마케팅·컨텐츠·유통 등)별로
|
||||||
연간·월별 계획을 적습니다. 매출의 <b>연간</b> 칸은 월 합계, <b>달성</b>은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다.
|
연간·분기·월별 계획을 적습니다. 3·6·9·12월 오른쪽에 <b>1~4분기</b> 칸이 있고, 매출의 <b>연간·분기</b> 칸은 월 합계,
|
||||||
|
<b>달성</b>은 실적÷목표(100% 이상 초록)로 저절로 계산됩니다. 분기 칸 머리의 <b>‹</b> 버튼을 누르면 그 분기의 월 칸 3개가
|
||||||
|
접히고, 다시 누르면 펼쳐집니다(접힌 상태는 내 브라우저에 기억). 월 이름을 누르면 그 달 <b>주간 회의록</b>이 열립니다.
|
||||||
<b>입력은 관리자만</b> 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 <b>+ 연도 추가</b>로 새해 목표를
|
<b>입력은 관리자만</b> 할 수 있고(칸을 고치면 바로 저장), 다른 직원은 보기만 합니다. 관리자는 <b>+ 연도 추가</b>로 새해 목표를
|
||||||
만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역 이름 칸에 마우스를 올려 이름·색·순서·줄 추가·삭제를 합니다.</li>
|
만들고(이전 연도의 업무 영역 구성을 그대로 가져옴), 영역·줄 이름은 <b>눌러서 그 자리에서 고치고</b>(Enter 저장, Esc 취소),
|
||||||
|
구역·항목 칸을 <b>우클릭</b>하거나 칸 오른쪽 위의 작은 <span class="pjh-ui">⋮</span> 버튼(마우스를 올리면 보임)을 눌러 색·순서·줄 추가·삭제를 합니다.
|
||||||
|
키보드로는 <kbd>Tab</kbd>으로 이름 칸·<span class="pjh-ui">⋮</span>로 가서 <kbd>Enter</kbd>(이름 칸 = 이름 고치기, ⋮ = 메뉴), 메뉴 안에서 <kbd>↑</kbd><kbd>↓</kbd>·<kbd>Enter</kbd>,
|
||||||
|
<kbd>Esc</kbd>로 닫습니다. 터치 화면에서는 ⋮ 버튼이 늘 옅게 보여 손가락으로 누르면 됩니다. 업무 영역 칸은 엑셀처럼 <b>병합</b>할 수 있습니다 — 칸을 마우스로
|
||||||
|
끌어 여러 칸을 고른 뒤 우클릭 → "셀 병합", 병합된 칸은 우클릭 → "병합 해제"(글은 왼쪽 위 칸에 남음).
|
||||||
|
가로 병합은 같은 분기의 월 칸끼리만(연간·분기 칸은 세로로만) 되고, 칸들의 글은 순서대로 첫 칸에 모입니다.
|
||||||
|
<br><b>저장이 안 되면</b>(네트워크 끊김 등) 칸 테두리가 빨갛게 되고 <b>쓴 글은 그대로 남습니다</b> — 다시 입력하거나 칸을 떠나면 다시 저장합니다.
|
||||||
|
저장 안 된 칸이 있으면 줄·영역 추가·병합은 하지 않고 알려 주며, 그 상태로 페이지를 떠나려 하면 브라우저가 한 번 묻습니다.
|
||||||
|
글은 내 브라우저에도 잠시 보관되어, 저장되지 못한 채 창이 닫혀도 다음에 열면 되살아납니다(그 사이 다른 사람이 같은 칸을 고쳤으면 되살리지 않음).</li>
|
||||||
|
<li><b>주간 회의록</b>(목표 표의 월 이름) — <b>지난주 리뷰</b>는 언제나 바로 앞 주(7일 전 월~일) 회의록만 보여 줍니다. 그 주 회의록이 없으면
|
||||||
|
"회의록 없음"으로 비워 두고, 몇 주 전 결과를 지난주처럼 보이지 않습니다. 회의록을 만드는 순서(다음 주를 먼저 만들어도)와 줄 이름 변경·순서 이동과
|
||||||
|
관계없이 같은 줄끼리 이어집니다. 실적 모듈에서 매출을 읽지 못하면 그 칸은 0원이 아니라 <b>⚠ 미확인</b>으로 보입니다(필요 매출·달성률도 미확인).
|
||||||
|
매출 자동 갱신은 평소엔 조용히 돌고, <b>실패하거나 일부 쇼핑몰만 실패</b>하면 숫자 아래에 작은 안내와 <span class="pjh-ui">다시 시도</span>가 나옵니다
|
||||||
|
(안내의 "마지막 갱신 성공" 시각은 실적 모듈이 기록한 시각). 실적 권한이 없으면 갱신하지 않고 저장된 실적으로 보여 줍니다.</li>
|
||||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||||
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -104,5 +104,5 @@
|
|||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
<span class="material-symbols-outlined">attach_file</span>
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||||
</label>
|
</label>
|
||||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -100,5 +100,5 @@
|
|||||||
"today": {{ today | tojson }}
|
"today": {{ today | tojson }}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<!-- 타임라인 vis-timeline — self-host -->
|
<!-- 타임라인 vis-timeline — self-host -->
|
||||||
@@ -420,7 +420,7 @@
|
|||||||
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
바깥이라 끝까지 내려도 마지막 내용은 이 칸 바로 위에서 멈추고 가리지 않는다. -->
|
||||||
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
<div class="pj-comment-dock" id="pj-comment-dock" hidden>
|
||||||
<div class="pj-comment-form">
|
<div class="pj-comment-form">
|
||||||
<input type="text" id="pj-comment-input" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요" autocomplete="off" />
|
<textarea id="pj-comment-input" class="pj-composer-ta" rows="1" placeholder="댓글을 추가하거나 @로 멤버를 태그하세요 (Shift+Enter 줄바꿈)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-comment-send">등록</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-comment-send">등록</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -466,7 +466,7 @@
|
|||||||
<span class="material-symbols-outlined">attach_file</span>
|
<span class="material-symbols-outlined">attach_file</span>
|
||||||
<input type="file" id="pj-cm-file-input" multiple hidden />
|
<input type="file" id="pj-cm-file-input" multiple hidden />
|
||||||
</label>
|
</label>
|
||||||
<input type="text" id="pj-cm-input" placeholder="댓글 입력… (이미지는 붙여넣기 가능)" autocomplete="off" />
|
<textarea id="pj-cm-input" class="pj-composer-ta" rows="1" placeholder="댓글 입력… (Shift+Enter 줄바꿈, 이미지는 붙여넣기 가능)" autocomplete="off"></textarea>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-cm-send">전송</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -496,5 +496,5 @@
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}
|
{% block head_extra %}
|
||||||
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
|
<link rel="stylesheet" href="/static/project.css?v=20261002b" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -70,5 +70,5 @@
|
|||||||
{% include "project/_side_modals.html" %}
|
{% include "project/_side_modals.html" %}
|
||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project.js?v=20260930g" defer></script>
|
<script src="/static/project.js?v=20261002b" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -59,29 +59,86 @@
|
|||||||
|
|
||||||
var state = { option: null, variants: [], displayTypes: {}, orphans: [], imageBase: "" };
|
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 () {
|
openBtn.addEventListener("click", function () {
|
||||||
var nameEl = document.getElementById("cf24-name-text");
|
var nameEl = document.getElementById("cf24-name-text");
|
||||||
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
modal.open((nameEl ? nameEl.textContent : "") + " (상품번호 " + no + ")");
|
||||||
|
myGen = modal.gen;
|
||||||
load();
|
load();
|
||||||
});
|
});
|
||||||
|
|
||||||
function load() {
|
function load() {
|
||||||
|
var seq = ++loadSeq;
|
||||||
|
var gen = myGen;
|
||||||
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
body.innerHTML = '<p class="cf24-muted">카페24에서 불러오는 중…</p>';
|
||||||
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
return apiJson("GET", "/cafe24/products/" + no + "/options")
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
|
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||||
state.option = data.option;
|
state.option = data.option;
|
||||||
state.variants = data.variants || [];
|
state.variants = data.variants || [];
|
||||||
state.displayTypes = data.display_types || {};
|
state.displayTypes = data.display_types || {};
|
||||||
state.imageBase = data.image_base || "";
|
state.imageBase = data.image_base || "";
|
||||||
render();
|
render();
|
||||||
|
return true;
|
||||||
})
|
})
|
||||||
.catch(function (err) {
|
.catch(function (err) {
|
||||||
|
if (seq !== loadSeq || gen !== modal.gen || !modal.isOpen()) return false;
|
||||||
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
body.innerHTML = '<p class="cf24-err">옵션을 불러오지 못했습니다: ' + esc(err.message) +
|
||||||
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
'</p><button type="button" class="erp-btn erp-btn-outline" id="cf24-opt-retry">다시 시도</button>';
|
||||||
body.querySelector("#cf24-opt-retry").addEventListener("click", load);
|
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) {
|
function typeSelect(current, name) {
|
||||||
var out = '<select name="' + name + '">';
|
var out = '<select name="' + name + '">';
|
||||||
@@ -236,25 +293,34 @@
|
|||||||
통합 목록 — 옵션값 1 : 품목 1
|
통합 목록 — 옵션값 1 : 품목 1
|
||||||
═══════════════════════════════════════════════════════════ */
|
═══════════════════════════════════════════════════════════ */
|
||||||
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
// 행 = 품목 목록 순서. index 는 options 응답 안 위치(옵션 PUT 짝맞춤용).
|
||||||
// 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
// 품목과 옵션값은 **옵션값 번호(value_no)** 로 먼저 짝짓고, 없을 때만 이름으로 짝짓는다.
|
||||||
|
// (옵션값 이름을 바꾼 직후 카페24 품목 조회가 예전 이름을 돌려줘도 정상 품목이 숨지 않게.
|
||||||
|
// 서버가 품목코드별 쓰기 기록으로 표기를 바로잡고 value_no 를 붙여 준다.)
|
||||||
|
// 방금 추가해 품목이 아직 안 보이는 옵션값(pending)은 "품목 생성 대기" 행으로 그린다.
|
||||||
|
// 그 밖에 품목이 없는 옵션값은 state.orphans 로 따로 모은다(행으로 그리지 않는다).
|
||||||
function unifiedRows() {
|
function unifiedRows() {
|
||||||
var opt = state.option;
|
var opt = state.option;
|
||||||
state.orphans = [];
|
state.orphans = [];
|
||||||
if (!opt || !opt.has_option) return [];
|
if (!opt || !opt.has_option) return [];
|
||||||
var group = opt.options[0];
|
var group = opt.options[0];
|
||||||
var byText = {};
|
var entries = group.option_value.map(function (v, vi) { return { index: vi, value: v, variant: null }; });
|
||||||
group.option_value.forEach(function (v, vi) { byText[v.option_text] = { 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 = [];
|
var rows = [];
|
||||||
state.variants.forEach(function (variant) {
|
state.variants.forEach(function (variant) {
|
||||||
if (!variant.options.length) return;
|
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;
|
if (!r || r.variant) return;
|
||||||
r.variant = variant;
|
r.variant = variant;
|
||||||
rows.push(r);
|
rows.push(r);
|
||||||
});
|
});
|
||||||
group.option_value.forEach(function (v) {
|
entries.forEach(function (r) {
|
||||||
var r = byText[v.option_text];
|
if (r.variant) return;
|
||||||
if (rows.indexOf(r) < 0) state.orphans.push(r);
|
if (r.value.pending) { r.await = true; rows.push(r); }
|
||||||
|
else state.orphans.push(r);
|
||||||
});
|
});
|
||||||
return rows;
|
return rows;
|
||||||
}
|
}
|
||||||
@@ -266,8 +332,10 @@
|
|||||||
var thumbSrc = [v.option_image_file, v.option_link_image,
|
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) : ""];
|
state.option && state.option.has_option ? variantImageFor(state.option.options[0].option_name, v.option_text) : ""];
|
||||||
var code = variant ? variant.variant_code : "";
|
var code = variant ? variant.variant_code : "";
|
||||||
|
var awaiting = !!r.await && !code;
|
||||||
// data-index: options 응답 안 위치(옵션 PUT 짝맞춤용, 새 행은 빈 값) / data-pos: 처음 그린 순서(순서 변경 판정용)
|
// 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-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>" +
|
'<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 || "") + '" />' +
|
'<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-u-name"><input type="text" name="option_text" value="' + esc(v.option_text) + '" placeholder="옵션값 이름" /></td>' +
|
||||||
'<td class="cf24-v-syscode">' + (code
|
'<td class="cf24-v-syscode">' + (code
|
||||||
? '<button type="button" class="cf24-v-copy" data-copy-text="' + esc(code) + '" title="클릭하면 품목코드를 복사합니다">' + esc(code) + "</button>"
|
? '<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-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-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("display", variant ? !!variant.display : true) + "</td>" +
|
||||||
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : 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>";
|
"</tr>";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -157,6 +157,7 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
|||||||
.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
|
.perf-modal { position: fixed; inset: 0; z-index: 1000; background: rgba(0, 0, 0, .35); display: flex; align-items: center; justify-content: center; padding: 20px; }
|
||||||
.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
|
.perf-modal-card { background: #fff; border-radius: 14px; width: min(1100px, 100%); max-height: 88vh; display: flex; flex-direction: column; box-shadow: 0 20px 60px rgba(0, 0, 0, .25); }
|
||||||
.perf-modal-card.is-narrow { width: min(560px, 100%); }
|
.perf-modal-card.is-narrow { width: min(560px, 100%); }
|
||||||
|
.perf-modal-card.is-wide { width: min(1640px, 100%); } /* 주문 내역 — 열이 많아 넓게 */
|
||||||
.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
|
.perf-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 14px 16px; border-bottom: 1px solid var(--perf-line); }
|
||||||
.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
.perf-modal-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||||
.perf-modal-body { padding: 12px 16px; overflow: auto; }
|
.perf-modal-body { padding: 12px 16px; overflow: auto; }
|
||||||
@@ -229,6 +230,8 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
|||||||
.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
|
.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
|
||||||
/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
|
/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
|
||||||
.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
|
.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
|
||||||
|
/* 상품명만 줄바꿈 — 긴 상품명 때문에 표가 창보다 넓어져 가로 스크롤이 생기지 않게(나머지 열은 한 줄) */
|
||||||
|
.perf-ev-table .perf-ev-name { white-space: normal; min-width: 220px; overflow-wrap: anywhere; }
|
||||||
|
|
||||||
/* ── 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대(runSyncWithProgress) ── */
|
/* ── 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대(runSyncWithProgress) ── */
|
||||||
.perf-prog-card { width: min(640px, 100%); }
|
.perf-prog-card { width: min(640px, 100%); }
|
||||||
@@ -262,6 +265,15 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
|||||||
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
|
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
|
||||||
|
|
||||||
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
|
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
|
||||||
|
/* 쇼핑몰별 [중지] — 이름 옆 작은 버튼(이 쇼핑몰만 멈추고 다음 쇼핑몰로) */
|
||||||
|
.perf-prog-name { display: flex; align-items: center; gap: 6px; }
|
||||||
|
.perf-prog-name > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.perf-prog-stop {
|
||||||
|
flex: none; margin-left: auto; padding: 1px 8px; border: 1px solid var(--perf-line); border-radius: 999px;
|
||||||
|
background: #fff; color: var(--perf-down); font-size: 11.5px; font-weight: 600; line-height: 1.6; cursor: pointer;
|
||||||
|
}
|
||||||
|
.perf-prog-stop:hover { border-color: var(--perf-down); background: #fff5f5; }
|
||||||
|
.perf-prog-stop:disabled { opacity: .6; cursor: default; }
|
||||||
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
|
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
|
||||||
.perf-prog-cancel[hidden] { display: none; }
|
.perf-prog-cancel[hidden] { display: none; }
|
||||||
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
|
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
|
||||||
|
|||||||
+71
-17
@@ -54,7 +54,8 @@
|
|||||||
function openModal(title, opts) {
|
function openModal(title, opts) {
|
||||||
opts = opts || {};
|
opts = opts || {};
|
||||||
const back = el("div", { class: "perf-modal" });
|
const back = el("div", { class: "perf-modal" });
|
||||||
const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : ""), role: "dialog", "aria-modal": "true" });
|
const card = el("div", { class: "perf-modal-card" + (opts.narrow ? " is-narrow" : opts.wide ? " is-wide" : ""),
|
||||||
|
role: "dialog", "aria-modal": "true" });
|
||||||
const head = el("div", { class: "perf-modal-head" });
|
const head = el("div", { class: "perf-modal-head" });
|
||||||
head.appendChild(el("h3", { text: title }));
|
head.appendChild(el("h3", { text: title }));
|
||||||
const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×");
|
const x = el("button", { type: "button", class: "perf-modal-x", "aria-label": "닫기" }, "×");
|
||||||
@@ -85,10 +86,10 @@
|
|||||||
sec = Math.max(0, Math.round(sec || 0));
|
sec = Math.max(0, Math.round(sec || 0));
|
||||||
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
|
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
|
||||||
}
|
}
|
||||||
function progressRow(name, fraction, text, cls) {
|
function progressRow(name, fraction, text, cls, action) {
|
||||||
const pct = Math.round((fraction || 0) * 100);
|
const pct = Math.round((fraction || 0) * 100);
|
||||||
return '<div class="perf-prog-row' + (cls ? " " + cls : "") + '">' +
|
return '<div class="perf-prog-row' + (cls ? " " + cls : "") + '">' +
|
||||||
'<div class="perf-prog-name">' + esc(name) + "</div>" +
|
'<div class="perf-prog-name"><span>' + esc(name) + "</span>" + (action || "") + "</div>" +
|
||||||
'<div class="perf-prog-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + pct + '">' +
|
'<div class="perf-prog-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + pct + '">' +
|
||||||
'<span style="width:' + pct + '%"></span></div>' +
|
'<span style="width:' + pct + '%"></span></div>' +
|
||||||
'<div class="perf-prog-pct">' + pct + "%</div>" +
|
'<div class="perf-prog-pct">' + pct + "%</div>" +
|
||||||
@@ -101,8 +102,10 @@
|
|||||||
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
|
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
|
||||||
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
|
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
|
||||||
if (s.state === "skipped") t += " · " + (s.message || "");
|
if (s.state === "skipped") t += " · " + (s.message || "");
|
||||||
if (s.state === "cancelled") t += " · 저장하지 않음(기존 매출 그대로)";
|
if (s.state === "cancelled") t = (s.message === "중지됨" ? "중지됨" : t) + " · 저장하지 않음(기존 매출 그대로)";
|
||||||
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
|
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
|
||||||
|
else if (s.state === "running" && s.stop_requested) t += " · 중지하는 중…";
|
||||||
|
if (s.state === "waiting" && s.stop_requested) t += " · 중지 — 차례가 오면 건너뜀";
|
||||||
let html = esc(t);
|
let html = esc(t);
|
||||||
if (s.elapsed && s.state !== "waiting") html += ' <span class="perf-muted">(' + fmtSec(s.elapsed) + ")</span>";
|
if (s.elapsed && s.state !== "waiting") html += ' <span class="perf-muted">(' + fmtSec(s.elapsed) + ")</span>";
|
||||||
return html;
|
return html;
|
||||||
@@ -118,7 +121,12 @@
|
|||||||
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
|
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
|
||||||
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
|
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
|
||||||
if (job.cancel_requested) s.cancel_pending = true;
|
if (job.cancel_requested) s.cancel_pending = true;
|
||||||
return progressRow(s.name, s.fraction, shopText(s), cls);
|
// 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로(대기·수집 중일 때만, 저장 중엔 못 멈춤)
|
||||||
|
const stoppable = !job.finished && !job.cancel_requested && !s.stop_requested &&
|
||||||
|
(s.state === "waiting" || s.state === "running");
|
||||||
|
const stopBtn = stoppable ? '<button type="button" class="perf-prog-stop" data-stop="' + esc(s.code) + '" title="' +
|
||||||
|
esc(s.name) + ' 업데이트만 멈추고 다음 쇼핑몰로 넘어갑니다(이 쇼핑몰은 저장하지 않음)">중지</button>' : "";
|
||||||
|
return progressRow(s.name, s.fraction, shopText(s), cls, stopBtn);
|
||||||
}).join("");
|
}).join("");
|
||||||
html += progressRow("전체", o.fraction,
|
html += progressRow("전체", o.fraction,
|
||||||
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
|
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
|
||||||
@@ -147,6 +155,23 @@
|
|||||||
m.foot.appendChild(cancelBtn);
|
m.foot.appendChild(cancelBtn);
|
||||||
m.foot.appendChild(closeBtn);
|
m.foot.appendChild(closeBtn);
|
||||||
let jobId = null;
|
let jobId = null;
|
||||||
|
// 쇼핑몰별 [중지] — 진행 창은 0.8초마다 다시 그려지므로 위임으로 받는다
|
||||||
|
m.body.addEventListener("click", async function (e) {
|
||||||
|
const b = e.target.closest("[data-stop]");
|
||||||
|
if (!b || !jobId) return;
|
||||||
|
b.disabled = true;
|
||||||
|
b.textContent = "중지하는 중…";
|
||||||
|
try {
|
||||||
|
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
|
||||||
|
encodeURIComponent(b.dataset.stop) + "/stop");
|
||||||
|
last = r.job;
|
||||||
|
renderSyncJob(m.body, r.job, false);
|
||||||
|
} catch (err) {
|
||||||
|
b.disabled = false;
|
||||||
|
b.textContent = "중지";
|
||||||
|
alertMsg("중지 실패: " + err.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
cancelBtn.addEventListener("click", async function () {
|
cancelBtn.addEventListener("click", async function () {
|
||||||
if (!jobId) return;
|
if (!jobId) return;
|
||||||
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
|
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
|
||||||
@@ -199,7 +224,7 @@
|
|||||||
function jobResults(job) {
|
function jobResults(job) {
|
||||||
return (job && job.shops || []).map(function (s) {
|
return (job && job.shops || []).map(function (s) {
|
||||||
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
|
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
|
||||||
cancelled: s.state === "cancelled",
|
cancelled: s.state === "cancelled", stopped: s.state === "cancelled" && s.message === "중지됨",
|
||||||
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
|
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -263,11 +288,12 @@
|
|||||||
const running = job && !job.finished;
|
const running = job && !job.finished;
|
||||||
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
|
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
|
||||||
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
|
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
|
||||||
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [];
|
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [], stopped = [];
|
||||||
let changed = 0;
|
let changed = 0;
|
||||||
(res.results || []).forEach(function (r) {
|
(res.results || []).forEach(function (r) {
|
||||||
const name = (data.names || {})[r.code] || r.name || r.code;
|
const name = (data.names || {})[r.code] || r.name || r.code;
|
||||||
if (r.cancelled) cancelled.push(name);
|
if (r.stopped) stopped.push(name);
|
||||||
|
else if (r.cancelled) cancelled.push(name);
|
||||||
else if (r.skipped) busy.push(name);
|
else if (r.skipped) busy.push(name);
|
||||||
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
|
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
|
||||||
else if (r.status === "not_implemented") pending.push(name);
|
else if (r.status === "not_implemented") pending.push(name);
|
||||||
@@ -278,6 +304,7 @@
|
|||||||
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
|
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
|
||||||
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
|
||||||
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
|
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
|
||||||
|
if (stopped.length) parts.push("<b>중지됨</b>(기존 매출 그대로) " + esc(stopped.join(", ")));
|
||||||
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
|
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
|
||||||
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
|
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
|
||||||
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
|
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
|
||||||
@@ -309,7 +336,7 @@
|
|||||||
async function openEvents(code, from, to) {
|
async function openEvents(code, from, to) {
|
||||||
const name = (data.names || {})[code] || code;
|
const name = (data.names || {})[code] || code;
|
||||||
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역";
|
||||||
const m = openModal(title);
|
const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이
|
||||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||||
try {
|
try {
|
||||||
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) +
|
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) +
|
||||||
@@ -325,7 +352,7 @@
|
|||||||
"<td>" + esc(r.sales_date) + "</td><td>" + esc(KIND[r.event_type] || r.event_type) +
|
"<td>" + esc(r.sales_date) + "</td><td>" + esc(KIND[r.event_type] || r.event_type) +
|
||||||
(r.is_sample ? ' <span class="perf-pill">테스트</span>' : "") + "</td>" +
|
(r.is_sample ? ' <span class="perf-pill">테스트</span>' : "") + "</td>" +
|
||||||
"<td>" + esc(r.external_order_id) + "</td>" +
|
"<td>" + esc(r.external_order_id) + "</td>" +
|
||||||
"<td>" + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
'<td class="perf-ev-name">' + esc(r.product_name) + (r.option_name ? " <span class='perf-muted'>" + esc(r.option_name) + "</span>" : "") + "</td>" +
|
||||||
'<td class="perf-num">' + esc(r.quantity) + "</td>" +
|
'<td class="perf-num">' + esc(r.quantity) + "</td>" +
|
||||||
'<td class="perf-num">' + fmt(r.amount) + "</td>" +
|
'<td class="perf-num">' + fmt(r.amount) + "</td>" +
|
||||||
"<td>" + esc(r.order_date || "") + "</td><td>" + esc(r.payment_date || "") + "</td>" +
|
"<td>" + esc(r.order_date || "") + "</td><td>" + esc(r.payment_date || "") + "</td>" +
|
||||||
@@ -334,7 +361,7 @@
|
|||||||
m.body.innerHTML =
|
m.body.innerHTML =
|
||||||
'<div class="perf-ev-wrap"><table class="perf-table perf-ev-table"><thead><tr>' +
|
'<div class="perf-ev-wrap"><table class="perf-table perf-ev-table"><thead><tr>' +
|
||||||
'<th class="perf-th-label">매출일</th><th class="perf-th-label">구분</th><th class="perf-th-label">주문번호</th>' +
|
'<th class="perf-th-label">매출일</th><th class="perf-th-label">구분</th><th class="perf-th-label">주문번호</th>' +
|
||||||
'<th class="perf-th-label">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
'<th class="perf-th-label perf-ev-name">상품명</th><th>수량</th><th>금액</th><th class="perf-th-label">주문일</th>' +
|
||||||
'<th class="perf-th-label">결제일</th><th class="perf-th-label">상태</th></tr></thead><tbody>' + body +
|
'<th class="perf-th-label">결제일</th><th class="perf-th-label">상태</th></tr></thead><tbody>' + body +
|
||||||
'</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" colspan="5">결제 ' + fmt(sales) +
|
'</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" colspan="5">결제 ' + fmt(sales) +
|
||||||
" / 취소·반품 " + fmt(minus) + '</th><td class="perf-num">' + fmt(sum) + '</td><td colspan="3"></td></tr></tfoot></table></div>' +
|
" / 취소·반품 " + fmt(minus) + '</th><td class="perf-num">' + fmt(sum) + '</td><td colspan="3"></td></tr></tfoot></table></div>' +
|
||||||
@@ -960,7 +987,7 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가·GS샵·토스쇼핑) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
|
||||||
const probe = document.getElementById("perf-probe");
|
const probe = document.getElementById("perf-probe");
|
||||||
if (probe) probe.addEventListener("click", async function () {
|
if (probe) probe.addEventListener("click", async function () {
|
||||||
const day = document.getElementById("perf-probe-date").value;
|
const day = document.getElementById("perf-probe-date").value;
|
||||||
@@ -970,7 +997,7 @@
|
|||||||
const codeSel = document.getElementById("perf-probe-code");
|
const codeSel = document.getElementById("perf-probe-code");
|
||||||
const code = codeSel ? codeSel.value : "elevenst";
|
const code = codeSel ? codeSel.value : "elevenst";
|
||||||
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
|
||||||
gsshop: "GS샵에서 불러오는 중… (10일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
gsshop: "GS샵에서 불러오는 중… (10일 단위)", toss: "토스쇼핑에서 불러오는 중… (31일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
|
||||||
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
|
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
|
||||||
try {
|
try {
|
||||||
const to = document.getElementById("perf-probe-to").value || day;
|
const to = document.getElementById("perf-probe-to").value || day;
|
||||||
@@ -993,10 +1020,11 @@
|
|||||||
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
|
||||||
}).join("") + "</tbody></table>";
|
}).join("") + "</tbody></table>";
|
||||||
}).join("");
|
}).join("");
|
||||||
// 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교
|
// 날짜별 현재 규칙 매출(네이버·토스쇼핑) — 쇼핑몰 관리자 화면 매출과 나란히 비교
|
||||||
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
|
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
|
||||||
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
|
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
|
||||||
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>매출</th>' +
|
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>' +
|
||||||
|
esc((r.day_cols || {}).amount || "매출") + "</th>" +
|
||||||
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
|
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
|
||||||
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
|
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
|
||||||
r.days.map(function (d) {
|
r.days.map(function (d) {
|
||||||
@@ -1007,7 +1035,33 @@
|
|||||||
["orders", "amount", "claimed", "ship"].map(function (k) {
|
["orders", "amount", "claimed", "ship"].map(function (k) {
|
||||||
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
|
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
|
||||||
}).join("") + "</tr></tbody></table>" : "";
|
}).join("") + "</tr></tbody></table>" : "";
|
||||||
out.innerHTML = summary + days + (details || '<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
|
// 환불 출처별(토스쇼핑) — 출처별 날짜 합계를 나란히, 아래에 건별 목록(주문번호·금액·메모)
|
||||||
|
const rc = r.refund_candidates || [];
|
||||||
|
const candDays = (r.days || []).map(function (d) { return d.date; });
|
||||||
|
const cands = rc.length ? '<h4 class="perf-h" style="margin:14px 0 6px">환불 출처별 비교 — 첫 열(적용 규칙)이 저장되는 환불</h4>' +
|
||||||
|
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||||
|
rc.map(function (c) { return "<th>" + esc(c.label) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||||
|
candDays.map(function (dt) {
|
||||||
|
return '<tr><td class="perf-td-label">' + esc(dt) + "</td>" + rc.map(function (c) {
|
||||||
|
return '<td class="perf-num">' + (c.error ? "" : fmt((c.days || {})[dt] || 0)) + "</td>";
|
||||||
|
}).join("") + "</tr>";
|
||||||
|
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' + rc.map(function (c) {
|
||||||
|
if (c.error) return '<td><span class="perf-pill is-bad">실패</span> <span class="perf-muted" style="white-space:normal">' + esc(c.error) + "</span></td>";
|
||||||
|
const t = Object.keys(c.days || {}).reduce(function (a, k) { return a + c.days[k]; }, 0);
|
||||||
|
return '<td class="perf-num"><b>' + fmt(t) + "</b></td>";
|
||||||
|
}).join("") + "</tr></tbody></table>" +
|
||||||
|
rc.filter(function (c) { return !c.error && (c.rows || []).length; }).map(function (c) {
|
||||||
|
return '<p class="perf-muted" style="margin:10px 0 4px">' + esc(c.label) + " — " + fmt(c.rows.length) + "건</p>" +
|
||||||
|
'<table class="perf-table"><thead><tr><th class="perf-th-label">환불일</th><th class="perf-th-label">주문일</th>' +
|
||||||
|
'<th class="perf-th-label">주문번호</th>' +
|
||||||
|
'<th class="perf-th-label">주문상품</th><th>금액</th><th class="perf-th-label">메모</th></tr></thead><tbody>' +
|
||||||
|
c.rows.map(function (x) {
|
||||||
|
return '<tr><td class="perf-td-label">' + esc(x.date) + "</td><td>" + esc(x.orderDate || "") + "</td><td>" +
|
||||||
|
esc(x.orderId) + "</td><td>" + esc(x.orderProductId) +
|
||||||
|
'</td><td class="perf-num">' + fmt(x.amount) + '</td><td class="perf-muted">' + esc(x.note) + "</td></tr>";
|
||||||
|
}).join("") + "</tbody></table>";
|
||||||
|
}).join("") : "";
|
||||||
|
out.innerHTML = summary + days + cands + (details ||'<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||||
} finally { probe.disabled = false; }
|
} finally { probe.disabled = false; }
|
||||||
@@ -1033,7 +1087,7 @@
|
|||||||
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
|
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
|
||||||
(res.results || []).forEach(function (r) {
|
(res.results || []).forEach(function (r) {
|
||||||
const name = names[r.code] || r.name || r.code;
|
const name = names[r.code] || r.name || r.code;
|
||||||
if (r.cancelled) rest.push(name + "(취소됨)");
|
if (r.cancelled) rest.push(name + (r.stopped ? "(중지됨)" : "(취소됨)"));
|
||||||
else if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
|
else if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
|
||||||
else if (r.skipped) rest.push(name + "(이미 진행 중)");
|
else if (r.skipped) rest.push(name + "(이미 진행 중)");
|
||||||
else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
|
else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
|
||||||
|
|||||||
+483
-26
@@ -48,6 +48,12 @@
|
|||||||
/* 페이지(.erp-page)는 스크롤하지 않고 좌/우 칸이 각자 안에서만 스크롤한다 —
|
/* 페이지(.erp-page)는 스크롤하지 않고 좌/우 칸이 각자 안에서만 스크롤한다 —
|
||||||
.erp-page 는 flex column 이라 .pj-wrap 을 flex:1 로 늘려 남은 높이를 확보한다. */
|
.erp-page 는 flex column 이라 .pj-wrap 을 flex:1 로 늘려 남은 높이를 확보한다. */
|
||||||
.erp-page > .pj-wrap { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding-bottom: 8px; }
|
.erp-page > .pj-wrap { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding-bottom: 8px; }
|
||||||
|
/* 프로젝트 관리 화면은 위쪽 여백을 줄여 표·보드 공간을 넓게(2026-10-01) — 공통 본문 위 여백 24px → 6px,
|
||||||
|
화면 자체 위 여백·제목 줄 위 여백 0. 다른 모듈(.erp-page)은 그대로(:has 로 프로젝트 화면만). */
|
||||||
|
.erp-page:has(> .pj-wrap), .erp-page:has(> .pjh) { padding-top: 6px; }
|
||||||
|
.erp-page > .pj-wrap { padding-top: 0; }
|
||||||
|
.erp-page > .pj-wrap .pj-section-head { margin-top: 0; }
|
||||||
|
.erp-page > .pj-wrap .pj-meet-headgrid { margin-top: 0; }
|
||||||
|
|
||||||
/* ── 프로젝트 페이지 레이아웃 (좌: 프로젝트 트리 / 가운데: 세션 등 뷰 / 우:
|
/* ── 프로젝트 페이지 레이아웃 (좌: 프로젝트 트리 / 가운데: 세션 등 뷰 / 우:
|
||||||
내 업무) — 화면(=.erp-page) 자체는 스크롤하지 않고 3칸이 각자 안에서만
|
내 업무) — 화면(=.erp-page) 자체는 스크롤하지 않고 3칸이 각자 안에서만
|
||||||
@@ -366,7 +372,30 @@
|
|||||||
.pj-card.is-done .pj-card-title { text-decoration: line-through; color: #9aa1a9; }
|
.pj-card.is-done .pj-card-title { text-decoration: line-through; color: #9aa1a9; }
|
||||||
.pj-card-title { font-size: 13.5px; font-weight: 600; color: var(--pj-ink); line-height: 1.4; }
|
.pj-card-title { font-size: 13.5px; font-weight: 600; color: var(--pj-ink); line-height: 1.4; }
|
||||||
.pj-card-meta { display: flex; align-items: center; gap: 6px; margin-top: 10px; }
|
.pj-card-meta { display: flex; align-items: center; gap: 6px; margin-top: 10px; }
|
||||||
.pj-card-due { margin-left: auto; font-size: 11px; color: var(--pj-ink-soft); font-weight: 600; }
|
.pj-card-due { margin-left: auto; font-size: 12.1px; color: var(--pj-ink-soft); font-weight: 600; } /* 11px +10% */
|
||||||
|
/* 보드 카드 담당자 — 글자·아바타 10% 크게(12→13.2px, 18→20px) */
|
||||||
|
.pj-card-meta .pj-card-assignee { font-size: 13.2px; }
|
||||||
|
.pj-card-meta .pj-card-assignee .pj-avatar.pj-gicon-sm { width: 20px; height: 20px; }
|
||||||
|
.pj-card-meta .pj-card-assignee .pj-gicon-sm { font-size: 22px; }
|
||||||
|
/* 카드 높이 100px 고정(표지 이미지·펼친 하위 작업은 그 위·아래에 더해짐) — 머리 = 100 − 아래 여백 12 − 테두리 2.
|
||||||
|
제목은 2줄까지(프로젝트 배지가 있으면 1줄), 담당자·날짜 줄은 맨 아래 */
|
||||||
|
.pj-card-head {
|
||||||
|
box-sizing: border-box; height: 86px; display: flex; flex-direction: column; overflow: hidden;
|
||||||
|
}
|
||||||
|
.pj-card-head .pj-card-title {
|
||||||
|
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; flex: none;
|
||||||
|
}
|
||||||
|
.pj-card-head:has(.pj-card-proj) .pj-card-title { -webkit-line-clamp: 1; }
|
||||||
|
.pj-card:has(.pj-card-subs-wrap.is-open) .pj-card-head { height: 96px; } /* 펼침 때 아래 10px 여백(음수 margin)만큼 */
|
||||||
|
.pj-card-head .pj-card-meta { margin-top: auto; padding-top: 6px; flex: none; }
|
||||||
|
/* 표지 이미지(설명의 첫 이미지, 아사나식) — 카드 위쪽 끝까지, 위 모서리만 둥글게 */
|
||||||
|
.pj-card-cover {
|
||||||
|
margin: -12px -14px 12px; height: 140px; overflow: hidden; background: #f4f5f7;
|
||||||
|
border-radius: calc(var(--pj-card-radius) - 1px) calc(var(--pj-card-radius) - 1px) 0 0;
|
||||||
|
}
|
||||||
|
.pj-card-cover img { display: block; width: 100%; height: 100%; object-fit: cover; pointer-events: none; }
|
||||||
|
.pj-card.has-cover .pj-card-head { border-radius: 0; }
|
||||||
|
.pj-card-meta .pj-card-assignee.is-empty svg, .pj-card-meta .pj-card-due.is-empty svg { width: 24px; height: 24px; }
|
||||||
.pj-pri { padding: 1px 7px; border-radius: 999px; font-size: 10px; font-weight: 700; }
|
.pj-pri { padding: 1px 7px; border-radius: 999px; font-size: 10px; font-weight: 700; }
|
||||||
.pj-pri-high { background: #fbe3df; color: #c22b10; }
|
.pj-pri-high { background: #fbe3df; color: #c22b10; }
|
||||||
.pj-pri-low { background: #e6eef0; color: #4a6066; }
|
.pj-pri-low { background: #e6eef0; color: #4a6066; }
|
||||||
@@ -647,7 +676,8 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
|||||||
transition: border-color .12s, box-shadow .12s;
|
transition: border-color .12s, box-shadow .12s;
|
||||||
}
|
}
|
||||||
.pj-comment-dock .pj-comment-form:focus-within { border-color: #a9aeb6; box-shadow: 0 1px 6px rgba(0,0,0,.06); }
|
.pj-comment-dock .pj-comment-form:focus-within { border-color: #a9aeb6; box-shadow: 0 1px 6px rgba(0,0,0,.06); }
|
||||||
.pj-comment-dock .pj-comment-form input { border: none !important; box-shadow: none !important; padding: 8px 8px; font-size: 14px; outline: none; background: transparent; }
|
.pj-comment-dock .pj-comment-form input,
|
||||||
|
.pj-comment-dock .pj-comment-form textarea { border: none !important; box-shadow: none !important; padding: 8px 8px; font-size: 14px; outline: none; background: transparent; }
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
.pj-task-modal-card { width: 100vw; max-width: 100vw; min-width: 0; }
|
.pj-task-modal-card { width: 100vw; max-width: 100vw; min-width: 0; }
|
||||||
.pj-side-2col { display: block; }
|
.pj-side-2col { display: block; }
|
||||||
@@ -844,6 +874,12 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
|||||||
.pj-comment-body a:hover, .pj-chat-bubble a:hover { color: #0b3f99; }
|
.pj-comment-body a:hover, .pj-chat-bubble a:hover { color: #0b3f99; }
|
||||||
.pj-comment-form { display: flex; align-items: center; gap: 6px; }
|
.pj-comment-form { display: flex; align-items: center; gap: 6px; }
|
||||||
.pj-comment-form input { flex: 1; padding: 7px 10px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; font-family: inherit; box-sizing: border-box; }
|
.pj-comment-form input { flex: 1; padding: 7px 10px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; font-family: inherit; box-sizing: border-box; }
|
||||||
|
/* 댓글·답글 여러 줄 입력칸 — Enter 등록 · Shift+Enter 줄바꿈, 글 줄 수만큼 늘어남(project.js fitComposer, 최대 160px) */
|
||||||
|
.pj-comment-form textarea.pj-composer-ta {
|
||||||
|
flex: 1; min-width: 0; padding: 7px 10px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; font-family: inherit;
|
||||||
|
line-height: 1.45; box-sizing: border-box; resize: none; overflow-y: hidden; max-height: 160px; align-self: center;
|
||||||
|
}
|
||||||
|
.pj-comment-form textarea.pj-composer-ta:focus { outline: none; border-color: #a9aeb6; }
|
||||||
.pj-comment-acts { display: inline-flex; gap: 1px; flex: 0 0 auto; }
|
.pj-comment-acts { display: inline-flex; gap: 1px; flex: 0 0 auto; }
|
||||||
.pj-comment-edit-box { margin-top: 5px; }
|
.pj-comment-edit-box { margin-top: 5px; }
|
||||||
.pj-comment-edit-box textarea { width: 100%; box-sizing: border-box; padding: 7px 9px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; font-family: inherit; resize: vertical; }
|
.pj-comment-edit-box textarea { width: 100%; box-sizing: border-box; padding: 7px 9px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; font-family: inherit; resize: vertical; }
|
||||||
@@ -1049,6 +1085,9 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
|||||||
.pj-card-subtoggle-ic { display: block; margin-left: 3px; }
|
.pj-card-subtoggle-ic { display: block; margin-left: 3px; }
|
||||||
.pj-card-subtoggle-caret { font-size: 18px; margin-left: -2px; transition: transform .12s; }
|
.pj-card-subtoggle-caret { font-size: 18px; margin-left: -2px; transition: transform .12s; }
|
||||||
.pj-card-subtoggle.is-open .pj-card-subtoggle-caret { transform: rotate(180deg); }
|
.pj-card-subtoggle.is-open .pj-card-subtoggle-caret { transform: rotate(180deg); }
|
||||||
|
/* 하위 작업 없음 — 빈 버튼(카드 hover 때 .pj-card-meta .is-empty 규칙으로 보임), 펼친 동안은 늘 보임 */
|
||||||
|
.pj-card-subtoggle.is-empty { padding-left: 2px; }
|
||||||
|
.pj-card-meta .pj-card-subtoggle.is-empty.is-open { opacity: 1; }
|
||||||
/* 펼침 애니메이션 — grid 행 0fr→1fr 로 내용 높이만큼 부드럽게(높이 고정값 불필요) */
|
/* 펼침 애니메이션 — grid 행 0fr→1fr 로 내용 높이만큼 부드럽게(높이 고정값 불필요) */
|
||||||
.pj-card-subs-wrap {
|
.pj-card-subs-wrap {
|
||||||
display: grid; grid-template-rows: 0fr; margin-top: 0; opacity: 0;
|
display: grid; grid-template-rows: 0fr; margin-top: 0; opacity: 0;
|
||||||
@@ -1342,12 +1381,19 @@ label.pj-desc-fmtbtn {
|
|||||||
border: none; background: transparent; padding: 8px 10px; border-radius: 7px;
|
border: none; background: transparent; padding: 8px 10px; border-radius: 7px;
|
||||||
font-size: 13px; color: var(--pj-ink); cursor: pointer;
|
font-size: 13px; color: var(--pj-ink); cursor: pointer;
|
||||||
}
|
}
|
||||||
.pj-ctxmenu-item:hover { background: var(--pj-accent-tint); }
|
.pj-ctxmenu-item:hover, .pj-ctxmenu-item:focus { background: var(--pj-accent-tint); outline: none; }
|
||||||
|
.pj-ctxmenu-item:focus-visible { box-shadow: inset 0 0 0 2px var(--pj-accent); }
|
||||||
|
.pj-ctxmenu:focus { outline: none; }
|
||||||
.pj-ctxmenu-item.is-danger { color: #c22b10; }
|
.pj-ctxmenu-item.is-danger { color: #c22b10; }
|
||||||
.pj-ctxmenu-item.is-danger:hover { background: #fbecea; }
|
.pj-ctxmenu-item.is-danger:hover { background: #fbecea; }
|
||||||
.pj-ctxmenu-sep { height: 1px; background: var(--pj-border); margin: 4px 2px; }
|
.pj-ctxmenu-sep { height: 1px; background: var(--pj-border); margin: 4px 2px; }
|
||||||
/* 메뉴 항목 아이콘(담당자 아바타 등) + 오른쪽 현재값 ✓ */
|
/* 메뉴 항목 아이콘(담당자 아바타 등) + 오른쪽 현재값 ✓ */
|
||||||
.pj-ctxmenu-ic { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; }
|
.pj-ctxmenu-ic { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; }
|
||||||
|
/* 메뉴 왼쪽 아이콘(menuIcon) — 회색, 위험 항목(줄 삭제)은 글자색(빨강) 그대로 */
|
||||||
|
.pj-ctxmenu-mi { font-size: 18px; color: var(--pj-ink-soft); }
|
||||||
|
.pj-ctxmenu-item.is-danger .pj-ctxmenu-mi { color: inherit; }
|
||||||
|
.pj-ctxmenu-item:hover .pj-ctxmenu-mi { color: var(--pj-ink); }
|
||||||
|
.pj-ctxmenu-item.is-danger:hover .pj-ctxmenu-mi { color: inherit; }
|
||||||
.pj-ctxmenu-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.pj-ctxmenu-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.pj-ctxmenu-check { flex: 0 0 auto; font-size: 18px; color: var(--pj-accent); }
|
.pj-ctxmenu-check { flex: 0 0 auto; font-size: 18px; color: var(--pj-accent); }
|
||||||
.pj-ctxmenu-item.is-checked { font-weight: 600; }
|
.pj-ctxmenu-item.is-checked { font-weight: 600; }
|
||||||
@@ -1497,7 +1543,7 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
|||||||
/* 카드 담당자·마감일 없음 — 글자 대신 하위 업무 줄과 같은 점선 원 아이콘(아사나) */
|
/* 카드 담당자·마감일 없음 — 글자 대신 하위 업무 줄과 같은 점선 원 아이콘(아사나) */
|
||||||
.pj-card-assignee.is-empty,
|
.pj-card-assignee.is-empty,
|
||||||
.pj-card-due.is-empty {
|
.pj-card-due.is-empty {
|
||||||
display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px;
|
display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px;
|
||||||
padding: 0; margin: -2px 0; border-radius: 50%; color: #6d6e6f;
|
padding: 0; margin: -2px 0; border-radius: 50%; color: #6d6e6f;
|
||||||
}
|
}
|
||||||
.pj-card:hover .pj-card-meta .pj-card-assignee.is-empty,
|
.pj-card:hover .pj-card-meta .pj-card-assignee.is-empty,
|
||||||
@@ -1748,7 +1794,7 @@ html.pj-embed .pj-btn-goto-project { display: inline-flex; align-items: center;
|
|||||||
width: 18px; height: 18px; color: #a3a8b0; pointer-events: none;
|
width: 18px; height: 18px; color: #a3a8b0; pointer-events: none;
|
||||||
}
|
}
|
||||||
.pj-reply-form { margin: 4px 0 8px; }
|
.pj-reply-form { margin: 4px 0 8px; }
|
||||||
.pj-reply-form input { padding: 5px 9px; font-size: 12.5px; }
|
.pj-reply-form input, .pj-reply-form textarea.pj-composer-ta { padding: 5px 9px; font-size: 12.5px; }
|
||||||
.pj-reply-form .pj-btn { padding: 5px 12px; font-size: 12px; }
|
.pj-reply-form .pj-btn { padding: 5px 12px; font-size: 12px; }
|
||||||
|
|
||||||
.pj-comment-event, .pj-chat-event {
|
.pj-comment-event, .pj-chat-event {
|
||||||
@@ -1991,6 +2037,8 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
|||||||
}
|
}
|
||||||
.pj-side-goal-add:hover { background: #f1f2f4; color: var(--pj-ink); }
|
.pj-side-goal-add:hover { background: #f1f2f4; color: var(--pj-ink); }
|
||||||
|
|
||||||
|
/* 목표·회의록 제목 — 크게(32px)·굵게 */
|
||||||
|
.pj-goal-view h2.pj-goal-title { font-size: 32px; font-weight: 800; letter-spacing: -.6px; line-height: 1.2; }
|
||||||
/* 표는 화면 폭 전체 — 내 작업·수신함의 읽기 폭 제한(1180px)을 푼다 */
|
/* 표는 화면 폭 전체 — 내 작업·수신함의 읽기 폭 제한(1180px)을 푼다 */
|
||||||
.pj-goal-view .pj-main { max-width: none; }
|
.pj-goal-view .pj-main { max-width: none; }
|
||||||
.pj-goal-head-acts { display: flex; align-items: center; gap: 10px; }
|
.pj-goal-head-acts { display: flex; align-items: center; gap: 10px; }
|
||||||
@@ -2006,8 +2054,10 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
|||||||
|
|
||||||
/* 가로·세로 스크롤은 이 칸 하나가 맡고, 머리 줄과 왼쪽 두 칸(구분·항목)은 붙어 있다 */
|
/* 가로·세로 스크롤은 이 칸 하나가 맡고, 머리 줄과 왼쪽 두 칸(구분·항목)은 붙어 있다 */
|
||||||
.pj-goal-pane { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
.pj-goal-pane { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
||||||
|
/* width: 1px — table-layout: fixed 는 표 너비가 auto 가 아닐 때만 먹는다. 표는 칸 너비 합만큼 늘어나고,
|
||||||
|
칸 너비가 머리 칸 width 로만 정해져야 분기 접기 애니메이션이 양방향으로 부드럽다(auto 면 펼 때 한 번에 튄다). */
|
||||||
.pj-goal-table {
|
.pj-goal-table {
|
||||||
border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
|
width: 1px; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
|
||||||
color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px;
|
color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px;
|
||||||
}
|
}
|
||||||
/* 칸 너비는 여백·테두리 포함(border-box) — 안 그러면 padding 만큼 넓어진다 */
|
/* 칸 너비는 여백·테두리 포함(border-box) — 안 그러면 padding 만큼 넓어진다 */
|
||||||
@@ -2017,11 +2067,12 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
|||||||
}
|
}
|
||||||
.pj-goal-table tr > :last-child { border-right: none; }
|
.pj-goal-table tr > :last-child { border-right: none; }
|
||||||
.pj-goal-table thead th {
|
.pj-goal-table thead th {
|
||||||
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 10px;
|
position: sticky; top: 0; z-index: 9; background: #f7f8f9; height: 32px; padding: 0 10px;
|
||||||
font-weight: 700; text-align: center; vertical-align: middle; white-space: nowrap;
|
font-weight: 700; text-align: center; vertical-align: middle; white-space: nowrap;
|
||||||
}
|
}
|
||||||
.pj-goal-table thead th { width: 85px; min-width: 85px; max-width: 85px; } /* 1~12월 */
|
/* 열 너비 = 머리 칸 너비(table-layout: fixed). --cw 는 initGoals 가 머리 칸마다 넣는다(끌어서 조절, localStorage pj_goal_col_w) */
|
||||||
.pj-goal-table thead th.pj-goal-year-col { width: 90px; min-width: 90px; max-width: 90px; }
|
.pj-goal-table thead th { width: var(--cw, 85px); min-width: var(--cw, 85px); max-width: var(--cw, 85px); } /* 1~12월 */
|
||||||
|
.pj-goal-table thead th.pj-goal-year-col { width: var(--cw, 90px); min-width: var(--cw, 90px); max-width: var(--cw, 90px); }
|
||||||
.pj-goal-table thead th.is-now { color: var(--pj-accent-dark); box-shadow: inset 0 -2px 0 var(--pj-accent); }
|
.pj-goal-table thead th.is-now { color: var(--pj-accent-dark); box-shadow: inset 0 -2px 0 var(--pj-accent); }
|
||||||
/* 왼쪽 고정 두 칸(구분·항목) — 너비는 머리 칸 오른쪽 끝을 끌어 조절(initGoals, localStorage
|
/* 왼쪽 고정 두 칸(구분·항목) — 너비는 머리 칸 오른쪽 끝을 끌어 조절(initGoals, localStorage
|
||||||
pj_goal_col_w). --goal-c1-w 가 c2 의 left 도 같이 정한다. */
|
pj_goal_col_w). --goal-c1-w 가 c2 의 left 도 같이 정한다. */
|
||||||
@@ -2034,8 +2085,8 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
|||||||
left: var(--goal-c1-w); width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w);
|
left: var(--goal-c1-w); width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w);
|
||||||
font-weight: 600; color: #3b4048;
|
font-weight: 600; color: #3b4048;
|
||||||
}
|
}
|
||||||
.pj-goal-table thead th.pj-goal-c1 { z-index: 4; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
|
.pj-goal-table thead th.pj-goal-c1 { z-index: 10; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
|
||||||
.pj-goal-table thead th.pj-goal-c2 { z-index: 4; width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w); }
|
.pj-goal-table thead th.pj-goal-c2 { z-index: 10; width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w); }
|
||||||
.pj-goal-colresize {
|
.pj-goal-colresize {
|
||||||
position: absolute; top: 0; right: -4px; bottom: 0; width: 8px; z-index: 5; cursor: col-resize;
|
position: absolute; top: 0; right: -4px; bottom: 0; width: 8px; z-index: 5; cursor: col-resize;
|
||||||
}
|
}
|
||||||
@@ -2043,10 +2094,18 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
|||||||
content: ""; position: absolute; top: 6px; bottom: 6px; left: 3px; width: 2px; border-radius: 2px; background: transparent;
|
content: ""; position: absolute; top: 6px; bottom: 6px; left: 3px; width: 2px; border-radius: 2px; background: transparent;
|
||||||
}
|
}
|
||||||
.pj-goal-colresize:hover::after, .pj-goal-colresize.is-dragging::after { background: var(--pj-accent); }
|
.pj-goal-colresize:hover::after, .pj-goal-colresize.is-dragging::after { background: var(--pj-accent); }
|
||||||
|
/* 월 칸은 overflow: hidden(접기 애니메이션)이라 칸 밖으로 나간 손잡이가 잘린다 — 칸 안쪽 오른쪽 끝에 둔다 */
|
||||||
|
.pj-goal-table thead th.pj-goal-m .pj-goal-colresize { right: 0; width: 7px; }
|
||||||
|
.pj-goal-table thead th.pj-goal-m .pj-goal-colresize::after { left: auto; right: 1px; }
|
||||||
html.pj-goal-resizing, html.pj-goal-resizing * { cursor: col-resize !important; user-select: none !important; }
|
html.pj-goal-resizing, html.pj-goal-resizing * { cursor: col-resize !important; user-select: none !important; }
|
||||||
.pj-goal-table tbody th { padding: 7px 8px; vertical-align: middle; } /* 왼쪽 이름은 세로 가운데 */
|
.pj-goal-table tbody th { padding: 7px 8px; vertical-align: middle; } /* 왼쪽 이름은 세로 가운데 */
|
||||||
|
|
||||||
/* 숫자 지표 */
|
/* 숫자 지표 — 틀 고정: 머리 줄 아래에 로아스 줄까지 붙어 있다(줄마다 top = --kpi-top, initGoals stickKpi).
|
||||||
|
z-index: 업무 영역 이름 칸 2(마우스 올림 6) < 지표 칸 7 < 지표 이름 칸 8 < 머리 줄 9 < 머리 이름 칸 10.
|
||||||
|
스크롤에 아래 줄이 비치지 않게 배경을 채운다(:where = 아래 .pj-goal-sum 등 배경이 이긴다). */
|
||||||
|
.pj-goal-kpi > tr > * { position: sticky; top: var(--kpi-top, 0); z-index: 7; }
|
||||||
|
.pj-goal-kpi > tr > .pj-goal-c1, .pj-goal-kpi > tr > .pj-goal-c2 { z-index: 8; }
|
||||||
|
:where(.pj-goal-kpi) td { background: #fff; }
|
||||||
.pj-goal-kpi td { height: 32px; vertical-align: middle; }
|
.pj-goal-kpi td { height: 32px; vertical-align: middle; }
|
||||||
.pj-goal-kpi td.is-now { background: #faf9ff; }
|
.pj-goal-kpi td.is-now { background: #faf9ff; }
|
||||||
input.pj-goal-num, span.pj-goal-num {
|
input.pj-goal-num, span.pj-goal-num {
|
||||||
@@ -2066,35 +2125,433 @@ input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -
|
|||||||
.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
||||||
.pj-goal-area-name { font-size: 13px; font-weight: 800 !important; }
|
.pj-goal-area-name { font-size: 13px; font-weight: 800 !important; }
|
||||||
.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; }
|
.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; }
|
||||||
/* 관리자 도구(✎ 색 ↑ ↓ + ×) — 이름 칸 아래에 떠 있는 작은 막대. 자리를 차지하지 않아야
|
/* 구역·항목 칸 메뉴(색·순서·줄 추가·삭제)는 우클릭(project.js areaMenuItems·rowMenuItems) — 마우스 오버 도구 막대는 2026-10-01 요청으로 뺐다.
|
||||||
이름이 세로 가운데에 온다. 칸 안에 붙어 있어 마우스를 막대로 옮겨도 사라지지 않는다. */
|
대신 칸 오른쪽 위 작은 ⋮ 버튼(.pj-goal-menu-btn, 관리자만) — 자리를 차지하지 않게 absolute, 평소 투명·칸에 마우스/포커스가 오면 보임.
|
||||||
.pj-goal-area-name:hover, .pj-goal-row-label:hover, .pj-goal-area-name:focus-within, .pj-goal-row-label:focus-within { z-index: 6; }
|
키보드(Tab → Enter/Space)·터치(마우스 없는 화면은 늘 옅게 보임)로도 같은 메뉴. */
|
||||||
.pj-goal-tools {
|
.pj-goal-menu-btn {
|
||||||
position: absolute; top: calc(100% - 6px); left: 50%; transform: translateX(-50%); z-index: 7;
|
position: absolute; top: 2px; right: 1px; z-index: 3; display: inline-flex; align-items: center; justify-content: center;
|
||||||
display: flex; flex-wrap: nowrap; gap: 1px; padding: 3px; background: #ffe3c7; border: 1px solid #f6c69a;
|
width: 18px; height: 22px; padding: 0; border: none; border-radius: 5px; background: transparent; color: var(--pj-ink-soft);
|
||||||
border-radius: 10px; box-shadow: 0 4px 12px rgba(16, 24, 40, .14); /* 파스텔 주황 */
|
cursor: pointer; opacity: 0; transition: opacity .12s;
|
||||||
opacity: 0; pointer-events: none; transition: opacity .12s;
|
|
||||||
}
|
}
|
||||||
.pj-goal-area-name:hover .pj-goal-tools, .pj-goal-row-label:hover .pj-goal-tools,
|
.pj-goal-menu-btn .material-symbols-outlined { font-size: 17px; }
|
||||||
.pj-goal-tools:focus-within { opacity: 1; pointer-events: auto; }
|
.pj-goal-menu-btn:hover, .pj-goal-menu-btn[aria-expanded="true"] { background: rgba(255, 255, 255, .85); color: var(--pj-ink); box-shadow: 0 0 0 1px rgba(0, 0, 0, .12); }
|
||||||
.pj-goal-tools .pj-icon-btn { width: 30px; height: 30px; font-size: 20px; color: #8a4b14; border-radius: 7px; }
|
th.pj-goal-area-name:hover .pj-goal-menu-btn, th.pj-goal-row-label:hover .pj-goal-menu-btn,
|
||||||
.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 22px; }
|
th.pj-goal-area-name:focus-within .pj-goal-menu-btn, th.pj-goal-row-label:focus-within .pj-goal-menu-btn,
|
||||||
.pj-goal-tools .pj-icon-btn:hover { background: #ffc98f; color: #5c2e06; }
|
.pj-goal-menu-btn:focus-visible, .pj-goal-menu-btn[aria-expanded="true"] { opacity: 1; }
|
||||||
|
.pj-goal-menu-btn:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 0; }
|
||||||
|
@media (hover: none) { .pj-goal-menu-btn { opacity: .7; } }
|
||||||
|
.pj-goal-area-text[tabindex]:focus-visible, .pj-goal-row-text[tabindex]:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 1px; border-radius: 4px; }
|
||||||
|
html.pj-goal-selecting .pj-goal-menu-btn { pointer-events: none; }
|
||||||
|
@media print { .pj-goal-menu-btn { display: none !important; } }
|
||||||
textarea.pj-goal-text {
|
textarea.pj-goal-text {
|
||||||
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 6px; border: none;
|
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 6px; border: none;
|
||||||
background: transparent; font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
|
background: transparent; font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
|
||||||
}
|
}
|
||||||
textarea.pj-goal-text:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .75); }
|
/* 입력 중인 칸 — 테두리·밝은 배경은 입력칸(글 높이만큼)이 아니라 칸 전체(td)에 */
|
||||||
|
textarea.pj-goal-text:focus { outline: none; }
|
||||||
|
.pj-goal-table td.pj-goal-texttd:focus-within {
|
||||||
|
box-shadow: inset 0 0 0 2px var(--pj-accent);
|
||||||
|
background-image: linear-gradient(rgba(255, 255, 255, .75), rgba(255, 255, 255, .75));
|
||||||
|
}
|
||||||
textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
|
textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
|
||||||
.pj-goal-text-ro { min-height: 46px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
.pj-goal-text-ro { min-height: 46px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
.pj-goal-area td.is-now { box-shadow: inset 2px 0 0 rgba(123, 104, 238, .35), inset -2px 0 0 rgba(123, 104, 238, .35); }
|
.pj-goal-area td.is-now { box-shadow: inset 2px 0 0 rgba(123, 104, 238, .35), inset -2px 0 0 rgba(123, 104, 238, .35); }
|
||||||
.pj-goal-texttd.pj-goal-year-col { font-weight: 600; }
|
.pj-goal-texttd.pj-goal-year-col { font-weight: 600; }
|
||||||
|
/* 가로 스크롤 때 3열(구분·항목·연간)까지 고정 — 연간 열 left = 1열 + 2열 너비, 오른쪽에 경계 그림자.
|
||||||
|
z-index: 업무 영역 칸 2(이름 칸과 같게) · 지표 칸 8(지표 이름 칸과 같게, 틀 고정 줄) · 머리 칸 10 */
|
||||||
|
.pj-goal-table .pj-goal-year-col {
|
||||||
|
position: sticky; left: calc(var(--goal-c1-w) + var(--goal-c2-w)); z-index: 2;
|
||||||
|
box-shadow: 4px 0 6px -4px rgba(16, 24, 40, .18);
|
||||||
|
}
|
||||||
|
.pj-goal-kpi > tr > .pj-goal-year-col { z-index: 8; }
|
||||||
|
.pj-goal-table thead th.pj-goal-year-col { z-index: 10; }
|
||||||
|
.pj-goal-area > tr > td.pj-goal-year-col { background-color: var(--goal-bg, #fff); }
|
||||||
|
.pj-goal-table td.pj-goal-texttd.pj-goal-year-col:focus-within {
|
||||||
|
box-shadow: inset 0 0 0 2px var(--pj-accent), 4px 0 6px -4px rgba(16, 24, 40, .18);
|
||||||
|
}
|
||||||
|
.pj-goal-table td.pj-goal-year-col.is-merge-sel { box-shadow: inset 0 0 0 2px var(--pj-accent), 4px 0 6px -4px rgba(16, 24, 40, .18); }
|
||||||
|
|
||||||
.pj-goal-numtd.is-saved, .pj-goal-texttd.is-saved { animation: pj-goal-saved 1s ease-out; }
|
.pj-goal-numtd.is-saved, .pj-goal-texttd.is-saved { animation: pj-goal-saved 1s ease-out; }
|
||||||
|
/* 저장 실패한 칸 — 빨간 테두리(입력한 내용은 그대로, 다시 입력·칸 떠남·Enter 에 다시 저장) */
|
||||||
|
.pj-goal-table td.is-save-failed, .pj-meet-table td.is-save-failed, .pj-meet-kpi.is-save-failed,
|
||||||
|
.pj-meet-notes textarea.is-save-failed { box-shadow: inset 0 0 0 2px #d93025 !important; }
|
||||||
@keyframes pj-goal-saved { from { box-shadow: inset 0 0 0 2px #34a853; } to { box-shadow: inset 0 0 0 2px transparent; } }
|
@keyframes pj-goal-saved { from { box-shadow: inset 0 0 0 2px #34a853; } to { box-shadow: inset 0 0 0 2px transparent; } }
|
||||||
|
|
||||||
|
.pj-goal-table th.is-saved { animation: pj-goal-saved 1s ease-out; }
|
||||||
|
|
||||||
|
/* 분기 칸(클래스 이름은 반기 때 그대로) — 3·6·9·12월 오른쪽. 앞 칸 오른쪽 테두리와 겹쳐 두 줄로 구분된다. */
|
||||||
|
.pj-goal-table thead th.pj-goal-half-col {
|
||||||
|
width: var(--cw, 90px); min-width: var(--cw, 90px); max-width: var(--cw, 90px); padding: 0 6px; background: #eef0f3;
|
||||||
|
}
|
||||||
|
.pj-goal-table .pj-goal-half-col { border-left: 1px solid #cfd3d8; }
|
||||||
|
.pj-goal-kpi td.pj-goal-half-col { background: #f4f5f7; }
|
||||||
|
.pj-goal-texttd.pj-goal-half-col { font-weight: 600; }
|
||||||
|
.pj-goal-kpi td { white-space: nowrap; }
|
||||||
|
/* 분기 색(monday.com 그룹 색 띠 방식, 2026-10-01) — 좋고 나쁨 뜻이 없는 차분한 색(달성률 빨강·초록과 겹치지 않게).
|
||||||
|
data-h(분기 1~4)가 있는 칸마다 --qc(띠·글자) · --qt(분기 열 음영) · --qt2(접힌 분기 머리) */
|
||||||
|
.pj-goal-table [data-h="1"] { --qc: #4f7cc9; --qt: rgba(79, 124, 201, .09); --qt2: rgba(79, 124, 201, .18); }
|
||||||
|
.pj-goal-table [data-h="2"] { --qc: #2a9d8f; --qt: rgba(42, 157, 143, .09); --qt2: rgba(42, 157, 143, .18); }
|
||||||
|
.pj-goal-table [data-h="3"] { --qc: #8a63c9; --qt: rgba(138, 99, 201, .09); --qt2: rgba(138, 99, 201, .18); }
|
||||||
|
.pj-goal-table [data-h="4"] { --qc: #3d4f73; --qt: rgba(61, 79, 115, .09); --qt2: rgba(61, 79, 115, .18); }
|
||||||
|
/* 머리 위 색 띠 — 월 칸 3px, 분기 칸 6px(같은 색으로 이어져 "석 달 + 합계"가 한 묶음). 월 이름 링크가 칸을 덮어도 보이게 ::before */
|
||||||
|
.pj-goal-table thead th[data-h]::before {
|
||||||
|
content: ""; position: absolute; left: 0; right: 0; top: 0; height: 3px; background: var(--qc); z-index: 2; pointer-events: none;
|
||||||
|
}
|
||||||
|
.pj-goal-table thead th.pj-goal-half-col[data-h]::before { height: 6px; }
|
||||||
|
/* 분기 열 — 같은 색 옅은 음영(영역 색 위에도 덮인다) + 오른쪽 굵은 경계(분기 묶음의 끝) */
|
||||||
|
.pj-goal-table td.pj-goal-half-col[data-h] { background-image: linear-gradient(var(--qt), var(--qt)); }
|
||||||
|
.pj-goal-table .pj-goal-half-col { border-right: 2px solid #a3abb5; }
|
||||||
|
.pj-goal-table tr > .pj-goal-half-col:last-child { border-right: none; }
|
||||||
|
|
||||||
|
/* 분기 접기 — 머리 칸 전체가 버튼(.pj-goal-fold-th, project.js). 아이콘은 엑셀 열 그룹처럼 네모 안 −(펼침) / +(접힘):
|
||||||
|
바뀔 때 아이콘이 90° 돌며 세로 막대가 자라나거나(− → +) 줄어든다(+ → −). 접힌 분기 머리는 분기 색으로 진하게 */
|
||||||
|
.pj-goal-table thead th.pj-goal-fold-th { cursor: pointer; user-select: none; transition: background-color .15s; color: var(--qc); }
|
||||||
|
.pj-goal-table thead th.pj-goal-fold-th:hover { background: #e3e6ea; }
|
||||||
|
.pj-goal-table thead th.pj-goal-fold-th.is-folded { background-image: linear-gradient(var(--qt2), var(--qt2)); }
|
||||||
|
.pj-goal-fold {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px;
|
||||||
|
margin: 0 3px 0 -3px; padding: 0; border: none; border-radius: 5px; background: transparent;
|
||||||
|
color: var(--qc, var(--pj-ink-soft)); cursor: pointer; vertical-align: -5px; pointer-events: none; /* 클릭은 머리 칸이 받는다 */
|
||||||
|
}
|
||||||
|
.pj-goal-fold-ic { display: block; transition: transform .32s cubic-bezier(.4, 0, .2, 1); }
|
||||||
|
.pj-goal-fold-v {
|
||||||
|
transform-box: fill-box; transform-origin: center; transform: scaleY(0);
|
||||||
|
transition: transform .32s cubic-bezier(.4, 0, .2, 1);
|
||||||
|
}
|
||||||
|
.pj-goal-fold.is-folded .pj-goal-fold-ic { transform: rotate(90deg); }
|
||||||
|
.pj-goal-fold.is-folded .pj-goal-fold-v { transform: scaleY(1); }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.pj-goal-fold-ic, .pj-goal-fold-v { transition: none; }
|
||||||
|
}
|
||||||
|
/* 접기 애니메이션 — 월 칸 너비를 0 으로(.is-shrunk) 줄인 뒤 숨김(.is-gone), 펼 땐 거꾸로(initGoals applyFold).
|
||||||
|
줄어드는 동안 칸 안 글이 다시 줄바꿈돼 줄 높이가 출렁이지 않게 안쪽 내용은 원래 폭(--fold-w = 걸친 월 너비 합)으로 고정해 잘라 낸다. */
|
||||||
|
.pj-goal-table .pj-goal-m { overflow: hidden; }
|
||||||
|
.pj-goal-table.is-folding .pj-goal-m {
|
||||||
|
transition: width .32s ease, min-width .32s ease, max-width .32s ease,
|
||||||
|
padding .32s ease, border-right-width .32s ease;
|
||||||
|
}
|
||||||
|
.pj-goal-table.is-folding td.pj-goal-m > * { width: var(--fold-w, calc(85px * var(--span, 1) - 1px)); }
|
||||||
|
.pj-goal-table thead th.pj-goal-m.is-shrunk,
|
||||||
|
.pj-goal-table td.pj-goal-m.is-shrunk {
|
||||||
|
width: 0; min-width: 0; max-width: 0; padding-left: 0 !important; padding-right: 0 !important; border-right-width: 0;
|
||||||
|
}
|
||||||
|
.pj-goal-table .pj-goal-m.is-gone { display: none; }
|
||||||
|
|
||||||
|
/* 영역·줄 이름 — 눌러서 그 자리에서 수정(관리자) */
|
||||||
|
.pj-goal-table [data-goal-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; }
|
||||||
|
.pj-goal-table [data-goal-edit]:hover { background: rgba(255, 255, 255, .65); box-shadow: 0 0 0 1px rgba(0, 0, 0, .14); }
|
||||||
|
.pj-goal-table [data-goal-edit].is-editing {
|
||||||
|
background: #fff; box-shadow: 0 0 0 2px var(--pj-accent); outline: none; word-break: normal;
|
||||||
|
}
|
||||||
|
.pj-goal-row-text[data-goal-edit]:empty { min-height: 1.5em; }
|
||||||
|
.pj-goal-row-text[data-goal-edit]:empty:hover::before { content: "줄 이름"; color: rgba(0, 0, 0, .3); font-weight: 500; }
|
||||||
|
|
||||||
|
/* 칸 병합 — 끌어서(또는 Shift+클릭) 고른 범위 표시. 우클릭 메뉴로 셀 병합·병합 해제 */
|
||||||
|
.pj-goal-table td.pj-goal-texttd.is-merge-sel {
|
||||||
|
box-shadow: inset 0 0 0 2px var(--pj-accent);
|
||||||
|
background-image: linear-gradient(rgba(123, 104, 238, .12), rgba(123, 104, 238, .12));
|
||||||
|
}
|
||||||
|
|
||||||
.pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; }
|
.pj-goal-foot { display: flex; align-items: center; gap: 12px; margin: 12px 0 4px; }
|
||||||
|
|
||||||
|
/* 표를 그 자리에서 다시 그린 뒤(refreshTable) — 새 줄 잠깐 강조, 병합한 칸 테두리 강조 */
|
||||||
|
.pj-goal-table tr.is-new-row > * { animation: pj-goal-row-new 1.4s ease-out; }
|
||||||
|
@keyframes pj-goal-row-new { from { box-shadow: inset 0 0 0 999px rgba(123, 104, 238, .16); } to { box-shadow: inset 0 0 0 999px rgba(123, 104, 238, 0); } }
|
||||||
|
.pj-goal-table td.is-merge-flash { animation: pj-goal-merge-flash 1.2s ease-out; }
|
||||||
|
@keyframes pj-goal-merge-flash { from { box-shadow: inset 0 0 0 2px var(--pj-accent), inset 0 0 0 999px rgba(123, 104, 238, .14); }
|
||||||
|
to { box-shadow: inset 0 0 0 2px transparent, inset 0 0 0 999px rgba(123, 104, 238, 0); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .pj-goal-table tr.is-new-row > *, .pj-goal-table td.is-merge-flash { animation: none; } }
|
||||||
|
/* 칸 병합 — 끌어서 고르는 동안 글 선택 막기 */
|
||||||
|
html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; cursor: cell !important; }
|
||||||
|
/* 칸 아무 곳이나 눌러 입력 — 칸 전체가 글 입력 커서(관리자 화면) */
|
||||||
|
.pj-goal-table[data-admin="true"] tbody.pj-goal-area td.pj-goal-texttd { cursor: text; }
|
||||||
|
.pj-meet-table td.pj-meet-c-text:not(.is-prev), .pj-meet-table td.pj-meet-c-amt:not(.is-prev) { cursor: text; }
|
||||||
|
/* 월 머리 → 그 달 주간 회의록 */
|
||||||
|
/* 월 머리 칸 전체가 링크(글자만이 아니라) — 오른쪽 끝 너비 조절 손잡이(z-index 5)는 링크 위에 남는다 */
|
||||||
|
.pj-goal-mlink {
|
||||||
|
position: absolute; inset: 0; z-index: 1; display: flex; align-items: center; justify-content: center;
|
||||||
|
color: inherit; text-decoration: none; cursor: pointer;
|
||||||
|
}
|
||||||
|
.pj-goal-mlink:hover { color: var(--pj-accent-dark); background: var(--pj-accent-tint); }
|
||||||
|
.pj-goal-table thead th.is-now .pj-goal-mlink { box-shadow: inset 0 -2px 0 var(--pj-accent); } /* 이번 달 밑줄을 덮지 않게 */
|
||||||
|
.pj-btn-sm { padding: 4px 10px; font-size: 12.5px; text-decoration: none; display: inline-flex; align-items: center; }
|
||||||
|
|
||||||
|
/* ════════════════════════════════════════════════════════════
|
||||||
|
주간 회의록(goal_meeting.html) — 주차 탭 · 머리 숫자 카드 · 구역별 줄(이번주 | 지난주 리뷰) · 메모
|
||||||
|
════════════════════════════════════════════════════════════ */
|
||||||
|
.pj-meet-pane { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
||||||
|
.pj-meet-title { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.pj-meet-title h2 { margin: 0 6px 0 0; }
|
||||||
|
/* 연간 목표로 가는 큰 버튼(회의록 제목 왼쪽) */
|
||||||
|
.pj-meet-goalbtn {
|
||||||
|
display: inline-flex; align-items: center; gap: 6px; padding: 7px 14px 7px 10px; margin-right: 6px; border-radius: 12px;
|
||||||
|
background: var(--pj-accent-tint); color: var(--pj-accent-dark); border: 1.5px solid #cfc6fb;
|
||||||
|
font-size: 15px; font-weight: 800; text-decoration: none; white-space: nowrap; transition: background .12s, color .12s;
|
||||||
|
}
|
||||||
|
.pj-meet-goalbtn .material-symbols-outlined { font-size: 26px; }
|
||||||
|
.pj-meet-goalbtn:hover { background: var(--pj-accent); border-color: var(--pj-accent); color: #fff; }
|
||||||
|
.pj-goal-head-acts .pj-btn .material-symbols-outlined { font-size: 17px; vertical-align: -3px; }
|
||||||
|
|
||||||
|
/* 머리 — 왼쪽: 제목·인쇄·삭제 … 주차 탭(달력 쪽 끝) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력(폭 174px, 글자 10.5px) */
|
||||||
|
.pj-meet-headgrid { display: flex; align-items: flex-start; gap: 10px; margin: 8px 0 12px; }
|
||||||
|
.pj-meet-headleft { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.pj-meet-headleft > .pj-meet-plan { margin: 0; }
|
||||||
|
.pj-meet-title { flex-wrap: wrap; }
|
||||||
|
.pj-meet-title-acts { display: inline-flex; align-items: center; gap: 6px; margin-left: 4px; }
|
||||||
|
.pj-meet-title-acts .material-symbols-outlined { font-size: 16px; margin-right: 3px; }
|
||||||
|
/* 주차 탭 — 제목 줄 오른쪽 끝(달력 바로 왼쪽)에 붙인다 */
|
||||||
|
.pj-meet-weeks { display: flex; flex-wrap: wrap; gap: 4px; margin: 0 0 0 auto; padding-top: 6px; } /* "이번 주" 꼬리표 자리 */
|
||||||
|
.pj-meet-cal {
|
||||||
|
flex: 0 0 auto; width: 174px; padding: 6px 6px 4px; border: 1px solid var(--pj-border); border-radius: 10px; background: #fff;
|
||||||
|
}
|
||||||
|
.pj-meet-cal-head { font-size: 11px; font-weight: 800; text-align: center; margin-bottom: 2px; }
|
||||||
|
.pj-meet-cal-wd, .pj-meet-cal-row { display: grid; grid-template-columns: repeat(7, 1fr); }
|
||||||
|
.pj-meet-cal-wd span { font-size: 9px; font-weight: 700; color: var(--pj-ink-soft); text-align: center; padding: 1px 0; }
|
||||||
|
.pj-meet-cal-row {
|
||||||
|
position: relative; margin: 1px 0; border-radius: 7px; color: var(--pj-ink); text-decoration: none; cursor: pointer;
|
||||||
|
}
|
||||||
|
.pj-meet-cal-row:hover { background: #f3f4f6; }
|
||||||
|
/* 보고 있는 주 = 영역 표시 */
|
||||||
|
.pj-meet-cal-row.is-on { background: var(--pj-accent-tint); box-shadow: inset 0 0 0 1.5px var(--pj-accent); }
|
||||||
|
/* 앞뒤 달에 속한 주(월요일이 다른 달) — 흐리게, 누르면 그 달 회의록 */
|
||||||
|
.pj-meet-cal-row.is-other { opacity: .55; }
|
||||||
|
.pj-meet-cal-row.is-other:hover { opacity: 1; }
|
||||||
|
.pj-meet-cal-d { height: 21px; line-height: 21px; text-align: center; font-size: 10.5px; font-variant-numeric: tabular-nums; }
|
||||||
|
.pj-meet-cal-d.is-sat { color: #2563eb; }
|
||||||
|
.pj-meet-cal-d.is-sun { color: #dc2626; }
|
||||||
|
.pj-meet-cal-d.is-out { opacity: .35; }
|
||||||
|
.pj-meet-cal-d.is-today { position: relative; color: #fff; font-weight: 800; z-index: 0; }
|
||||||
|
.pj-meet-cal-d.is-today::before {
|
||||||
|
content: ""; position: absolute; inset: 1px 3px; border-radius: 999px; background: var(--pj-accent); z-index: -1;
|
||||||
|
}
|
||||||
|
.pj-meet-cal-row.is-on .pj-meet-cal-d { font-weight: 700; }
|
||||||
|
/* 회의록 있음 점 — 달력 왼쪽 여백 안(달력 밖으로 나가지 않게) */
|
||||||
|
.pj-meet-cal-dot { position: absolute; left: -5px; top: 50%; width: 4px; height: 4px; margin-top: -2px; border-radius: 50%; background: #34a853; }
|
||||||
|
@media (max-width: 900px) { .pj-meet-headgrid { flex-direction: column; } .pj-meet-cal { align-self: flex-end; } }
|
||||||
|
@media print { .pj-meet-cal { display: none !important; } }
|
||||||
|
.pj-meet-week {
|
||||||
|
position: relative; display: flex; align-items: baseline; gap: 3px; padding: 3px 10px 3px 7px; white-space: nowrap;
|
||||||
|
border: 1px solid var(--pj-border); border-radius: 8px; background: #fff; color: var(--pj-ink); text-decoration: none;
|
||||||
|
}
|
||||||
|
.pj-meet-week b { font-size: 11.5px; }
|
||||||
|
.pj-meet-week span { font-size: 10px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
|
||||||
|
.pj-meet-week em { position: absolute; top: -8px; right: 6px; font-style: normal; font-size: 9.5px; font-weight: 700; line-height: 14px;
|
||||||
|
padding: 0 5px; border-radius: 999px; background: var(--pj-accent); color: #fff; }
|
||||||
|
.pj-meet-week:hover { border-color: #cfd3d8; background: #fafafb; }
|
||||||
|
.pj-meet-week.is-on { border-color: var(--pj-accent); box-shadow: inset 0 0 0 1px var(--pj-accent); background: var(--pj-accent-tint); }
|
||||||
|
.pj-meet-dot { position: absolute; top: 3px; left: 3px; width: 6px; height: 6px; border-radius: 50%; background: #34a853; }
|
||||||
|
|
||||||
|
/* 매출 자료 갱신 — 정상이면 숨김. 실패·일부 실패·권한 없음일 때만 작은 안내(initMeetingSync, #pj-meet-sync.pj-meet-syncnote) */
|
||||||
|
.pj-meet-syncnote {
|
||||||
|
display: flex; align-items: center; gap: 6px; margin: -4px 0 8px; padding: 4px 8px; border-radius: 7px;
|
||||||
|
font-size: 12px; line-height: 1.4; background: #fff4ec; color: #9a4a07;
|
||||||
|
}
|
||||||
|
.pj-meet-syncnote[hidden] { display: none; }
|
||||||
|
.pj-meet-syncnote .material-symbols-outlined { font-size: 16px; flex: 0 0 auto; }
|
||||||
|
.pj-meet-syncnote .pj-btn { margin-left: auto; flex: 0 0 auto; }
|
||||||
|
.pj-meet-syncnote[data-state="noperm"] { background: #f6f7f9; color: var(--pj-ink-soft); }
|
||||||
|
.pj-meet-syncnote[data-state="noperm"] .material-symbols-outlined { display: none; }
|
||||||
|
.pj-meet-syncnote[data-state="running"] { background: #eef4ff; color: #1d4ed8; }
|
||||||
|
@media print { .pj-meet-syncnote { display: none !important; } }
|
||||||
|
/* 실적 미확인(조회 실패) — 0 원과 구분 */
|
||||||
|
.pj-meet-unknown { color: #b45309; font-weight: 700; font-size: .92em; }
|
||||||
|
.pj-meet-unknown::before { content: "⚠ "; font-weight: 400; }
|
||||||
|
.pj-meet-perf-warn { color: #9a4a07; }
|
||||||
|
.pj-meet-noprev { font-weight: 500; color: rgba(0, 0, 0, .45); }
|
||||||
|
.pj-meet-market.is-unknown { background: #fff4ec; color: #b45309; }
|
||||||
|
.pj-meet-week-auto.is-unknown { color: #b45309; }
|
||||||
|
.pj-meet-sync {
|
||||||
|
display: flex; align-items: center; gap: 8px; margin: -4px 0 10px; padding: 6px 10px; border-radius: 8px;
|
||||||
|
background: #f6f7f9; color: var(--pj-ink-soft); font-size: 12.5px;
|
||||||
|
}
|
||||||
|
.pj-meet-sync .material-symbols-outlined { font-size: 17px; }
|
||||||
|
.pj-meet-sync .pj-btn { margin-left: auto; }
|
||||||
|
.pj-meet-sync.is-running { background: #eef4ff; color: #1d4ed8; }
|
||||||
|
.pj-meet-sync.is-running .material-symbols-outlined { animation: pj-meet-spin 1s linear infinite; }
|
||||||
|
.pj-meet-sync.is-done { background: #eefaf2; color: #1f7a44; }
|
||||||
|
.pj-meet-sync.is-warn { background: #fff4ec; color: #b45309; }
|
||||||
|
@keyframes pj-meet-spin { to { transform: rotate(360deg); } }
|
||||||
|
@media print { .pj-meet-sync { display: none !important; } }
|
||||||
|
/* 숫자 — 한 줄 막대(칸 9개, 좁으면 두 줄). 설명 문구는 말풍선(title) */
|
||||||
|
.pj-meet-kpibar {
|
||||||
|
display: grid; grid-template-columns: repeat(9, minmax(0, 1fr)); margin-bottom: 10px;
|
||||||
|
border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; overflow: hidden;
|
||||||
|
}
|
||||||
|
.pj-meet-kpis { display: contents; }
|
||||||
|
.pj-meet-kpi { display: flex; flex-direction: column; gap: 1px; padding: 6px 10px; min-width: 0; border-right: 1px solid var(--pj-border); }
|
||||||
|
.pj-meet-kpis.is-week .pj-meet-kpi:last-child { border-right: none; }
|
||||||
|
.pj-meet-kpis:not(.is-week) .pj-meet-kpi:last-child { border-right: 2px solid #d5d9de; } /* 월 | 주 경계 */
|
||||||
|
.pj-meet-kpi.is-accent { background: #faf9ff; }
|
||||||
|
.pj-meet-kpi.is-input { background: #fffaf4; }
|
||||||
|
.pj-meet-kpi-label { font-size: 11px; color: var(--pj-ink-soft); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.pj-meet-kpi-label small { font-weight: 500; }
|
||||||
|
.pj-meet-kpi-val { font-size: 15px; font-weight: 800; font-variant-numeric: tabular-nums; display: flex; align-items: baseline; gap: 2px; white-space: nowrap; }
|
||||||
|
.pj-meet-kpi-val small { font-size: 10.5px; font-weight: 600; color: var(--pj-ink-soft); }
|
||||||
|
.pj-meet-kpi-val.is-good { color: #1f8a4c; }
|
||||||
|
.pj-meet-kpi-val.is-low { color: #c2410c; }
|
||||||
|
.pj-meet-kpi-sub { font-size: 10.5px; color: var(--pj-ink-soft); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.pj-meet-kpi .pj-meet-amount {
|
||||||
|
font-size: 14px; font-weight: 800; height: 24px; width: 100%; text-align: left;
|
||||||
|
border: 1px solid #f3d2b0; border-radius: 6px; background: #fff; padding: 0 6px;
|
||||||
|
}
|
||||||
|
@media (max-width: 1300px) { .pj-meet-kpibar { grid-template-columns: repeat(5, minmax(0, 1fr)); } }
|
||||||
|
|
||||||
|
/* 이 달 계획 — 연간 목표 표의 그 달 열(업무 영역별 작은 카드) */
|
||||||
|
.pj-meet-plan { margin: 0 0 10px; padding: 8px 10px; border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; }
|
||||||
|
.pj-meet-plan-head { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 800; margin-bottom: 6px; }
|
||||||
|
.pj-meet-plan-head .material-symbols-outlined { font-size: 18px; color: var(--pj-accent); }
|
||||||
|
.pj-meet-plan-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 6px; }
|
||||||
|
.pj-meet-plan-area { padding: 6px 8px; border-radius: 8px; background: var(--goal-bg, #f4f5f7); font-size: 12px; line-height: 1.45; min-width: 0; }
|
||||||
|
.pj-meet-plan-name { display: block; font-size: 12px; margin-bottom: 2px; }
|
||||||
|
.pj-meet-plan-item { display: flex; gap: 6px; align-items: baseline; }
|
||||||
|
.pj-meet-plan-item + .pj-meet-plan-item { margin-top: 2px; }
|
||||||
|
.pj-meet-plan-label { flex: none; font-weight: 700; color: #3b4048; }
|
||||||
|
.pj-meet-plan-label::after { content: ":"; }
|
||||||
|
.pj-meet-plan-text { white-space: pre-line; overflow-wrap: anywhere; }
|
||||||
|
.pj-meet-plan-item em { flex: none; margin-left: auto; font-style: normal; font-size: 10.5px; color: var(--pj-ink-soft); }
|
||||||
|
.pj-meet-plan-empty { margin: 0; font-size: 12px; color: var(--pj-ink-soft); }
|
||||||
|
|
||||||
|
/* 참석자 — 멤버 칩 + [참석자] 고르기 창(body 에 붙음) */
|
||||||
|
.pj-meet-attend { display: flex; align-items: flex-start; gap: 8px; margin: 0 0 10px; font-size: 12.5px; }
|
||||||
|
.pj-meet-attend-label { font-weight: 600; color: var(--pj-ink-soft); line-height: 30px; flex: none; }
|
||||||
|
.pj-meet-attend-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-height: 30px; padding: 2px; border-radius: 8px; }
|
||||||
|
.pj-meet-chip {
|
||||||
|
display: inline-flex; align-items: center; gap: 5px; height: 28px; padding: 0 4px 0 3px; border: 1px solid var(--pj-border);
|
||||||
|
border-radius: 999px; background: #fff; color: var(--pj-ink); font-weight: 600;
|
||||||
|
}
|
||||||
|
.pj-meet-chip .pj-avatar { width: 22px; height: 22px; }
|
||||||
|
.pj-meet-chip-ini {
|
||||||
|
display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border-radius: 50%;
|
||||||
|
background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-size: 11px; font-weight: 800; flex: none;
|
||||||
|
}
|
||||||
|
.pj-meet-chip-x { width: 20px; height: 20px; border: none; border-radius: 50%; background: transparent; color: var(--pj-ink-soft); cursor: pointer; line-height: 1; }
|
||||||
|
.pj-meet-chip-x:hover { background: #fde8e8; color: #c22b10; }
|
||||||
|
.pj-meet-attend-add {
|
||||||
|
display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 0 10px 0 8px; border: 1px dashed #c2c6cc;
|
||||||
|
border-radius: 999px; background: transparent; color: var(--pj-ink-soft); font-size: 12.5px; font-weight: 600; cursor: pointer;
|
||||||
|
}
|
||||||
|
.pj-meet-attend-add .material-symbols-outlined { font-size: 17px; }
|
||||||
|
.pj-meet-attend-add:hover { border-color: var(--pj-accent); color: var(--pj-accent-dark); background: var(--pj-accent-tint); }
|
||||||
|
.pj-meet-attend-chips.is-saved { animation: pj-goal-saved 1s ease-out; }
|
||||||
|
.pj-meet-pick {
|
||||||
|
position: fixed; z-index: 1000; width: 280px; max-height: 360px; display: flex; flex-direction: column; gap: 6px; padding: 10px;
|
||||||
|
background: #fff; border: 1px solid var(--pj-border); border-radius: 12px; box-shadow: 0 10px 30px rgba(16, 24, 40, .18);
|
||||||
|
}
|
||||||
|
.pj-meet-pick-q { height: 32px; padding: 0 10px; border: 1px solid var(--pj-border); border-radius: 8px; font: inherit; font-size: 13px; }
|
||||||
|
.pj-meet-pick-acts { display: flex; gap: 6px; }
|
||||||
|
.pj-meet-pick-acts button { flex: 1; height: 26px; border: 1px solid var(--pj-border); border-radius: 7px; background: #fafafb; font-size: 12px; cursor: pointer; }
|
||||||
|
.pj-meet-pick-acts button:hover { background: var(--pj-accent-tint); border-color: #cfc6fb; }
|
||||||
|
.pj-meet-pick-list { overflow: auto; min-height: 0; }
|
||||||
|
.pj-meet-pick-row { display: flex; align-items: center; gap: 8px; padding: 6px 6px; border-radius: 8px; cursor: pointer; font-size: 13px; }
|
||||||
|
.pj-meet-pick-row:hover { background: #f4f5f7; }
|
||||||
|
.pj-meet-pick-row .pj-avatar { width: 24px; height: 24px; }
|
||||||
|
.pj-meet-pick-name { font-weight: 600; }
|
||||||
|
.pj-meet-pick-id { margin-left: auto; color: var(--pj-ink-soft); font-size: 11.5px; }
|
||||||
|
.pj-meet-pick-empty { margin: 10px 4px; color: var(--pj-ink-soft); font-size: 12.5px; }
|
||||||
|
|
||||||
|
.pj-meet-table {
|
||||||
|
width: 100%; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
|
||||||
|
background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; color: var(--pj-ink);
|
||||||
|
}
|
||||||
|
.pj-meet-table th, .pj-meet-table td {
|
||||||
|
box-sizing: border-box; border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top;
|
||||||
|
}
|
||||||
|
.pj-meet-table tr > :last-child { border-right: none; }
|
||||||
|
.pj-meet-table thead th {
|
||||||
|
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 8px; font-weight: 700;
|
||||||
|
text-align: center; vertical-align: middle; white-space: nowrap;
|
||||||
|
}
|
||||||
|
.pj-meet-table thead tr.pj-meet-group th { top: 0; height: 26px; font-size: 12px; }
|
||||||
|
.pj-meet-table thead tr:nth-child(2) th { top: 26px; }
|
||||||
|
.pj-meet-table thead th.is-this { background: #fff7ed; color: #9a4b0b; }
|
||||||
|
/* 이번주 ↔ 지난주 순서 바꾸기 버튼(표 왼쪽 위 빈 칸) */
|
||||||
|
.pj-meet-order-cell { vertical-align: middle; }
|
||||||
|
.pj-meet-order-btn {
|
||||||
|
display: inline-flex; align-items: center; gap: 3px; height: 22px; padding: 0 8px 0 5px; border: 1px solid var(--pj-border);
|
||||||
|
border-radius: 999px; background: #fff; color: var(--pj-ink-soft); font: inherit; font-size: 11.5px; font-weight: 600; cursor: pointer;
|
||||||
|
}
|
||||||
|
.pj-meet-order-btn .material-symbols-outlined { font-size: 16px; transition: transform .3s ease; }
|
||||||
|
.pj-meet-order-btn:hover { color: var(--pj-ink); border-color: #c9ced6; background: #f6f7f9; }
|
||||||
|
.pj-meet-order-btn[aria-pressed="true"] .material-symbols-outlined { transform: rotate(180deg); }
|
||||||
|
@media print { .pj-meet-order-btn { display: none; } }
|
||||||
|
.pj-meet-table thead th.is-prev { background: #f1f3f6; color: #4b5563; }
|
||||||
|
.pj-meet-w-sec { width: 80px; }
|
||||||
|
.pj-meet-w-label { width: 160px; }
|
||||||
|
.pj-meet-w-amt { width: 122px; }
|
||||||
|
.pj-meet-w-rate { width: 76px; }
|
||||||
|
.pj-meet-w-eval { width: 88px; }
|
||||||
|
.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); }
|
||||||
|
.pj-meet-sec > tr > td.is-prev { background: #fafbfc; }
|
||||||
|
.pj-meet-sec > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
||||||
|
.pj-meet-sec th { padding: 7px 8px; vertical-align: middle; text-align: center; }
|
||||||
|
th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; }
|
||||||
|
.pj-meet-sec-add {
|
||||||
|
display: block; margin: 4px auto 0; width: 22px; height: 22px; border: 1px dashed rgba(0, 0, 0, .25); border-radius: 6px;
|
||||||
|
background: rgba(255, 255, 255, .6); color: var(--pj-ink-soft); cursor: pointer; line-height: 18px; opacity: 0; transition: opacity .12s;
|
||||||
|
}
|
||||||
|
th.pj-meet-c-sec:hover .pj-meet-sec-add, .pj-meet-sec-add:focus { opacity: 1; }
|
||||||
|
th.pj-meet-c-label { position: relative; font-weight: 600; color: #3b4048; text-align: left; }
|
||||||
|
.pj-meet-label { word-break: keep-all; overflow-wrap: anywhere; }
|
||||||
|
.pj-meet-label[data-meet-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; }
|
||||||
|
.pj-meet-label[data-meet-edit]:hover { background: rgba(255, 255, 255, .65); box-shadow: 0 0 0 1px rgba(0, 0, 0, .14); }
|
||||||
|
.pj-meet-label.is-editing { background: #fff; box-shadow: 0 0 0 2px var(--pj-accent); outline: none; }
|
||||||
|
.pj-meet-label[data-meet-edit]:empty { display: inline-block; min-width: 3em; min-height: 1.4em; }
|
||||||
|
.pj-meet-market {
|
||||||
|
display: inline-block; margin-left: 4px; padding: 0 6px; border-radius: 999px; font-size: 10.5px; font-weight: 700;
|
||||||
|
background: #e8f1ff; color: #1d4ed8; vertical-align: 1px;
|
||||||
|
}
|
||||||
|
.pj-meet-more { position: absolute; top: 3px; right: 2px; width: 24px; height: 24px; opacity: 0; transition: opacity .12s; }
|
||||||
|
.pj-meet-more .material-symbols-outlined { font-size: 18px; }
|
||||||
|
th.pj-meet-c-label:hover .pj-meet-more, .pj-meet-more:focus { opacity: 1; }
|
||||||
|
textarea.pj-meet-text, .pj-meet-notes textarea {
|
||||||
|
display: block; width: 100%; box-sizing: border-box; min-height: 38px; padding: 6px; border: none; background: transparent;
|
||||||
|
font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
|
||||||
|
}
|
||||||
|
textarea.pj-meet-text:focus { outline: none; }
|
||||||
|
.pj-meet-notes textarea:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .8); }
|
||||||
|
/* 입력 중인 칸 — 칸 전체(td) 테두리 */
|
||||||
|
.pj-meet-table td:focus-within:not(.pj-meet-c-eval) {
|
||||||
|
box-shadow: inset 0 0 0 2px var(--pj-accent);
|
||||||
|
background-image: linear-gradient(rgba(255, 255, 255, .8), rgba(255, 255, 255, .8));
|
||||||
|
}
|
||||||
|
.pj-meet-ro { min-height: 38px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
.pj-meet-table td.pj-meet-c-amt { text-align: right; vertical-align: middle; padding: 0 6px; font-variant-numeric: tabular-nums; }
|
||||||
|
input.pj-meet-amount {
|
||||||
|
display: block; width: 100%; box-sizing: border-box; height: 34px; padding: 0 4px; border: none; background: transparent;
|
||||||
|
font: inherit; text-align: right; font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
input.pj-meet-amount:focus { outline: none; background: transparent; }
|
||||||
|
.pj-meet-kpi input.pj-meet-amount:focus { outline: 2px solid var(--pj-accent); outline-offset: -1px; }
|
||||||
|
input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
|
||||||
|
.pj-meet-auto { color: #1d4ed8; font-weight: 600; }
|
||||||
|
.pj-meet-market.is-off { background: #fdecec; color: #b42318; }
|
||||||
|
.pj-meet-week-auto { display: block; padding: 0 4px 5px; font-size: 11px; color: #1d4ed8; text-align: right; white-space: nowrap; }
|
||||||
|
.pj-meet-auto::before { content: "자동 "; font-size: 10.5px; font-weight: 700; color: #6b8fd6; }
|
||||||
|
.pj-meet-c-rate { text-align: right; vertical-align: middle !important; padding: 0 6px !important; font-weight: 700; }
|
||||||
|
.pj-meet-c-rate .is-good { color: #1f8a4c; }
|
||||||
|
.pj-meet-c-rate .is-low { color: #c2410c; }
|
||||||
|
.pj-meet-c-eval { vertical-align: middle !important; text-align: center; }
|
||||||
|
select.pj-meet-eval { width: calc(100% - 8px); height: 28px; margin: 0 4px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font: inherit; }
|
||||||
|
select.pj-meet-eval[data-v="done"], .pj-meet-eval-ro[data-v="done"] { color: #1f8a4c; font-weight: 700; }
|
||||||
|
select.pj-meet-eval[data-v="partial"], .pj-meet-eval-ro[data-v="partial"] { color: #b45309; font-weight: 700; }
|
||||||
|
select.pj-meet-eval[data-v="miss"], .pj-meet-eval-ro[data-v="miss"] { color: #c22b10; font-weight: 700; }
|
||||||
|
.pj-meet-table td.is-none { vertical-align: middle; padding: 0 8px; font-size: 12px; }
|
||||||
|
.pj-meet-table td.is-saved, .pj-meet-table th.is-saved, .pj-meet-notes textarea.is-saved, #pj-meet-attendees.is-saved {
|
||||||
|
animation: pj-goal-saved 1s ease-out;
|
||||||
|
}
|
||||||
|
.pj-meet-notes { margin: 16px 0 8px; }
|
||||||
|
.pj-meet-notes h3 { margin: 0 0 6px; font-size: 14px; }
|
||||||
|
.pj-meet-notes textarea, .pj-meet-notes .pj-meet-ro { border: 1px solid #dfe2e6; border-radius: 10px; background: #fff; min-height: 90px; padding: 10px; }
|
||||||
|
|
||||||
|
/* 인쇄 — 회의록 표만 */
|
||||||
|
@media print {
|
||||||
|
.erp-sidebar, .erp-topbar, .pj-side, .pj-goal-head-acts, .pj-meet-weeks, .pj-goal-foot, .pj-meet-more, .pj-meet-sec-add,
|
||||||
|
.pj-meet-goalbtn, .pj-meet-title .pj-btn { display: none !important; }
|
||||||
|
.pj-meet-pane { overflow: visible; }
|
||||||
|
.pj-meet-table thead th { position: static; }
|
||||||
|
input.pj-meet-amount, select.pj-meet-eval { border: none; appearance: none; }
|
||||||
|
}
|
||||||
|
|
||||||
/* 영역 색 고르기 팝업(body 에 붙음) */
|
/* 영역 색 고르기 팝업(body 에 붙음) */
|
||||||
.pj-goal-colorpop {
|
.pj-goal-colorpop {
|
||||||
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
|
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
|
||||||
|
|||||||
+1736
-155
File diff suppressed because it is too large
Load Diff
@@ -29,7 +29,7 @@
|
|||||||
|
|
||||||
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
|
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
|
||||||
|
|
||||||
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑 = **구현됨**, 나머지 5개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
|
||||||
**연동 단계에서 공식 API 문서로 확정**한다.
|
**연동 단계에서 공식 API 문서로 확정**한다.
|
||||||
|
|
||||||
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
### 카페24 (`adapters/cafe24.py`, 구현됨)
|
||||||
@@ -147,6 +147,42 @@
|
|||||||
**GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`.
|
**GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`.
|
||||||
원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고).
|
원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고).
|
||||||
|
|
||||||
|
### 토스쇼핑 (`adapters/toss.py`, 구현됨)
|
||||||
|
|
||||||
|
- 문서: `https://shopping-docs.toss.im/dev` (공개, 전체 목록 `llms.txt`, 쪽 주소 뒤 `.md` = 원문). 문의는 문서의 디스코드.
|
||||||
|
- 인증: 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > **자체 개발** → [키 발급](**호출 IP 입력 — 운영 서버 외부 IP**, 등록된
|
||||||
|
IP 만 호출 가능) → Access Key·Secret Key. `POST https://oauth2.cert.toss.im/token`(form: `grant_type=client_credentials`·
|
||||||
|
`client_id`=Access Key·`client_secret`=Secret Key·`scope=toss-shopping-fep:write`). 토큰 `expires_in` 약 1년 — 문서가 매번 발급하면
|
||||||
|
이용이 제한될 수 있다고 해서 `access_token`·`access_token_expires_at`(internal, 암호화)으로 저장해 재사용, 만료 1시간 전·401 이면 새로.
|
||||||
|
[연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. 입력칸 키는 처음 만든 `api_key`(Access Key)·`api_secret`(Secret Key) 그대로
|
||||||
|
(라벨만 변경 — 예전 "판매자 ID" 칸은 없앰).
|
||||||
|
- API: `https://shopping-fep.toss.im`, `Authorization: Bearer {token}`. 오류가 **HTTP 200 + `resultType: "FAIL"`**(`error.errorCode`·
|
||||||
|
`reason`)로도 온다. 읽기 초당 50회(넘으면 `TOO_MANY_REQUEST`) → 호출 간격 0.1초, 제한이면 1·2·4초 쉬고 다시.
|
||||||
|
- 수집: 주문 내역 조회 `GET /api/v3/shopping-fep/orders/v2?startDate&endDate&limit=50&nextCursor` — 한 번에 **31일**, 상태 생략 =
|
||||||
|
전체, 커서(`nextCursor` null = 끝). 줄 = 주문상품(`orderProductId`), 주문 = `orderId`. 금액 항목: `price`(판매가 × 수량)·
|
||||||
|
`originPrice`(정상가 × 수량)·`totalDiscountPrice`(= `tossShoppingDiscount` + `tossPayDiscount`)·`tossPayPoint`·`deliveryFee`
|
||||||
|
(묶음 `deliveryFeeGroupId` 마다). 결제일 필드는 따로 없고 `orderedAt`(주문 = 결제) · `canceledAt` · `confirmedAt`.
|
||||||
|
- **매출 규칙 = 파트너스 "순 거래액" = 매출 − 환불**(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 순 거래액 17,700).
|
||||||
|
- 매출 SALE = 주문 하나(`toss:{orderId}`), 날짜 = `orderedAt` 의 한국 날짜, 금액 = `price` 합(할인 전, 배송비 제외), 할인은
|
||||||
|
`discount_amount` 로만. 결제 전(`BEFORE_PAYMENT`)만 빼고 나중에 취소·반품된 주문도 주문일 매출에 둔다(화면 "매출"도 환불 전).
|
||||||
|
- 환불 = **환불일**에 뺀다, 주문상품마다 한 번(사건 ID `toss:R{orderProductId}`), `merge_refunds`:
|
||||||
|
① 클레임 목록 `GET /api/v3/shopping-fep/claims?size=100&nextToken`(유형·상태 조건 없음 = 전체 — 이 API 는 그 밖엔 날짜로 못 거른다,
|
||||||
|
최대 1만 건)의 **환불 완료**(`isRefunded`) `CANCEL`·`RETURN` — 날짜 = `refundedDt`. 반품은 이것뿐(주문 내역엔 반품 완료 날짜 없음).
|
||||||
|
사건 종류 CANCEL / RETURN.
|
||||||
|
② 클레임이 **없는** 결제취소(`CANCELED_PAYMENT`) — 날짜 = 주문 내역 `canceledAt`(결제완료 단계 고객 취소는 클레임이 안 생김).
|
||||||
|
클레임이 있는 주문상품은 클레임 날짜만 쓴다(그 날짜가 기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 흔들리지 않게).
|
||||||
|
금액 = 그 주문상품의 `price`(판매가 × 수량 — 매출과 같은 기준), 주문 내역에 없으면 클레임 `order.price`. 다른 날 주문의 환불을 잡으려고
|
||||||
|
수집 때 **기간 앞 90일**(`CANCEL_LOOKBACK_DAYS`) 주문 내역도 부른다. 교환·미환불 클레임은 제외.
|
||||||
|
- 수집은 `collect` 를 직접 구현(주문 내역을 매출·환불 금액·취소 시각에 함께 쓰려고). 진행 막대 = 기간 주문 구간 + 앞 90일 구간 + 클레임 1.
|
||||||
|
`replace_range`(접두어 `toss:` — 매출·환불 함께 교체). 개인정보(주문자·수령인·주소·요청사항·수거 주소·요청 사유·송장)는 저장 안 함.
|
||||||
|
- **실데이터 대조(2026-10-01, 9/6)**: 매출 29,600 = 주문 2건 `price` 합 **일치**(`orderedAt` 은 시간대 없이 한국 시간 — 17:57 주문도 9/6).
|
||||||
|
환불 11,900 = 9/5 주문(276435356)을 9/6 취소 — 클레임 `CANCEL/COMPLETED` `refundedDt` 9/6 과 `canceledAt` 9/6 **둘 다 일치**,
|
||||||
|
정산 건별 REFUND 에는 **없다**(9/6 거래일 정산 = PAY 2줄 + 배송비 2줄뿐 — 구매확정 전 취소는 정산에 안 올라옴) → 정산은 환불에 쓰지 않는다.
|
||||||
|
- 원본 데이터 확인(토스쇼핑): 날짜별 **매출(주문일)·환불(환불일)·순 거래액**(`day_cols`, = 저장되는 값) + **환불 출처별 비교**
|
||||||
|
(`refund_candidates`: 적용 규칙 · 클레임 환불 완료 · 주문 취소 시각 · 정산 REFUND(참고), 날짜별 합계 + 건별 주문번호·금액·메모)
|
||||||
|
+ 주문 상태별·클레임·정산 항목 합계. 화면 숫자와 다르면 출처별 열로 어느 쪽이 빠졌는지 본다.
|
||||||
|
- 정산 줄의 다른 항목: 셀러 부담 쿠폰 `shoppingDiscountMerchant`, 정산 지급액 `settlementAmount`, 수수료 `payFee`·`productFee`.
|
||||||
|
|
||||||
### 연동 단계 체크리스트(쇼핑몰마다)
|
### 연동 단계 체크리스트(쇼핑몰마다)
|
||||||
|
|
||||||
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
|
||||||
@@ -198,9 +234,11 @@
|
|||||||
| 기능 | 권한 |
|
| 기능 | 권한 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
|
| 대시보드 · 매출 업데이트 · 금액 상세 | `performance` (admin 자동) |
|
||||||
| 설정 화면 · 수수료 · 인증정보 · 연결 테스트 · 테스트 데이터 · 재암호화 | `is_admin` |
|
| 설정 화면 진입 · **수수료율 조회·변경·이력 삭제**(`/api/marketplaces/{code}/rates`) | `performance` (2026-10-01부터 일반 사용자도) |
|
||||||
|
| 사용·매출 집계 토글 · 인증정보 · 연결 테스트 · 원본 데이터 확인·대조 · 과거 매출 가져오기(92일 초과) · 테스트 데이터 · 재암호화 | `is_admin` |
|
||||||
|
|
||||||
화면에서 설정 탭을 숨기는 것과 별개로 모든 설정 API 가 `common.require_store(admin=True)` 로 403 을 낸다.
|
일반 사용자의 설정 화면(탭 이름 "수수료 설정")은 쇼핑몰 표에 쇼핑몰·수수료율·마지막 동기화만, 다른 칸·카드는 템플릿이 관리자에게만
|
||||||
|
그린다. 화면과 별개로 수수료 API 를 뺀 설정 API 는 모두 `common.require_store(admin=True)` 로 403 을 낸다.
|
||||||
|
|
||||||
## 6. 동기화 (`sync.py`)
|
## 6. 동기화 (`sync.py`)
|
||||||
|
|
||||||
@@ -220,6 +258,10 @@
|
|||||||
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
|
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
|
||||||
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
|
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
|
||||||
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
|
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
|
||||||
|
- **쇼핑몰별 [중지]**(진행 창 쇼핑몰 이름 옆, 대기·수집 중일 때만, 시작한 사람·관리자,
|
||||||
|
`POST /api/sync/jobs/{id}/shops/{code}/stop`): 그 쇼핑몰만 위와 같은 방식으로 멈추고(저장 안 함, 기존 매출 그대로) **다음 쇼핑몰로
|
||||||
|
넘어간다**. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. `ShopProgress.stop_requested` → `cancel_requested`/`check()`,
|
||||||
|
상태 "중지됨"(`stopped_only`), `perf_sync_runs` 는 failed + "쇼핑몰 중지". 저장 중·끝난 쇼핑몰은 409.
|
||||||
- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
|
- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
|
||||||
+ 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
|
+ 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
|
||||||
9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
|
9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
|
||||||
|
|||||||
+274
-6
@@ -66,6 +66,12 @@
|
|||||||
펼친 하위 작업 한 줄을 다른 카드로 드래그하면 그 작업의 하위 작업으로 옮겨진다
|
펼친 하위 작업 한 줄을 다른 카드로 드래그하면 그 작업의 하위 작업으로 옮겨진다
|
||||||
(`POST /api/tasks/{id}/move-parent` `{parent_task_id}` → `db.move_subtask`, 활동 `subtask_moved`).
|
(`POST /api/tasks/{id}/move-parent` `{parent_task_id}` → `db.move_subtask`, 활동 `subtask_moved`).
|
||||||
받는 쪽은 **같은 프로젝트의 최상위 작업만**(순환 방지), 하위 작업의 하위 작업은 함께 따라간다.
|
받는 쪽은 **같은 프로젝트의 최상위 작업만**(순환 방지), 하위 작업의 하위 작업은 함께 따라간다.
|
||||||
|
**카드 크기·표지**(2026-10-02): 카드 높이 100px 고정(`.pj-card-head` height 86px = 100 − 아래 여백 12 − 테두리 2, 제목 2줄·
|
||||||
|
프로젝트 배지가 있으면 1줄까지, 담당자·날짜 줄은 맨 아래), 담당자 13.2px·아바타 20px·날짜 12.1px(기존 +10%).
|
||||||
|
설명에 이미지가 있으면 **첫 이미지를 카드 위 표지**로(아사나, `cardCoverSrc` — template 로 읽어 이미지를 불러오지 않음,
|
||||||
|
우리 첨부·http(s)·data:image 만, 높이 140px object-fit cover). 표지·펼친 하위 작업은 100px 위·아래에 더해진다.
|
||||||
|
**하위 작업이 없는 카드**도 같은 모양의 빈 토글(⤷ ▾, `.pj-card-subtoggle.is-empty` — 카드에 마우스를 올리면 보임, 편집 권한자만)이
|
||||||
|
있어 누르면 카드 아래가 펼쳐지며 곧바로 새 하위 작업 이름 입력 줄이 열린다(빈 목록엔 "하위 작업 없음" 대신 추가 줄).
|
||||||
펼친 하위 작업 목록 맨 아래 **"+ 하위 작업 추가"**(아사나, `renderSubAdd`) — 누르면 그 자리에 새 줄
|
펼친 하위 작업 목록 맨 아래 **"+ 하위 작업 추가"**(아사나, `renderSubAdd`) — 누르면 그 자리에 새 줄
|
||||||
(✓ · "작업 이름 입력" · 점선 달력 · 점선 사람)이 열려 Enter 로 바로 만들고, 줄은 열린 채 다음 입력으로.
|
(✓ · "작업 이름 입력" · 점선 달력 · 점선 사람)이 열려 Enter 로 바로 만들고, 줄은 열린 채 다음 입력으로.
|
||||||
이름을 쓴 채 다른 곳을 누르면 Enter 와 같이 만들고 줄은 닫힘(`onOutsideDown` — 문서 pointerdown, 한글 조합 중인
|
이름을 쓴 채 다른 곳을 누르면 Enter 와 같이 만들고 줄은 닫힘(`onOutsideDown` — 문서 pointerdown, 한글 조합 중인
|
||||||
@@ -293,6 +299,17 @@ docker exec -i postgres-db psql -U postgres -d project_db \
|
|||||||
< scripts/sql/project_db_012_comment_replies_reactions.sql
|
< scripts/sql/project_db_012_comment_replies_reactions.sql
|
||||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
< scripts/sql/project_db_013_goals.sql
|
< scripts/sql/project_db_013_goals.sql
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
< scripts/sql/project_db_014_goal_halves_merges.sql
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
< scripts/sql/project_db_015_goal_rect_merges_meetings.sql
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
< scripts/sql/project_db_016_goal_row_label_groups.sql
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
< scripts/sql/project_db_017_goal_quarters.sql
|
||||||
|
# 018 = 주간 회의록 줄 연결키(line_key) — 적용 전 백업, 적용·확인 방법은 6-9-3
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
< scripts/sql/project_db_018_meeting_line_keys.sql
|
||||||
|
|
||||||
# 4) 재배포 (git pull 후 반드시 --build)
|
# 4) 재배포 (git pull 후 반드시 --build)
|
||||||
cd /opt/www/main && docker compose up -d --build web
|
cd /opt/www/main && docker compose up -d --build web
|
||||||
@@ -347,6 +364,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
|||||||
(`.pj-modal-actions-top`) — 카드가 flex column 이고 `.pj-modal-body` 만 스크롤하므로 sticky 없이 고정된다(sticky 는 카드 padding 안쪽에 붙어 바가 밀려 내려오고 제목을 덮었다). 저장 버튼은 없다 — 실시간 저장(§6-6).
|
(`.pj-modal-actions-top`) — 카드가 flex column 이고 `.pj-modal-body` 만 스크롤하므로 sticky 없이 고정된다(sticky 는 카드 padding 안쪽에 붙어 바가 밀려 내려오고 제목을 덮었다). 저장 버튼은 없다 — 실시간 저장(§6-6).
|
||||||
댓글 입력칸은 아사나처럼 **창 맨 아래 고정**(`#pj-comment-dock`) — `.pj-modal-body` 바깥 형제라서
|
댓글 입력칸은 아사나처럼 **창 맨 아래 고정**(`#pj-comment-dock`) — `.pj-modal-body` 바깥 형제라서
|
||||||
끝까지 스크롤해도 마지막 내용이 입력칸 위에서 멈춘다(sticky 아님). 새 작업(id 없음)이면 숨긴다.
|
끝까지 스크롤해도 마지막 내용이 입력칸 위에서 멈춘다(sticky 아님). 새 작업(id 없음)이면 숨긴다.
|
||||||
|
댓글·댓글 대화창(`#pj-cm-input`)·답글 입력칸은 여러 줄 입력칸(`textarea.pj-composer-ta`) — **Enter = 등록, Shift+Enter = 줄바꿈**,
|
||||||
|
글 줄 수만큼 높이가 늘어난다(`fitComposer`, 최대 160px). 댓글 본문은 `white-space: pre-wrap` 이라 줄바꿈이 그대로 보인다.
|
||||||
|
**설명란 이미지 더블클릭 → 별도 브라우저 창**(`openImageWindow`, 페이지 안 팝업 아님) — 창 크기 = 원본 크기(화면보다 크면 95%),
|
||||||
|
처음 원본 100%(창보다 크면 맞춤), 휠 = 커서 기준 확대·축소, 끌기 = 이동, 아래 막대 − / % / + · 1:1 · 맞춤, 더블클릭 = 원본↔맞춤,
|
||||||
|
키 + − 0 1 Esc. 팝업이 막히면 허용 안내 토스트.
|
||||||
그 아래 메타(담당자·섹션·우선순위·마감일 한 줄 — 마감일은 캘린더 아이콘 버튼, 좁으면 2×2 | 협업자), 다시 그 아래 **설명란**과
|
그 아래 메타(담당자·섹션·우선순위·마감일 한 줄 — 마감일은 캘린더 아이콘 버튼, 좁으면 2×2 | 협업자), 다시 그 아래 **설명란**과
|
||||||
**하위 작업**가 각각 팝업 너비 전체를 쓰는 별도 행(`.pj-desc-block` / `.pj-subtask-full`,
|
**하위 작업**가 각각 팝업 너비 전체를 쓰는 별도 행(`.pj-desc-block` / `.pj-subtask-full`,
|
||||||
그리드 `1 / -1`). 하위 작업은 제목 왼쪽 체크박스로 완료를 토글하고, 완료된 줄은
|
그리드 `1 / -1`). 하위 작업은 제목 왼쪽 체크박스로 완료를 토글하고, 완료된 줄은
|
||||||
@@ -478,6 +500,8 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
|||||||
프로젝트 화면을 `?task={id}&embed=1` 로 iframe 에 열고, `html.pj-embed` 가 작업 창 외에는 숨긴다.
|
프로젝트 화면을 `?task={id}&embed=1` 로 iframe 에 열고, `html.pj-embed` 가 작업 창 외에는 숨긴다.
|
||||||
작업 창을 닫으면 iframe 이 `postMessage({type:"pj-embed-close"})` → 패널 닫힘.
|
작업 창을 닫으면 iframe 이 `postMessage({type:"pj-embed-close"})` → 패널 닫힘.
|
||||||
embed 에서만 작업 창 맨 위에 "프로젝트로 이동"(`#pj-goto-project`) — `window.top` 을 그 프로젝트 화면(`?task=`)으로. Ctrl+클릭은 새 탭(예전처럼 이동).
|
embed 에서만 작업 창 맨 위에 "프로젝트로 이동"(`#pj-goto-project`) — `window.top` 을 그 프로젝트 화면(`?task=`)으로. Ctrl+클릭은 새 탭(예전처럼 이동).
|
||||||
|
- **위쪽 여백 줄임**(2026-10-01): 프로젝트 관리 모든 화면(`.erp-page` 안이 `.pj-wrap`·`.pjh` 일 때만, `:has`)은 공통 본문 위 여백
|
||||||
|
24px → 6px, 화면 위 여백·제목 줄 위 여백 0 — 상단 바와 제목 사이 36px → 6px. 다른 모듈은 그대로.
|
||||||
- 화면 배율 토글(상단 바 `fit_screen`, `_help_btn.html`) — `html.pj-ui-scale` 이면 `.erp-app` 에 `zoom: .75`
|
- 화면 배율 토글(상단 바 `fit_screen`, `_help_btn.html`) — `html.pj-ui-scale` 이면 `.erp-app` 에 `zoom: .75`
|
||||||
(2880×1620·200% = CSS 폭 1440px 에서 1920 기준 화면처럼). zoom 안에서 줄어드는 `vh` 높이는 배율로 나눠
|
(2880×1620·200% = CSS 폭 1440px 에서 1920 기준 화면처럼). zoom 안에서 줄어드는 `vh` 높이는 배율로 나눠
|
||||||
되돌린다. 팝업은 전부 `body` 에 붙어 배율 밖이라 좌표 보정 불필요(전체 검색 결과창도 body 로 옮김),
|
되돌린다. 팝업은 전부 `body` 에 붙어 배율 밖이라 좌표 보정 불필요(전체 검색 결과창도 body 로 옮김),
|
||||||
@@ -489,9 +513,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
|||||||
(`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav`
|
(`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav`
|
||||||
(`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`.
|
(`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`.
|
||||||
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
|
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
|
||||||
이번 달 열 강조. 월 칸 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`), 머리·왼쪽 이름 가운데 정렬(왼쪽 이름은 세로도 가운데 — 관리자 도구는 칸 아래에 떠 있는 막대라 자리를 차지하지 않음). 왼쪽 이름 두 칸(구분·항목)은 머리 칸 오른쪽 끝을 끌어 너비 조절(48~320px, 더블클릭 = 72px) — 브라우저별 localStorage `pj_goal_col_w`, CSS 변수 `--goal-c1-w`·`--goal-c2-w`.
|
이번 달 열 강조. **가로 스크롤 때 3열(구분·항목·연간)까지 고정** — 연간 열 `position: sticky; left: 1열+2열 너비`, 경계 그림자. 월 칸 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`), 머리·왼쪽 이름 가운데 정렬(왼쪽 이름은 세로도 가운데 — 관리자 도구는 칸 아래에 떠 있는 막대라 자리를 차지하지 않음). **모든 열**(구분·항목·연간·1~12월·상/하반기)은 머리 칸 오른쪽 끝을 끌어 너비 조절(더블클릭 = 기본 너비) — 브라우저별 localStorage `pj_goal_col_w`(키 `c1`·`c2`·`y`·`m1`~`m12`·`h1`·`h2`, 기본값과 다른 칸만 저장). 이름 두 칸은 48~320px·CSS 변수 `--goal-c1-w`·`--goal-c2-w`, 나머지는 40~600px·머리 칸의 `--cw`(table-layout: fixed 라 머리 칸 너비가 열 너비). 반기 접기 애니메이션의 월 칸 안쪽 고정 폭은 `--fold-w`(병합 칸 = 걸친 월 너비 합)로 JS 가 넣는다.
|
||||||
|
- **틀 고정** — 세로 스크롤에도 머리 줄 + 숫자 지표(매출·로아스) 줄까지 위에 붙어 있다. 지표 칸 `position: sticky` + 줄마다 `--kpi-top`(머리 줄 높이 + 앞 지표 줄 높이 합, `stickKpi`, 창 크기 바뀌면 다시 잼). z-index: 영역 이름 칸 2(마우스 올림 6) < 지표 칸 7 < 지표 이름 칸 8 < 머리 줄 9 < 머리 이름 칸 10.
|
||||||
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
|
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
|
||||||
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, 연간은 실적이 있는 달의 목표 합계 대비)는
|
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, **연간·반기는 그 기간 목표 합계 전체 대비 입력된
|
||||||
|
실적 합계** — 2026-10-01 사용자 기준, 예전엔 실적이 있는 달의 목표만)는
|
||||||
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
|
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
|
||||||
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
||||||
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
|
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
|
||||||
@@ -501,14 +527,256 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
|||||||
관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제).
|
관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제).
|
||||||
- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
|
- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
|
||||||
`{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` ·
|
`{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` ·
|
||||||
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` ·
|
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` `{label, ref_row_id?, place?: above|below}`(기준 줄 위/아래, 없으면 맨 끝) ·
|
||||||
`PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`.
|
`PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`.
|
||||||
013 미적용 503, 없는 대상 404, 입력 오류 400(`_goal_call`).
|
013 미적용 503, 없는 대상 404, 입력 오류 400(`_goal_call`).
|
||||||
- 화면 동작(`initGoals`): 숫자 칸은 Enter/칸 떠남에 저장(Esc 취소), 글 칸은 0.8초 멈춤·칸 떠남·페이지 떠남(keepalive)에 저장,
|
- 화면 동작(`initGoals`): 숫자 칸은 Enter/칸 떠남에 저장(Esc = 저장된 값으로), 글 칸은 0.8초 멈춤·칸 떠남에 저장,
|
||||||
저장되면 칸 테두리가 잠깐 초록. 영역/줄 추가·이름·순서·삭제는 저장 뒤 새로고침(스크롤 위치 sessionStorage 로 되살림),
|
저장되면 칸 테두리가 잠깐 초록, 실패하면 빨간 테두리(입력값 유지). 저장은 공용 `createFieldSaver`(6-9-3 — 같은 칸 요청 직렬화,
|
||||||
영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
|
보낸 값만 저장됨으로, 실패 시 초안 유지·localStorage 초안 백업, 페이지 떠남 보호). 영역/줄 추가·순서·삭제·병합은 먼저 저장 안 된
|
||||||
|
글을 저장하고(실패하면 작업 중단) 그 자리에서 다시 그림(`refreshTable`), 영역 색은 팝업(body 에 붙임)에서 바로 바뀜.
|
||||||
|
목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
|
||||||
- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기.
|
- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기.
|
||||||
|
|
||||||
|
### 6-9-0. 1~4분기 칸 (마이그레이션 017, 2026-10-01 — 상·하반기 대신)
|
||||||
|
|
||||||
|
- **열 순서** — 연간 · 1~3월 · **1분기** · 4~6월 · **2분기** · 7~9월 · **3분기** · 10~12월 · **4분기**
|
||||||
|
(`store.GOAL_COL_ORDER = (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)`). 템플릿 컨텍스트 `quarters`
|
||||||
|
(`(분기, 월 목록, 글 칸 번호, "N분기")`), 월 칸 `data-h` = 분기 1~4, 분기 칸 클래스는 예전 이름 `pj-goal-half-col` 그대로.
|
||||||
|
- **분기 글 칸 번호**(`store.GOAL_QUARTER_COL`) = 1분기 13 · 2분기 15 · 3분기 14 · 4분기 16 — 예전 반기 칸 번호를 그대로 이어 써서
|
||||||
|
글을 옮기지 않는다(예전 상반기 글 → 1분기, 하반기 글 → 3분기에 보임). 15·16 은 017 이 `goal_cells` CHECK 를 0~16 으로 넓힌 뒤에만
|
||||||
|
저장(미적용이면 읽기 전용 칸 + API 503 `GoalMigration017Needed`, 적용 여부 = `db._goal_quarters` → `board.quarters`).
|
||||||
|
- **병합** — 가로는 **같은 분기 월 칸끼리만**, 연간·분기 칸은 세로로만(`goal_col_group`: year · q1~q4 · months1~4).
|
||||||
|
017 은 분기를 넘던 예전 반기 병합(예: 2~4월)을 그 분기 끝 월까지로 줄이고(글은 시작 칸 그대로), 한 칸짜리가 된 병합 행은 지운다.
|
||||||
|
화면(`_goal_area_layout`)도 분기를 넘는 병합은 잘라 그린다(017 전에도 안전).
|
||||||
|
- **숫자 지표** — 분기 칸 = 그 분기 월 합계, 달성률 = 분기 실적 합계 ÷ 분기 목표 합계(`SUM_SCOPES` 연간 + 4분기),
|
||||||
|
로아스 분기 = 매출 가중 평균(연간과 같은 규칙).
|
||||||
|
- **업무 영역 추가 · 줄 추가는 묻지 않고 바로**(2026-10-02) — 영역은 "새 업무 영역", 줄은 빈 이름으로 만들고 표를 다시 그린 뒤
|
||||||
|
그 이름 칸을 바로 입력 상태로(`editNewName` → `startNameEdit`, Enter 저장 · Esc 그대로).
|
||||||
|
- **분기 접기** — 분기 **머리 칸 아무 곳이나** 누르면(`.pj-goal-fold-th`, 너비 조절 손잡이를 끈 직후 0.3초 클릭은 무시) 그 분기 월 칸을
|
||||||
|
접었다 편다. 아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘) — 바뀔 때 90° 돌며 세로 막대가 자라거나 줄어든다.
|
||||||
|
- **분기 색(monday.com 그룹 색 띠 방식)** — 분기마다 차분한 색 하나(1 파랑 · 2 청록 · 3 보라 · 4 남색, 달성률 빨강·초록과 안 겹치게).
|
||||||
|
`data-h` 가 있는 칸에 `--qc`·`--qt`·`--qt2`. 머리 위 색 띠 = 월 칸 3px · 분기 칸 6px(`th::before`, 월 링크가 덮어도 보임),
|
||||||
|
분기 열 전체 옅은 음영(`td.pj-goal-half-col[data-h]` background-image — 영역 색 위에도), 분기 칸 오른쪽 2px 경계,
|
||||||
|
분기 머리 글자·아이콘은 분기 색, 접힌 분기 머리는 진한 음영.
|
||||||
|
열 너비 키는 `q1`~`q4`(기본 80px).
|
||||||
|
- 아래 6-9-1 의 상·하반기 설명은 014 당시 기록 — 칸 번호·접기·병합 규칙은 이 절이 우선.
|
||||||
|
|
||||||
|
### 6-9-1. 상·하반기 칸 · 반기 접기 · 이름 바로 수정 · 월 칸 병합 · 로아스 % (마이그레이션 014) — 017 에서 분기로 바뀜(6-9-0)
|
||||||
|
|
||||||
|
- **열 순서** — 연간 · 1~6월 · **상반기** · 7~12월 · **하반기**. 템플릿 컨텍스트 `halves`
|
||||||
|
(`(반기, 월 목록, 글 칸 번호 13|14, 이름)`), 월 칸은 `pj-goal-m` + `data-h="1|2"`, 반기 칸은 `pj-goal-half-col`.
|
||||||
|
- 숫자 지표: 매출 목표·실적의 반기 칸 = 그 반기 월 합계(`data-scope="13|14"`, 연간은 `0`), 달성률은 연간과 같은 규칙
|
||||||
|
(그 반기 목표 합계 대비 실적, `SUM_SCOPES`). **로아스 연간·반기**(목표·실적) = 기간 매출 ÷ 기간 광고비 — 광고비를 따로 적지 않아
|
||||||
|
월마다 매출 ÷ 로아스로 환산해 합친 **매출 가중 평균**(같은 목표/실적 매출 사용), 로아스가 있는 달 중 매출이 없는 달이 있으면 단순 평균
|
||||||
|
(말풍선에 방식·개월 수). 화면 계산(저장 안 함), 숫자 칸을 고치면 바로 다시 계산.
|
||||||
|
- 업무 영역 글: `goal_cells.month` **13 = 상반기, 14 = 하반기**(014 가 CHECK 를 0~14 로 넓힘). 014 미적용이면 반기 글 칸은
|
||||||
|
보기 전용 빈 칸이고, 저장 API 는 503 "마이그레이션 014 필요"(`store.GoalMigration014Needed`).
|
||||||
|
- **반기 접기** — 반기 칸 머리의 버튼(`.pj-goal-fold`, 펼침 ‹ / 접힘 뒤집힌 › + 강조색)이 그 반기 월 칸을 접었다 편다.
|
||||||
|
보기 전용 사용자도 쓸 수 있고 상태는 브라우저별 localStorage `pj_goal_fold`(`{"1":bool,"2":bool}`).
|
||||||
|
애니메이션(`applyFold`): 접기 = `.is-shrunk`(칸 width·padding·테두리 → 0, `.is-folding` 동안만 transition .32s) 뒤
|
||||||
|
`.is-gone`(display:none), 펴기 = 거꾸로. 줄어드는 동안 칸 안 내용은 원래 폭(`85px × --span`)으로 고정해 잘라 내서 줄 높이가
|
||||||
|
출렁이지 않는다. **표는 `width: 1px` + `table-layout: fixed`** — fixed 는 표 너비가 auto 가 아닐 때만 먹는다(auto 면 칸 너비가
|
||||||
|
내용을 따라가 펼칠 때 애니메이션 없이 한 번에 튄다). 표는 칸 너비 합만큼 늘어난다. 접힌 칸의 글 칸 높이는 잴 수 없어(`fit` 이
|
||||||
|
`offsetParent` 없으면 건너뜀) 펼친 뒤 다시 잰다. `prefers-reduced-motion` 이면 애니메이션 없이.
|
||||||
|
- **영역·줄 이름 바로 수정**(관리자) — 이름(`[data-goal-edit="area|row"]`)을 누르면 contenteditable(`startNameEdit`) —
|
||||||
|
Enter·칸 떠남 = 저장, Esc = 취소, 붙여넣기는 글자만. 영역 이름 빈 값은 되돌림(서버도 400), 줄 이름은 빈 값 허용(빈 줄 이름은
|
||||||
|
마우스를 올리면 "줄 이름" 자리 표시). 예전 ✎(prompt) 버튼은 없앴다. 색·순서·줄 추가·삭제는 우클릭 메뉴(아래).
|
||||||
|
- **구역·항목 칸 메뉴 = 우클릭 + ⋮ 버튼**(2026-10-01) — 마우스 오버 도구 막대(색·↑·↓·+·×)는 뺐다(옆 칸으로 갈 때 걸리거나 고정되는 문제).
|
||||||
|
대신(점검 UX 8) 칸 오른쪽 위 작은 ⋮ 버튼(`.pj-goal-menu-btn`, 관리자만, `data-goal-menu="area|row"`) — absolute 라 자리를 차지하지 않고
|
||||||
|
평소 투명, 칸에 마우스·포커스가 오면 보임, 터치 화면(`hover: none`)은 늘 옅게(0.7). 우클릭과 **같은 메뉴**(`openAreaMenu`·`openRowLabelMenu`).
|
||||||
|
접근성: 버튼 `aria-label="{이름} 구역 메뉴|줄 메뉴"`·`aria-haspopup="menu"`·`aria-expanded`, Tab → Enter/Space 로 열면 첫 항목 포커스,
|
||||||
|
메뉴(`showContextMenu` 공용, `role=menu`/`menuitem`) 안 ↑↓·Home·End·Enter, Esc·Tab = 닫고 버튼으로 포커스 복귀, 같은 버튼 다시 누르면 닫힘.
|
||||||
|
이름 칸(`[data-goal-edit]`)도 `tabindex=0` — Enter·F2 = 이름 수정(한글 조합 중 Enter 무시).
|
||||||
|
1열(구역 칸) 우클릭(`areaMenuItems` → `goalAct`): 색 바꾸기(색 창은 우클릭한 자리, 현재 색은 `tbody[data-color]`) · 위로 · 아래로
|
||||||
|
(맨 위·맨 아래면 없음) · 줄 추가(구역 맨 아래) · 영역 삭제. 2열(항목 칸) 우클릭(`rowMenuItems`): 위/아래에 줄 추가 · **위로 · 아래로**
|
||||||
|
(묶이지 않은 칸만) · 항목 칸 나누기(묶인 칸) · 줄 삭제. 이름은 눌러서 바로 수정(그대로).
|
||||||
|
- **줄 추가·삭제(항목 칸)**(관리자) — 줄 이름 칸 도구 막대: ↑·↓(줄 2개 이상)·**+ = 이 줄 아래에 줄 추가**·×(줄 2개 이상). 항목 칸 **우클릭 메뉴**: 위에 줄 추가 / 아래에 줄 추가 / 줄 삭제(영역의 마지막 한 줄이면 없음). 추가는 이름을 묻고(비워도 됨) `db.add_goal_row(ref_row_id, place)` 가 영역 줄 순서를 다시 매긴다(영역 FOR UPDATE). 영역 이름 칸의 + 는 예전처럼 맨 끝에 추가.
|
||||||
|
- **칸 병합 — 엑셀식**(관리자, 014 + 015, 2026-10-01에 예전 Shift+클릭·떠 있는 병합 버튼·오른쪽/왼쪽 칸과 병합 메뉴를 대체)
|
||||||
|
— `goal_cell_merges(row_id, start_month, span, row_span)`. 시작 칸 = **왼쪽 위**(row_id = 맨 위 줄, start_month = 왼쪽 칸 번호).
|
||||||
|
- 범위: **같은 업무 영역 안 연속된 줄**(세로, `row_span` — 015) × 화면 순서(연간 · 1~6월 · 상반기 · 7~12월 · 하반기 =
|
||||||
|
`store.GOAL_COL_ORDER`)의 연속된 칸. 가로는 **같은 반기 월 칸끼리만**, 연간(0)·상반기(13)·하반기(14) 칸은 **세로로만**
|
||||||
|
(`store.validate_goal_rect_cols`, DB CHECK). 015 미적용이면 예전처럼 한 줄 월 칸 가로 병합만(세로·연간/반기는 503).
|
||||||
|
- 고르기: 글 칸을 **마우스로 끌기**(다른 칸으로 넘어가는 순간부터 범위 선택, 글 선택·포커스는 막음 — `html.pj-goal-selecting`)
|
||||||
|
또는 **Shift+클릭**(마지막으로 누른 칸부터). 범위가 병합된 칸에 걸치면 **엑셀처럼 그 칸 전체로 넓힌다**(`expand`). 칸 한 번 클릭은
|
||||||
|
그대로 입력. 다른 곳 누름·Esc = 해제.
|
||||||
|
- **우클릭**: "셀 병합 (N줄 × M칸)"(2칸 이상) · "병합 해제"(범위 안 병합된 칸, 여러 곳이면 개수). 범위 밖을 우클릭하면 그 칸만
|
||||||
|
고른 것으로(엑셀과 같음). 해당 메뉴가 없으면 브라우저 기본 메뉴. 묶음이 다른 가로 범위는 서버를 부르지 않고 안내.
|
||||||
|
- `POST /api/goals/areas/{area_id}/merge {row_from, row_to(줄 id), col_from, col_to(칸 번호)}` → `db.merge_goal_rect`: 영역 FOR UPDATE,
|
||||||
|
걸친 병합 흡수(넓힌 뒤 묶음 다시 검사), 범위 안 글을 **왼쪽 위부터 줄·칸 순서대로 줄바꿈으로 이어 왼쪽 위 칸에**(글을 잃지 않게 —
|
||||||
|
엑셀은 왼쪽 위 값만 남기지만 여기선 잇는다), 나머지 칸 글·안쪽 병합은 지운다. 응답 `{row_id, start, span, row_span}`.
|
||||||
|
`DELETE /api/goals/rows/{row_id}/merge/{start}` = 해제 — **글은 왼쪽 위 칸에 남는다**(엑셀과 같음). 화면은 저장 안 된 글을 먼저
|
||||||
|
저장(`flushTexts`)한 뒤 부르고 새로고침.
|
||||||
|
- 화면 배치: `router._goal_area_layout` 이 영역 단위로 칸마다 `{m, kind, h, span, rspan, now}` — 시작 칸은 `colspan`·`rowspan`,
|
||||||
|
가려진 칸은 그리지 않는다(세로는 영역 끝, 가로는 같은 묶음 안으로 자름). 반기 접기는 병합 칸도 `pj-goal-m[data-h]` 로 함께 숨김.
|
||||||
|
- 가려진 칸으로 늦게 온 글 저장은 400("병합된 칸입니다", `_area_geometry`·`_covered_by` — 가로·세로 모두).
|
||||||
|
- 줄 작업과 세로 병합(엑셀처럼): 병합 **안쪽에 줄 끼우기** → `row_span + 1` · **가려진 줄 지우기** → `row_span − 1`(1칸이 되면 병합 삭제) ·
|
||||||
|
맨 위(시작) 줄 지우기 → 병합도 지워짐(CASCADE) · 세로 병합에 걸린 줄(자신이나 바꿀 이웃)의 **↑↓ 이동은 400**(해제 뒤 이동).
|
||||||
|
- 새 연도 만들기(구조 복사)는 병합을 복사하지 않는다(줄 이름만).
|
||||||
|
- **구조 변경 뒤 제자리 다시 그리기**(`refreshTable`, 2026-10-01) — 줄·영역 추가/삭제/이동, 병합/해제 뒤 페이지를 새로고침하지
|
||||||
|
않고 이 페이지를 다시 받아 **업무 영역 tbody 만** 바꿔 끼운다(열 너비·반기 접기 다시 적용, 새 글 칸 연결 `bindTexts`). 새로고침 때
|
||||||
|
저장된 열 너비가 늦게 적용돼 표가 줄었다 늘어나고 깜박이던 것을 없앴다. 애니메이션: 지운 줄은 흐려지며 사라지고, 남은 줄은 예전
|
||||||
|
자리에서 미끄러져 오고(FLIP, 0.28초), 새 줄은 위에서 내려오며 보라색으로 잠깐 강조(`is-new-row`), 병합·해제한 칸은 테두리 강조
|
||||||
|
(`is-merge-flash`). 동작 줄이기 설정이면 애니메이션 없이. 받아 오기 실패하면 예전처럼 새로고침.
|
||||||
|
- **3열(연간 칸) 우클릭 → 줄 메뉴**: 위에 줄 추가 · 아래에 줄 추가 · 줄 삭제. **3열에서 추가한 줄은 같은 항목 칸(2열) 안에** 들어간다
|
||||||
|
(2열은 하나, 3열부터 줄이 늘어남 — 이름을 묻지 않음, `same_label`, 마이그레이션 016). 세로로 병합된 연간 칸이면 아래 추가는 병합의
|
||||||
|
맨 아래 줄 기준, 삭제는 없음. 병합 메뉴(셀 병합·해제)가 있으면 그 아래에 붙는다.
|
||||||
|
- **항목 칸(2열) 묶음**(016 `goal_rows.label_cont` = 바로 위 줄 항목 칸에 묶임, 이름은 묶음 첫 줄에): 화면은 `router._goal_label_spans`
|
||||||
|
가 묶음 첫 줄에 `label_span`(2열 rowspan), 이어 붙은 줄은 2열을 그리지 않는다.
|
||||||
|
- `POST /api/goals/areas/{id}/rows {ref_row_id, place, same_label: true}` → 아래 = 새 줄이 이어 붙음, 위 = 기준 줄이 묶음 첫 줄이면
|
||||||
|
새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙음(이어 붙은 줄 위면 그냥 이어 붙음). 016 미적용이면 503.
|
||||||
|
- 2열 메뉴·+ 의 줄 추가는 **묶음 밖**(위 = 묶음 첫 줄 위, 아래 = 묶음 맨 아래 줄 아래, 이름 물음). 묶인 2열 우클릭 → **항목 칸 나누기**
|
||||||
|
(`POST /api/goals/rows/{첫 줄}/split-label` — 이어 붙은 줄들이 각자 빈 이름 항목 칸으로).
|
||||||
|
- 묶음 첫 줄 삭제 → 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름이 비어 있으면 넘겨받음. 묶인 줄(첫 줄·이어 붙은 줄)과 바꾸는 ↑↓ 이동은 400
|
||||||
|
(나눈 뒤 이동), 묶음 첫 줄 도구 막대엔 ↑↓ 없음. 새 연도 만들기는 묶음도 복사한다.
|
||||||
|
- **칸 아무 곳이나 눌러 입력**(엑셀처럼) — 글 칸(textarea)은 글 높이만큼이라, 옆 칸 글이 길거나 세로 병합으로 칸이 길면 아래쪽을 눌러도
|
||||||
|
입력이 안 됐다. 이제 업무 영역 글 칸(`td.pj-goal-texttd`)·회의록 글/금액 칸 아무 곳이나 누르면 그 칸 입력으로 들어가고 커서는 글 끝.
|
||||||
|
칸 전체가 글 입력 마우스 모양. Shift+클릭(범위 고르기)·끌기(병합 선택)는 그대로.
|
||||||
|
입력 중 테두리·밝은 배경도 입력칸이 아니라 **칸 전체**(`td:focus-within`, 회의록 표도 같음).
|
||||||
|
- **고른 칸 내용 지우기(엑셀 Del)** — 끌기·Shift+클릭으로 고른 범위에서 Del → 범위 안 글 칸을 비우고 칸마다 바로 저장, 안내 토스트.
|
||||||
|
바로 직전 지우기는 **Ctrl+Z** 로 되돌림(되돌린 값도 저장). 입력 중(글 칸에 커서)일 때의 Del·Ctrl+Z 는 평소 글자 편집.
|
||||||
|
우클릭 메뉴에도 "내용 지우기 (Del)"(`ink_eraser`, 고른 범위에 글이 있을 때).
|
||||||
|
- **우클릭 메뉴 아이콘** — `menuIcon(name)`(Material Symbols)을 `showContextMenu` 항목 `icon` 에: 위에 줄 추가 `add_row_above` ·
|
||||||
|
아래에 줄 추가 `add_row_below` · 줄 삭제 `delete`(빨강) · 셀 병합 `cell_merge` · 병합 해제 `call_split` · 항목 칸 나누기
|
||||||
|
`horizontal_split` · (회의록) 위로/아래로 `arrow_upward`/`arrow_downward` · 쇼핑몰 연결 `link` · 연결 안 함 `link_off` · 쇼핑몰 `storefront`.
|
||||||
|
- **월 머리 → 주간 회의록** — 목표 표 머리의 월 칸을 누르면 `/project/goals/{연도}/meetings/{월}`(6-9-2). 링크(`a.pj-goal-mlink`)는
|
||||||
|
글자만이 아니라 **칸 전체**(absolute inset 0), 오른쪽 끝 너비 조절 손잡이(z-index 5)는 링크 위라 그대로 끌 수 있다.
|
||||||
|
- **로아스 단위 %** — 로아스 목표·실적 칸은 `499%` 처럼 보인다(`router._goal_label`, 저장 응답 `label` 도 같음). 입력은 `499`·`499%`
|
||||||
|
둘 다 되고 저장 값은 숫자(`validate_goal_value` 가 `%` 를 뗀다).
|
||||||
|
|
||||||
|
### 6-9-2. 주간 회의록 (마이그레이션 015)
|
||||||
|
|
||||||
|
지난주 목표·결과를 리뷰하고 월 목표를 달성하기 위한 이번주 목표·할 일을 정하는 회의(WBR — Weekly Business Review)용.
|
||||||
|
참고한 도구 방식: **WBR 지표 자동 집계**(목표 대비 누적·주당 필요 매출 = 페이싱), **Fellow·Notion 회의 템플릿의 이월**(지난 회의
|
||||||
|
항목을 다음 회의로 이어받아 나란히 리뷰), **OKR 체크인 평가**(완료/일부/미달).
|
||||||
|
|
||||||
|
- 화면 `/project/goals/{연도}/meetings/{월}?week={월요일}`(`goal_meeting.html`, `initGoalMeeting`) — 목표 표 월 머리를 누르면 열린다.
|
||||||
|
- **주차 탭**: 그 달의 주(월~일, `store.month_weeks`) — **1주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||||
|
(2026-10-01 사용자 기준. 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 는 9월 마지막 주). 다른 달의 주를 `?week=` 로 열면
|
||||||
|
그 달 회의록 주소로 303. 점 = 회의록 있음, "이번 주" 꼬리표. 기본 선택 = 이번 주(그 달 주면) 아니면 1주차.
|
||||||
|
‹ 이전 달 · 다음 달 › 링크, ← 목표 표.
|
||||||
|
- **월간 목표·누적은 늘 1일~말일**(주차와 따로): 월 누적 실적 = 1일 ~ 이 주 앞(지난주 일요일, 1주차면 첫 월요일 전날)까지,
|
||||||
|
주당 필요 매출 = (월 목표 − 누적) ÷ 그 달 남은 주 수(이 주 포함).
|
||||||
|
- 머리 배치: 왼쪽 = **[🚩 {연도}년 목표] 버튼**(연간 목표로, 큰 강조 버튼 `.pj-meet-goalbtn` — 예전 ← 화살표 대신)·제목·‹이전 달·다음 달›·
|
||||||
|
인쇄·회의록 삭제·**주차 탭(제목 줄 오른쪽 끝 = 달력 바로 왼쪽에 붙음, 한 줄짜리 작은 탭 — `1주차 10/5~11`, 같은 달이면 끝 월 생략, 전체 기간은 말풍선)**,
|
||||||
|
그 아래 **{월}월 계획**(달력 앞까지 너비), **오른쪽 위 = 작은 달력**(폭 174px, 날짜 10.5px·칸 높이 21px). 목표·회의록 제목은 32px 굵게(`h2.pj-goal-title`).
|
||||||
|
- **작은 달력**(`.pj-meet-cal`, `store.calendar_weeks`): 그 달 날짜가 든 주 전부(월요일 시작) — 앞 달에 속한 주(1일 앞쪽,
|
||||||
|
예: 10월 달력의 9/28 주)는 흐리게, 누르면 그 달(9월) 회의록. 줄 = 주(월~일) — 보고 있는 주는 영역 표시(테두리·배경),
|
||||||
|
오늘 동그라미, 토 파랑·일/공휴일(`store.KR_HOLIDAYS`) 빨강, 다른 달 날짜 흐리게, 회의록 있는 주는 왼쪽 점. 줄을 누르면 그 주 회의록
|
||||||
|
(`?week=`). 날짜 정보는 라우터가 주마다 `days`(d·in·today·wd·hol)로 넘긴다. 인쇄에선 숨김.
|
||||||
|
- **머리 숫자**(`router._meeting_view`): 월 목표 매출(목표 표 숫자 + 단위, 단위가 원/천/만/십만/백만/천만/억이면 원 환산 —
|
||||||
|
`store.sales_unit_multiplier`) · **월 누적 실적(지난주 일요일까지)** · **주당 필요 매출** = (월 목표 − 누적) ÷ 이번 주 포함 남은 주 수 ·
|
||||||
|
목표 ROAS(목표 표) / 전주 목표(바로 앞 주 회의록의 금주 목표) · **전주 결과** · 전주 달성률 · **금주 목표**(입력, 칸 안내 = 필요 매출) ·
|
||||||
|
금주 현재 실적. 실적·누적·결과는 **실적 모듈 `performance_store.daily_amounts`(대시보드 총매출과 같은 값, 매출 집계 쇼핑몰)** 에서
|
||||||
|
읽기만 한다 — 실적 모듈이 없거나 오류면 빈칸("직접 입력" 안내), 회의록은 그대로 동작.
|
||||||
|
숫자는 **한 줄 막대**(`.pj-meet-kpibar`, 칸 9개·값 15px, 좁은 화면 1300px 이하 두 줄) — 긴 설명은 말풍선(`title`).
|
||||||
|
**실적을 알 수 없으면 0 원이 아니라 "⚠ 미확인"**(6-9-3 — `head.perf_state`·`head.unknown`), 그 값에 기대는 달성 %·주당 필요 매출도 미확인.
|
||||||
|
실적 칸 말풍선 = 쇼핑몰별 마지막 갱신 성공 시각(실적 모듈 `perf_connection_status.last_success_sync_at`, `head.fresh_tip`).
|
||||||
|
- **이번주 ↔ 지난주 리뷰 순서 바꾸기**(표 왼쪽 위 [⇄ 순서 바꾸기], `initMeetOrder`): 줄마다 is-this(2칸)·is-prev(5칸) 묶음과
|
||||||
|
colgroup 을 통째로 옮긴다. 보는 사람마다 브라우저에 기억(localStorage `pj_meet_order:{로그인 이메일}`, `.pj-wrap[data-me]`).
|
||||||
|
- 표 머리 "지난주 리뷰 (MM/DD ~ MM/DD)" = 지난주 월~일(`prev_week`·`prev_week_end`) — **줄의 지난주 칸·결과·달성률·머리 전주 목표도 정확히 이
|
||||||
|
주(7일 전) 회의록만**(그 주 회의록이 없으면 머리에 "— 이 주 회의록 없음", 줄은 "지난주(MM/DD~) 회의록 없음", 회의록은 있는데 그 줄이 없으면
|
||||||
|
"지난주 회의록에 없는 줄"). 예전엔 몇 주 전 회의록 줄이 지난주 날짜 아래 보였다(점검 버그 5).
|
||||||
|
- 첫 회의록 기본 줄 마케팅 "메타"(예전 "메타(숫자)" — 017 이 그 이름 줄만 "메타"로 바꿈).
|
||||||
|
- **{월}월 계획**(`router._month_plan`, `.pj-meet-plan`, 머리 왼쪽 `.pj-meet-headleft` 안 — 제목 줄 아래·달력 왼쪽): 연간 목표 표의 그 달 열 글을 업무 영역별 작은 카드로
|
||||||
|
(영역 색, `항목: 글`, 빈 칸·글 없는 영역은 뺌). 가로 병합 칸(예: 9~10월)에 적은 글도 그 달 계획으로 보이고 범위를 오른쪽에 작게,
|
||||||
|
세로 병합은 한 번만, 묶인 줄(016 `label_cont`)은 묶음 항목 이름. 목표 표가 없으면(013 미적용) 칸 자체를 숨김, 읽기만.
|
||||||
|
- **줄**(구역 = 목표 표 업무 영역, 표의 구역 칸 rowspan): 항목 | **이번주 할 일·행사** | **정량 목표**(원, 예전 이름 "목표 금액") ‖ 지난주 리뷰: 지난주 할 일 |
|
||||||
|
지난주 목표 | **결과** | 달성률 | **평가**(— · 완료 · 일부 · 미달). 지난주 칸 = **7일 전 주 회의록에서 같은 연결키(`line_key`, 018)의 줄**
|
||||||
|
(예전 `carry_from` 은 이력으로만 — 6-9-3).
|
||||||
|
결과는 그 줄이 **쇼핑몰 연결**(`marketplace_code`)이면 실적 모듈의 그 주(지난 회의록 주 월~일) 그 쇼핑몰 매출 **자동**("자동" 표시),
|
||||||
|
아니면 직접 입력 — **지난 회의록 줄의 `result_amount`·`status` 에 저장**(그 주 결과는 그 주 줄에 남는다). 달성률은 저장 즉시 화면 계산.
|
||||||
|
지난 회의록 주가 아직 시작 전이면 "진행 전"(0 으로 보이지 않게), 연결한 쇼핑몰이 실적 모듈에서 사용 중이 아니면(사용 OFF·없는 코드)
|
||||||
|
"실적 미사용" 표시 + 직접 입력. 자동 결과 말풍선 = 쇼핑몰·기간, 0 이면 "그 기간 실적 없음 — [매출 업데이트]" 안내.
|
||||||
|
쇼핑몰 연결 줄은 정량 목표 아래에 **이번주 실적**(이 주 월요일~오늘, 목표 대비 %)도 보인다 — % 는 화면이 실적(`slot data-auto`)과
|
||||||
|
**서버 확정 정량 목표**(`tr data-target-amount`)로 계산(`paintMeetWeek`): 목표 저장 즉시 다시 계산(100→200 이면 100%→50%), 목표 0·빈칸이면
|
||||||
|
% 없음, 실적 조회 실패면 "이번주 실적 미확인", 저장 실패면 확정값 그대로. 다시 그리기(`meetRepaint`)는 실적 값만 옮겨 와 같은 방식으로 계산하고
|
||||||
|
차례 번호(`meetRepaintSeq`)로 늦게 온 옛 화면을 버린다 — 목표 저장과 엇갈려도 옛 비율이 들어오지 않는다(점검 버그 7).
|
||||||
|
- **매출 자료 갱신**(`initMeetingSync`, **정상이면 화면 표시 없음** — 2026-10-01 상태 줄·[매출 갱신] 버튼은 요청으로 뺐다. 점검 UX 9 로
|
||||||
|
실패·일부 실패·권한 없음일 때만 숫자 막대 아래 한 줄 안내 `#pj-meet-sync.pj-meet-syncnote`(`data-state=error|partial|noperm|running`) +
|
||||||
|
[다시 시도] — 실패한 쇼핑몰 이름(상태), **서버가 기록한** 마지막 갱신 성공 시각(`data-fresh` = 매출 집계 쇼핑몰 중 가장 오래된 성공 시각,
|
||||||
|
다시 그릴 때 서버 값으로 바뀜. 브라우저 시각은 10분 제한 계산에만 쓰고 보여 주지 않음). 기록 `sessionStorage pj_meet_sync:{월요일}` =
|
||||||
|
`{at, state: ok|partial|error|noperm, bad}` — 일부 실패를 성공으로 기록하지 않고, 10분 안 다시 열면 부르지 않되 그 상태 안내는 유지.
|
||||||
|
실적 모듈 권한은 서버가 미리 알려 줘(`can_sync` → `data-can`) 권한이 없으면 API 를 부르지 않고 "권한이 없어 저장된 실적" 설명, 그래도 403 이면
|
||||||
|
noperm 으로 기억해 그 세션엔 다시 부르지 않음. 다른 업데이트에 합류(`joined`)했는데 그 작업 기간이 이 주 기간을 다 덮지 못하면 이 주 기간으로
|
||||||
|
한 번 더. 아래는 예전 설명(동작은 같음): 주차를 열면 실적 모듈 `POST /performance/api/sync {from: 지난주 월요일, to: 이번 주 일요일·오늘 중 이른 날, background: true}` 로 쇼핑몰에서 매출을 한 번 더 받고(진행 n/m 쇼핑몰·받은 자료), 끝나면 이 화면을 서버에서 다시 받아 **숫자 칸만** 바꿔 끼운다(머리 카드·자동 결과·달성률·이번주 실적 — 입력 중인 칸·직접 입력 결과 칸·저장 안 된 글은 그대로). 같은 주는 브라우저별 10분에 한 번만 자동(sessionStorage `pj_meet_sync:{월요일}` — 줄 추가 등으로 새로고침해도 다시 부르지 않음), [매출 갱신] 버튼은 언제나. 이미 다른 매출 업데이트가 돌면 그 작업이 끝나길 기다린다. 실적 권한이 없으면 저장된 실적으로 보여 준다는 안내, 실패한 쇼핑몰은 이름·상태. 지난주가 아직 오지 않은 주(미래)는 갱신 줄이 없다.
|
||||||
|
- **참석자 = 전체 멤버에서 고르기**(2026-10-01): 칩(사진·이름, × = 빼기) + [참석자] 고르기 창(찾기·전원 선택·모두 해제·체크) —
|
||||||
|
후보는 `project` 모듈 권한 보유 등록 사용자(`router._meet_members`, 좌측 전체 멤버와 같음). 저장은 이메일을 쉼표로 이어 그대로
|
||||||
|
`goal_meetings.attendees`(최대 3000자), 예전 자유 입력 글자는 칩으로 남는다(`_parse_attendees`). 바뀔 때마다 바로 저장.
|
||||||
|
- **결정 사항·메모**. 인쇄 버튼(인쇄용 CSS — 사이드바·탭·도구 숨김).
|
||||||
|
- 데이터: `goal_meetings(week_start 월요일 PK, week_target 원, attendees, notes)` · `goal_meeting_items(week_start FK CASCADE, section,
|
||||||
|
section_color, label, content, target_amount, result_amount, status '', done, partial, miss, marketplace_code, carry_from FK SET NULL,
|
||||||
|
sort_order)`. 금액은 **원 정수** — 입력은 `1,200,000`·`120만`·`1.5억`·`3천만`·`1억2천만` 다 된다(`store.validate_meeting_amount`).
|
||||||
|
- **만들기**(관리자, `POST /api/goals/meetings/{월요일} {year}`, GET 에서 자동 생성 안 함): 줄이 있는 앞선 가장 가까운 회의록, 없으면 **뒤에 있는
|
||||||
|
가장 가까운 회의록**(다음 주를 먼저 만든 경우)의 줄(구역·이름·색·쇼핑몰 연결·순서)을 글 없이 이어받고 **원본 줄의 연결키(`line_key`)를 그대로**
|
||||||
|
(앞선 원본이면 `carry_from` 도 이력으로 기록), 둘 다 없으면 그 해 목표 표 업무 영역마다 **기본 양식 줄**(`store.MEETING_TEMPLATE` —
|
||||||
|
상품1~5 / 메타·구글·네이버·기타.신규 / 내용1~5 / 신규 인플루언서·콜라보·쿠팡·네이버·gs·토스·애터미·해외·오프라인·기타, 없는 구역은
|
||||||
|
빈 줄 하나). **유통** 구역 줄 이름으로 쇼핑몰 연결 추측(`store.guess_meeting_market`: 쿠팡·네이버/스마트스토어·gs·토스·11번가·카페24/자사몰·
|
||||||
|
롯데·지마켓·카카오·오늘의집 — 마케팅의 "네이버"는 광고라 연결 안 함). 줄 추가 때도 같은 추측.
|
||||||
|
- 편집(관리자, 칸별 즉시 저장 — 목표 표와 같은 권한, 공용 `createFieldSaver` 6-9-3): 글 0.8초 멈춤·칸 떠남, 금액 Enter·칸 떠남(서버 확정값을
|
||||||
|
쉼표 표기로 — 요청 뒤 다시 입력 중이면 그 초안 유지), 금주 목표 저장(`PUT` 응답에 확정 `week_target`) 뒤엔 **새로고침 없이** 머리 숫자만 서버
|
||||||
|
계산으로 다시(`meetRepaint` — 다른 칸의 저장 안 된 글 보존). 줄 작업(추가·순서·쇼핑몰 연결·삭제)은 먼저 저장 안 된 칸을 저장하고, 실패하면
|
||||||
|
작업하지 않는다(초안 유지). **항목 우클릭·⋯ 메뉴**: 위/아래에 줄 추가 · 위로/아래로(같은 구역 안) ·
|
||||||
|
쇼핑몰 연결(결과 자동)…(연결 안 함 + 실적 모듈 사용 중 쇼핑몰, 현재 값 체크) · 줄 삭제. 구역 칸 + = 그 구역 끝에 줄, [+ 구역 추가].
|
||||||
|
줄 이름은 눌러서 그 자리에서 수정. 회의록 삭제 = 그 주 줄 전부 삭제, 다음 주 회의록의 지난주 칸은 빈다 — 그 주를 다시 만들면 같은 연결키로
|
||||||
|
다시 이어진다(새 회의록이라 글은 비어 있음, 018).
|
||||||
|
- API(관리자, 조회는 `project` 권한자): `GET /api/goals/meetings/{월요일}?year=&month=`(화면과 같은 계산) · `POST|PUT|DELETE
|
||||||
|
/api/goals/meetings/{월요일}`(PUT `{week_target, attendees, notes}`) · `POST /api/goals/meetings/{월요일}/items {section, label?,
|
||||||
|
ref_item_id?, place?}` · `PUT|DELETE /api/goals/meeting-items/{id}`(PUT `{label, content, target_amount, result_amount, status,
|
||||||
|
marketplace_code}`) · `POST /api/goals/meeting-items/{id}/move {direction}`. 015 미적용 503, 월요일 아님·금액 형식 400.
|
||||||
|
|
||||||
|
### 6-9-3. 저장 안전장치 · 지난주 연결 · 실적 미확인 (2026-10-01 점검 반영 — `docs/reviews/GOALS_MEETINGS_REVIEW_2026-10-01.md`, 마이그레이션 018)
|
||||||
|
|
||||||
|
**칸별 자동 저장 `createFieldSaver`**(project.js 공용, 목표 표 글·숫자 + 회의록 글·메모·금액·금주 목표 — 버그 1·2·3)
|
||||||
|
- 칸마다 `{saved, chain, busy, timer, failed}`. **saved = 성공한 요청에 실어 보낸 값**만(응답 때 바뀌어 있는 화면 값을 저장됨으로 보지 않음).
|
||||||
|
- **같은 칸 요청은 직렬화** — 앞 요청이 끝나야 다음 요청을 보내므로 서버에 닿는 쓰기 순서 = 보낸 순서(늦은 옛 요청이 최신 값을 덮지 못함, 응답만
|
||||||
|
버리는 방식이 아님). 다음 요청은 보낼 때의 최신 초안을 읽어 진행 중에 새로 쓴 값도 뒤이어 저장. 앞 요청이 없으면 그 자리에서(동기) 보낸다.
|
||||||
|
- 응답 반영: 서버 표기(쉼표·원 정수)는 **요청 뒤 초안이 그대로일 때만** 칸에 넣는다(`onSaved(..., same)`). 실패하면 초안·dirty 유지 +
|
||||||
|
빨간 테두리(`is-save-failed`, 말풍선) + 토스트 — 다음 입력·칸 떠남·Enter·`flushAll` 이 다시 보낸다. 숫자 Esc = 저장된 값.
|
||||||
|
- `flushAll()` = 대기 타이머 + 진행 중 요청 + 실패했던 칸까지 기다리고 하나라도 실패하면 reject. 목표 표 구조 작업(영역·줄 추가/이동/삭제,
|
||||||
|
병합/해제)과 회의록 줄 작업은 **먼저 flushAll — 실패하면 구조 요청·표 교체를 하지 않는다**. 목표 표 구조 작업은 한 번에 하나(`withStruct`).
|
||||||
|
- 목표 표 `refreshTable`: 시작 전 flush(실패 = throw), 표를 받는 사이 새로 입력한 글이 있으면 저장 후 다시 받기(최대 3번, 바꿔 끼우기 직전 검사는
|
||||||
|
동기라 그 사이 입력 불가), 계속 입력 중이면 바꿔 끼우지 않고 `pendingRefresh` — 저장이 끝나면 다시 그린다. 이름 고치는 중이어도 기다림.
|
||||||
|
- **초안 백업** — 글 칸은 입력할 때마다 `localStorage pj_draft:goal:{줄}:{칸}` · `pj_draft:meet:item:{id}:content` · `pj_draft:meet:notes:{월요일}` =
|
||||||
|
`{base(서버에 저장된 값), draft, at}`, 저장되면 지움(14일 지난 것은 열 때 정리). 다시 열 때 **서버 값 = base 면 되살려 다시 저장**, 서버 값이 바뀌었으면
|
||||||
|
(다른 사람·다른 창) 되살리지 않고 안내.
|
||||||
|
- **페이지 떠남**(`beforeunload`): 진행 중 요청이 없는 dirty 글 칸은 `keepalive` PUT 으로 한 번 더 보낸다 — **브라우저가 끝까지 보낸다는 보장은 없어서**
|
||||||
|
초안 백업이 함께 남는다(keepalive 도 같은 칸 줄에 들어가 순서가 섞이지 않음). 실패했던 칸·진행 중 요청이 있는 칸·Enter 전 숫자 칸이 있으면 브라우저
|
||||||
|
이탈 경고. 저장이 다 끝났으면 경고 없음.
|
||||||
|
|
||||||
|
**지난주 연결 — 연결키 `goal_meeting_items.line_key`(마이그레이션 018, 버그 4·5)**
|
||||||
|
- 왜 키인가: 이름(label) 비교는 같은 이름 줄(기타·빈 이름)·다른 구역 같은 이름(마케팅/유통 "네이버")·이름 변경에서 다른 줄 결과가 섞인다.
|
||||||
|
`carry_from`(앞선 회의록 줄 id)은 만들 때 한 방향으로만 생겨 역순 생성·앞 주 삭제/재생성(ON DELETE SET NULL)에서 끊긴다.
|
||||||
|
키는 **회의록을 만들 때 원본 줄 키를 그대로 이어받고 새 줄은 새 키** → "지난주" = `week_start − 7` 회의록의 같은 키 줄(UNIQUE `(week_start, line_key)`),
|
||||||
|
생성 순서·이름 변경·순서 이동과 무관, 한 줄이 두 줄에 붙지 않는다.
|
||||||
|
- 만들기 원본: 앞선 가장 가까운(줄 있는) 회의록 → 없으면 뒤의 가장 가까운 회의록 → 둘 다 없으면 양식(새 키).
|
||||||
|
- **018 적용 전**에도 코드는 동작 — `_meeting_keys` 가 칸 유무를 보고, 없으면 `carry_from` 을 쓰되 **가리키는 줄이 정확히 7일 전 주일 때만** 지난주로
|
||||||
|
(버그 5 는 적용 전에도 고침, 역순 생성 연결(버그 4)은 018 필요). 018 은 `line_key` 기본값(랜덤 키)을 두어 **코드 배포 전에 적용해도** 예전 코드의
|
||||||
|
줄 추가가 실패하지 않는다(그 줄은 연결 없이 새 키).
|
||||||
|
- **018 의 기존 데이터 채우기(자동 복구 범위)**: `carry_from` 사슬을 따라 같은 키(뿌리 = 사슬 맨 앞 줄, `md5('goal_meeting_item:'||id)::uuid` 라 다시 돌려도
|
||||||
|
같은 키). → 같은 원본(예: 9/14)에서 이어받은 9/28(먼저 만듦)·9/21(나중에 만듦) 줄은 자동으로 다시 이어진다. 이름 바꾼 줄도 사슬이면 이어진다.
|
||||||
|
**자동으로 잇지 않는 것**: `carry_from` 이 없는 줄(첫 회의록 양식 줄·줄 추가·앞 주 삭제로 끊긴 줄) — 이름이 같아도 붙이지 않는다.
|
||||||
|
예: 9/21·9/28 을 둘 다 앞선 회의록 없이 양식으로 만들었다면 연결 안 됨. 이런 쌍은 `scripts/sql/project_db_018b_meeting_line_link_candidates.sql`
|
||||||
|
(**조회만**)로 "정확히 7일 차이 + 같은 구역·같은 이름이 양쪽 주에 각각 한 줄씩만 + 아직 연결 안 됨" 후보를 보고, 사람이 확인한 쌍만 그 파일 안
|
||||||
|
주석의 UPDATE 로 따로 잇는다(운영 적용은 별도 승인·백업 후). 한 주 안 같은 키(정상 데이터엔 없음)는 순서가 뒤인 줄에 새 키.
|
||||||
|
- 적용(운영은 백업·승인 후, 여러 번 돌려도 안전):
|
||||||
|
```bash
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db < scripts/sql/project_db_018_meeting_line_keys.sql
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db -c \
|
||||||
|
"SELECT count(*) AS total, count(line_key) AS keyed FROM goal_meeting_items;" # total = keyed
|
||||||
|
docker exec -i postgres-db psql -U postgres -d project_db < scripts/sql/project_db_018b_meeting_line_link_candidates.sql # 후보 조회만
|
||||||
|
```
|
||||||
|
적용 전 확인(조회만): `SELECT week_start, count(*) FILTER (WHERE carry_from IS NULL) AS no_link, count(*) FROM goal_meeting_items GROUP BY 1 ORDER BY 1;`
|
||||||
|
|
||||||
|
**실적 미확인(버그 6)** — `router._MeetingPerf`: `state` = `off`(실적 모듈 미연결) · `error`(쇼핑몰 목록 조회 실패) · `empty`(매출 집계 쇼핑몰 없음) · `ok`.
|
||||||
|
조회 실패한 값은 None + `head.unknown`(`mtd`·`prev_result`·`week_result`, 기간마다 따로 → 부분 실패), 화면 "⚠ 미확인", 그 값에 기대는 달성 %·주당 필요
|
||||||
|
매출도 계산하지 않음. 정상 조회 0건만 0원. 목록 장애면 쇼핑몰 연결 줄 결과 = 미확인(직접 입력 칸으로 바꾸지 않음, "실적 미사용"으로 오인하지 않음),
|
||||||
|
연결 배지 "· 미확인". `head.perf` 는 예전 뜻(실적 모듈 연결 여부) 그대로 — 갱신 상자·"연결되지 않아" 문구 조건. 회의록 열기·직접 입력은 그대로.
|
||||||
|
|
||||||
|
**테스트** — `tests/test_project_module.py`(`test_meeting_prev_week_links`: 역순 생성·같은 이름·다른 구역 같은 이름·이름 변경·이동·새 줄·삭제/재생성·
|
||||||
|
건너뛴 주, 018 적용/미적용 둘 다 · `test_meeting_perf_unknown_vs_zero`: 미연결·목록 장애·매출 장애·부분 실패·정상 0·집계 쇼핑몰 없음),
|
||||||
|
`tests/test_meeting_line_keys_migration.py`(018 백필·멱등·UNIQUE — 임시 스키마, 끝에 ROLLBACK), `tests/js/goals_meeting_ui.test.js`
|
||||||
|
(`python tests/js/render_goals.py` 후 — 버그 1·2·3·5·6·7, UX 8·9, 분기 접기·열 너비·스크롤·참석자 회귀).
|
||||||
|
|
||||||
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
|
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
|
||||||
|
|
||||||
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
|
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
|
||||||
|
|||||||
@@ -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,45 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 마이그레이션 014 — 연간 목표: 상·하반기 칸 · 월 칸 병합
|
||||||
|
-- =====================================================================
|
||||||
|
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — goal_cells 의 month CHECK 제약만 넓혀 다시 건다.
|
||||||
|
--
|
||||||
|
-- goal_cells.month 0 = 연간, 1~12 = 월, 13 = 상반기, 14 = 하반기
|
||||||
|
-- goal_cell_merges 업무 영역 줄의 월 칸 가로 병합. start_month 부터 span 칸(2칸 이상).
|
||||||
|
-- 상반기(1~6)·하반기(7~12)를 넘지 않는다(사이에 상반기 칸이 있고, 반기를 접을 수 있어서).
|
||||||
|
-- 글은 start_month 칸(goal_cells)에 둔다.
|
||||||
|
--
|
||||||
|
-- 미적용이어도 목표 화면은 동작한다 — 상·하반기 글 칸과 병합만 "마이그레이션 014 필요".
|
||||||
|
--
|
||||||
|
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_014_goal_halves_merges.sql
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
ALTER TABLE goal_cells DROP CONSTRAINT IF EXISTS goal_cells_month_check;
|
||||||
|
ALTER TABLE goal_cells ADD CONSTRAINT goal_cells_month_check CHECK (month BETWEEN 0 AND 14);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS goal_cell_merges (
|
||||||
|
row_id BIGINT NOT NULL REFERENCES goal_rows(id) ON DELETE CASCADE,
|
||||||
|
start_month SMALLINT NOT NULL,
|
||||||
|
span SMALLINT NOT NULL,
|
||||||
|
updated_by TEXT NOT NULL DEFAULT '',
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (row_id, start_month),
|
||||||
|
CONSTRAINT goal_cell_merges_range CHECK (
|
||||||
|
span >= 2 AND start_month >= 1 AND start_month + span - 1 <= 12
|
||||||
|
AND (start_month <= 6) = (start_month + span - 1 <= 6)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 줄의 월 칸 가로 병합(반기 안에서만)';
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_cell_merges TO project_app;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
SELECT 'project_db 014 goal halves/merges ready' AS status;
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 마이그레이션 015 — 연간 목표: 엑셀식 사각형 병합 · 주간 회의록
|
||||||
|
-- =====================================================================
|
||||||
|
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — goal_cell_merges 의 CHECK 제약만 바꿔 다시 건다.
|
||||||
|
--
|
||||||
|
-- ① goal_cell_merges.row_span — 병합을 세로로도(같은 업무 영역 안 연속된 줄). 시작 칸 = 왼쪽 위.
|
||||||
|
-- 가로(span)는 예전처럼 같은 반기의 월 칸 안에서만, 연간(0)·상반기(13)·하반기(14) 칸은 세로로만(span 1).
|
||||||
|
-- 가린 줄은 "시작 줄부터 영역 줄 순서로 row_span 줄". 글은 시작 칸(goal_cells)에만.
|
||||||
|
-- ② goal_meetings / goal_meeting_items — 월 머리를 누르면 열리는 주간 회의록(주 = 월요일~일요일).
|
||||||
|
-- 한 주 = 회의록 하나(week_start = 그 주 월요일). 항목은 구역(상품·마케팅·컨텐츠·유통 …)별 줄:
|
||||||
|
-- 이번주 할 일 · 목표 금액(원), 그 주 결과(원, 다음 주 회의에서 리뷰)·평가, 실적 모듈 쇼핑몰 연결(결과 자동),
|
||||||
|
-- carry_from = 전주 같은 줄(지난주 할 일·목표·결과를 나란히 보여 준다).
|
||||||
|
--
|
||||||
|
-- 미적용이어도 목표 화면은 동작한다 — 세로 병합·회의록만 "마이그레이션 015 필요".
|
||||||
|
--
|
||||||
|
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_015_goal_rect_merges_meetings.sql
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ① 사각형 병합 ─────────────────────────────────────────────────────
|
||||||
|
ALTER TABLE goal_cell_merges ADD COLUMN IF NOT EXISTS row_span SMALLINT NOT NULL DEFAULT 1;
|
||||||
|
ALTER TABLE goal_cell_merges DROP CONSTRAINT IF EXISTS goal_cell_merges_range;
|
||||||
|
ALTER TABLE goal_cell_merges ADD CONSTRAINT goal_cell_merges_range CHECK (
|
||||||
|
span >= 1 AND row_span >= 1 AND span * row_span >= 2
|
||||||
|
AND (
|
||||||
|
(start_month IN (0, 13, 14) AND span = 1)
|
||||||
|
OR (start_month BETWEEN 1 AND 12 AND start_month + span - 1 <= 12
|
||||||
|
AND (start_month <= 6) = (start_month + span - 1 <= 6))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 칸 병합(가로: 반기 안 월 칸, 세로: 같은 영역 안 줄 row_span)';
|
||||||
|
|
||||||
|
-- ② 주간 회의록 ─────────────────────────────────────────────────────
|
||||||
|
CREATE TABLE IF NOT EXISTS goal_meetings (
|
||||||
|
week_start DATE PRIMARY KEY CHECK (EXTRACT(ISODOW FROM week_start) = 1),
|
||||||
|
week_target BIGINT NULL CHECK (week_target IS NULL OR week_target >= 0), -- 금주 목표 매출(원)
|
||||||
|
attendees TEXT NOT NULL DEFAULT '',
|
||||||
|
notes TEXT NOT NULL DEFAULT '', -- 결정 사항·메모
|
||||||
|
created_by TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_by TEXT NOT NULL DEFAULT '',
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS goal_meeting_items (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
week_start DATE NOT NULL REFERENCES goal_meetings(week_start) ON DELETE CASCADE,
|
||||||
|
section TEXT NOT NULL DEFAULT '', -- 구역 이름(상품·마케팅·컨텐츠·유통 …)
|
||||||
|
section_color TEXT NOT NULL DEFAULT '',
|
||||||
|
label TEXT NOT NULL DEFAULT '', -- 줄 이름(쿠팡·메타 …)
|
||||||
|
content TEXT NOT NULL DEFAULT '', -- 이번주 할 일·행사 내용
|
||||||
|
target_amount BIGINT NULL CHECK (target_amount IS NULL OR target_amount >= 0),
|
||||||
|
result_amount BIGINT NULL, -- 그 주 결과(직접 입력, 쇼핑몰 연결이면 실적 자동)
|
||||||
|
status TEXT NOT NULL DEFAULT '' CHECK (status IN ('', 'done', 'partial', 'miss')),
|
||||||
|
marketplace_code TEXT NOT NULL DEFAULT '', -- 실적 모듈 쇼핑몰 코드(결과 자동)
|
||||||
|
carry_from BIGINT NULL REFERENCES goal_meeting_items(id) ON DELETE SET NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
updated_by TEXT NOT NULL DEFAULT '',
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_week ON goal_meeting_items (week_start, sort_order, id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_carry ON goal_meeting_items (carry_from);
|
||||||
|
|
||||||
|
COMMENT ON TABLE goal_meetings IS '연간 목표 — 주간 회의록(주 = 월~일, week_start = 월요일)';
|
||||||
|
COMMENT ON TABLE goal_meeting_items IS '연간 목표 — 주간 회의록 줄(구역·이번주 할 일·목표/결과 금액·전주 줄 carry_from)';
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_meetings, goal_meeting_items TO project_app;
|
||||||
|
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
SELECT 'project_db 015 goal rect merges/meetings ready' AS status;
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 마이그레이션 016 — 연간 목표: 항목 칸(2열) 묶음
|
||||||
|
-- =====================================================================
|
||||||
|
-- 멱등(idempotent). 칸 하나 추가뿐 — 기존 데이터는 그대로(모두 false = 지금과 같은 화면).
|
||||||
|
--
|
||||||
|
-- goal_rows.label_cont = true → 이 줄의 항목 칸(2열)은 바로 위 줄의 항목 칸에 묶인다(이름은 묶음 첫 줄에만).
|
||||||
|
-- 3열(연간 칸)에서 "아래에 줄 추가"를 하면 새 줄이 같은 항목 칸 안에 들어간다(2열은 하나, 3열부터 줄이 늘어남).
|
||||||
|
--
|
||||||
|
-- 미적용이어도 목표 화면은 동작한다 — 3열 줄 추가만 "마이그레이션 016 필요".
|
||||||
|
--
|
||||||
|
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_016_goal_row_label_groups.sql
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
ALTER TABLE goal_rows ADD COLUMN IF NOT EXISTS label_cont BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
COMMENT ON COLUMN goal_rows.label_cont IS 'true = 항목 칸(2열)이 바로 위 줄 항목 칸에 묶임(이름은 묶음 첫 줄에)';
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
SELECT 'project_db 016 goal row label groups ready' AS status;
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 마이그레이션 017 — 연간 목표: 상·하반기 → 1~4분기
|
||||||
|
-- =====================================================================
|
||||||
|
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음 — CHECK 제약만 바꿔 다시 걸고, 조건 있는 UPDATE/DELETE 만 한다.
|
||||||
|
--
|
||||||
|
-- 분기 글 칸 번호는 예전 반기 칸을 그대로 이어 쓴다(글 옮기기 없음):
|
||||||
|
-- 13 = 1분기(예전 상반기 글이 여기 보임) · 15 = 2분기 · 14 = 3분기(예전 하반기 글) · 16 = 4분기
|
||||||
|
-- 화면 순서: 연간 · 1~3월 · 1분기 · 4~6월 · 2분기 · 7~9월 · 3분기 · 10~12월 · 4분기
|
||||||
|
--
|
||||||
|
-- ① goal_cells.month — 0~14 → 0~16 (2·4분기 칸 저장)
|
||||||
|
-- ② goal_cell_merges — 가로 병합은 같은 분기 월 칸 안에서만. 예전 반기 병합이 분기를 넘으면(예: 2~4월)
|
||||||
|
-- 그 분기 끝 월까지로 줄인다(글은 시작 칸에 그대로). 줄인 뒤 한 칸짜리(가로 1 · 세로 1)가 된 병합은 지운다
|
||||||
|
-- — 병합이 아니게 된 것뿐이고 글(goal_cells)은 지우지 않는다. 분기 칸(13~16)은 세로로만.
|
||||||
|
-- ③ 주간 회의록 기본 줄 이름 "메타(숫자)" → "메타"(store.MEETING_TEMPLATE 와 같게, 그 이름인 줄만)
|
||||||
|
--
|
||||||
|
-- 미적용이어도 목표 화면은 동작한다 — 2·4분기 칸 저장·병합만 "마이그레이션 017 필요".
|
||||||
|
--
|
||||||
|
-- 적용 (1회, 여러 번 돌려도 안전):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_017_goal_quarters.sql
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ① 분기 글 칸 ───────────────────────────────────────────────────────
|
||||||
|
ALTER TABLE goal_cells DROP CONSTRAINT IF EXISTS goal_cells_month_check;
|
||||||
|
ALTER TABLE goal_cells ADD CONSTRAINT goal_cells_month_check CHECK (month BETWEEN 0 AND 16);
|
||||||
|
|
||||||
|
-- ② 병합 — 분기 안으로 ──────────────────────────────────────────────
|
||||||
|
ALTER TABLE goal_cell_merges DROP CONSTRAINT IF EXISTS goal_cell_merges_range;
|
||||||
|
|
||||||
|
UPDATE goal_cell_merges
|
||||||
|
SET span = ((start_month - 1) / 3 + 1) * 3 - start_month + 1
|
||||||
|
WHERE start_month BETWEEN 1 AND 12
|
||||||
|
AND start_month + span - 1 > ((start_month - 1) / 3 + 1) * 3;
|
||||||
|
|
||||||
|
DELETE FROM goal_cell_merges WHERE span = 1 AND row_span = 1;
|
||||||
|
|
||||||
|
ALTER TABLE goal_cell_merges ADD CONSTRAINT goal_cell_merges_range CHECK (
|
||||||
|
span >= 1 AND row_span >= 1 AND span * row_span >= 2
|
||||||
|
AND (
|
||||||
|
(start_month IN (0, 13, 14, 15, 16) AND span = 1)
|
||||||
|
OR (start_month BETWEEN 1 AND 12 AND (start_month - 1) / 3 = (start_month + span - 2) / 3)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
COMMENT ON TABLE goal_cell_merges IS '연간 목표 — 업무 영역 칸 병합(가로: 분기 안 월 칸, 세로: 같은 영역 안 줄 row_span)';
|
||||||
|
|
||||||
|
-- ③ 회의록 줄 이름 ──────────────────────────────────────────────────
|
||||||
|
UPDATE goal_meeting_items SET label = '메타' WHERE label = '메타(숫자)';
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
SELECT 'project_db 017 goal quarters ready' AS status;
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 마이그레이션 018 — 주간 회의록 줄 연결키(line_key)
|
||||||
|
-- =====================================================================
|
||||||
|
-- 멱등(idempotent). DROP TABLE/TRUNCATE/DELETE 없음 — 새 칸을 더하고 비어 있는 칸만 채운다.
|
||||||
|
--
|
||||||
|
-- 왜: 예전엔 "지난주" 줄을 carry_from(만들 때 앞선 회의록 줄 id)으로만 찾았다.
|
||||||
|
-- · 다음 주(9/28)를 먼저 만들고 앞 주(9/21)를 나중에 만들면 9/28 의 carry_from 이 비어 지난주 리뷰가 빠졌다.
|
||||||
|
-- · 한 주를 건너뛰면 몇 주 전 줄이 "지난주"로 보였다.
|
||||||
|
-- · 앞 주를 지웠다 다시 만들면 ON DELETE SET NULL 로 끊긴 연결이 돌아오지 않았다.
|
||||||
|
-- 이제: 줄마다 연결키(line_key) — 회의록을 만들 때 원본 줄의 키를 그대로 이어받고, 새 줄은 새 키.
|
||||||
|
-- "지난주" = 정확히 7일 전 주 회의록에서 같은 키의 줄(생성 순서·이름 변경·순서 이동과 무관).
|
||||||
|
--
|
||||||
|
-- ① line_key UUID 칸 추가
|
||||||
|
-- ② 기존 줄 채우기 — carry_from 사슬을 따라 같은 키를 준다(사슬의 맨 앞 줄 = 키의 뿌리).
|
||||||
|
-- carry_from 이 없는 줄(첫 회의록·줄 추가·앞 주 삭제로 끊긴 줄)은 자기만의 새 키 → 다른 줄에 붙지 않는다.
|
||||||
|
-- 이름(label)으로 추정해 붙이지 않는다(같은 이름 줄·이름 변경 때 다른 줄 결과가 섞일 수 있어서).
|
||||||
|
-- → 9/14 를 원본으로 9/28 을 먼저, 9/21 을 나중에 만든 경우 두 주 줄이 모두 9/14 키를 받아 9/28 ↔ 9/21 이 다시 연결된다.
|
||||||
|
-- → 둘 다 양식(앞선 회의록 없음)으로 만든 주끼리는 사슬이 없어 연결되지 않는다(자동 복구 범위 밖,
|
||||||
|
-- project_db_018b_meeting_line_link_candidates.sql 로 후보를 조회해 사람이 확인 후 따로 연결).
|
||||||
|
-- ③ 한 주 안에서 키가 겹치면(정상 데이터에선 없음) 순서가 뒤인 줄에 새 키 — 한 줄이 두 줄에 붙지 않게
|
||||||
|
-- ④ 기본값(예전 코드 호환) + NOT NULL + (week_start, line_key) UNIQUE
|
||||||
|
--
|
||||||
|
-- 미적용이어도 회의록은 동작한다 — "지난주"는 carry_from 이 정확히 7일 전 주 줄을 가리킬 때만 보인다(역순 생성 연결은 안 됨).
|
||||||
|
--
|
||||||
|
-- 적용 (1회, 여러 번 돌려도 안전, 적용 전 project_db 백업):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_018_meeting_line_keys.sql
|
||||||
|
-- 확인:
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db -c \
|
||||||
|
-- "SELECT count(*) AS total, count(line_key) AS keyed FROM goal_meeting_items;"
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- ① 칸 ─────────────────────────────────────────────────────────────
|
||||||
|
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS line_key UUID;
|
||||||
|
|
||||||
|
-- ② 기존 줄 — carry_from 사슬로 키 채우기(비어 있는 줄만). id 는 만든 순서라 자식 id > 부모 id(순환 방지).
|
||||||
|
-- 뿌리 키 = md5('goal_meeting_item:' || 뿌리 id) — 같은 데이터면 몇 번 돌려도 같은 키.
|
||||||
|
WITH RECURSIVE chain AS (
|
||||||
|
SELECT i.id, COALESCE(i.line_key, md5('goal_meeting_item:' || i.id)::uuid) AS k
|
||||||
|
FROM goal_meeting_items i
|
||||||
|
WHERE i.line_key IS NOT NULL
|
||||||
|
OR i.carry_from IS NULL
|
||||||
|
OR NOT EXISTS (SELECT 1 FROM goal_meeting_items p WHERE p.id = i.carry_from)
|
||||||
|
UNION ALL
|
||||||
|
SELECT c.id, chain.k
|
||||||
|
FROM goal_meeting_items c
|
||||||
|
JOIN chain ON c.carry_from = chain.id
|
||||||
|
WHERE c.line_key IS NULL AND c.id > chain.id
|
||||||
|
)
|
||||||
|
UPDATE goal_meeting_items g
|
||||||
|
SET line_key = chain.k
|
||||||
|
FROM chain
|
||||||
|
WHERE g.id = chain.id AND g.line_key IS NULL;
|
||||||
|
|
||||||
|
-- 사슬에 닿지 않은 줄(있을 수 없지만 안전하게) — 자기만의 키
|
||||||
|
UPDATE goal_meeting_items SET line_key = md5('goal_meeting_item:' || id)::uuid WHERE line_key IS NULL;
|
||||||
|
|
||||||
|
-- ③ 한 주 안 같은 키 — 순서가 뒤인 줄만 새 키(줄 내용·carry_from 은 그대로)
|
||||||
|
UPDATE goal_meeting_items g
|
||||||
|
SET line_key = md5('goal_meeting_item:dup:' || g.id)::uuid
|
||||||
|
FROM (SELECT id, row_number() OVER (PARTITION BY week_start, line_key ORDER BY sort_order, id) AS rn
|
||||||
|
FROM goal_meeting_items) d
|
||||||
|
WHERE g.id = d.id AND d.rn > 1;
|
||||||
|
|
||||||
|
-- ④ 제약 ───────────────────────────────────────────────────────────
|
||||||
|
-- 기본값 — 018 을 먼저 적용하고 코드를 나중에 배포해도(예전 코드는 line_key 를 넣지 않음) 줄 추가가 실패하지 않게 새 키.
|
||||||
|
-- 새 코드는 늘 키를 직접 넣는다(이어받기 = 원본 키, 새 줄 = 새 키). pgcrypto 없이 되는 식(md5 → uuid).
|
||||||
|
ALTER TABLE goal_meeting_items ALTER COLUMN line_key SET DEFAULT md5(random()::text || clock_timestamp()::text)::uuid;
|
||||||
|
ALTER TABLE goal_meeting_items ALTER COLUMN line_key SET NOT NULL;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS uq_goal_meeting_items_week_key ON goal_meeting_items (week_start, line_key);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_goal_meeting_items_key ON goal_meeting_items (line_key);
|
||||||
|
|
||||||
|
COMMENT ON COLUMN goal_meeting_items.line_key IS
|
||||||
|
'주가 바뀌어도 같은 줄을 가리키는 연결키 — 회의록을 만들 때 원본 줄 키를 이어받음. 지난주 = 7일 전 주의 같은 키 줄';
|
||||||
|
COMMENT ON COLUMN goal_meeting_items.carry_from IS
|
||||||
|
'만들 때 이어받은 앞선 회의록 줄(이력). 화면의 지난주 연결은 line_key(018) 로 찾는다';
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
|
|
||||||
|
SELECT 'project_db 018 meeting line keys ready' AS status,
|
||||||
|
(SELECT count(*) FROM goal_meeting_items) AS items,
|
||||||
|
(SELECT count(*) FROM goal_meeting_items WHERE line_key IS NULL) AS missing_keys;
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- =====================================================================
|
||||||
|
-- project_db 018b — 주간 회의록 "지난주" 연결 후보 조회 (읽기 전용, 자동 적용 없음)
|
||||||
|
-- =====================================================================
|
||||||
|
-- 018 은 carry_from 사슬이 있는 줄만 자동으로 이어 준다. 앞선 회의록 없이 양식으로 만든 주끼리
|
||||||
|
-- (예: 9/28 을 먼저 양식으로 만들고 9/21 도 양식으로 만든 경우)는 사슬이 없어 연결되지 않는다.
|
||||||
|
-- 이 조회는 그런 주 쌍(정확히 7일 차이)에서 **구역+줄 이름이 양쪽 주에 각각 한 줄씩만 있는** 줄만 후보로 보여 준다.
|
||||||
|
-- 같은 구역에 같은 이름이 두 줄 이상이거나 이름이 빈 줄, 이미 연결된 줄은 후보에서 뺀다(추정 연결 금지).
|
||||||
|
--
|
||||||
|
-- 실행(조회만):
|
||||||
|
-- docker exec -i postgres-db psql -U postgres -d project_db \
|
||||||
|
-- < scripts/sql/project_db_018b_meeting_line_link_candidates.sql
|
||||||
|
--
|
||||||
|
-- 후보를 사람이 확인한 뒤에만, 한 쌍씩 아래처럼 연결한다(다음 주 줄이 앞 주 줄의 키를 받음). 운영 적용은 별도 승인·백업 후.
|
||||||
|
-- BEGIN;
|
||||||
|
-- UPDATE goal_meeting_items SET line_key = (SELECT line_key FROM goal_meeting_items WHERE id = <앞 주 줄 id>)
|
||||||
|
-- WHERE id = <다음 주 줄 id>
|
||||||
|
-- AND NOT EXISTS (SELECT 1 FROM goal_meeting_items x
|
||||||
|
-- WHERE x.week_start = goal_meeting_items.week_start
|
||||||
|
-- AND x.line_key = (SELECT line_key FROM goal_meeting_items WHERE id = <앞 주 줄 id>));
|
||||||
|
-- -- 다음 주 다음(+14일) 회의록이 그 줄을 예전 키로 이어받았다면 그 줄도 같은 키로 맞춰야 사슬이 이어진다 — 결과 확인 후 COMMIT
|
||||||
|
-- COMMIT;
|
||||||
|
-- =====================================================================
|
||||||
|
|
||||||
|
\set ON_ERROR_STOP on
|
||||||
|
\connect project_db
|
||||||
|
|
||||||
|
WITH items AS (
|
||||||
|
SELECT i.*, count(*) OVER (PARTITION BY i.week_start, i.section, i.label) AS same_name
|
||||||
|
FROM goal_meeting_items i
|
||||||
|
WHERE btrim(i.label) <> ''
|
||||||
|
),
|
||||||
|
pairs AS (
|
||||||
|
SELECT p.week_start AS prev_week, n.week_start AS week,
|
||||||
|
n.section, n.label, p.id AS prev_item_id, n.id AS item_id
|
||||||
|
FROM items n
|
||||||
|
JOIN items p ON p.week_start = n.week_start - 7 AND p.section = n.section AND p.label = n.label
|
||||||
|
WHERE n.same_name = 1 AND p.same_name = 1
|
||||||
|
AND n.line_key <> p.line_key
|
||||||
|
-- 이미 이 앞 주에 같은 키 줄이 있는 다음 주 줄(연결됨)은 빼고, 앞 주 줄이 다른 줄과 이미 이어진 것도 뺀다
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM goal_meeting_items x WHERE x.week_start = p.week_start AND x.line_key = n.line_key)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM goal_meeting_items y WHERE y.week_start = n.week_start AND y.line_key = p.line_key)
|
||||||
|
)
|
||||||
|
SELECT prev_week, week, section, label, prev_item_id, item_id
|
||||||
|
FROM pairs
|
||||||
|
ORDER BY week, section, label;
|
||||||
@@ -13,3 +13,15 @@ node tests/js/box_calc_ui.test.js
|
|||||||
```
|
```
|
||||||
|
|
||||||
성공하면 마지막 줄에 `ALL PASS`, 실패하면 실패한 항목명이 출력되고 종료코드 1.
|
성공하면 마지막 줄에 `ALL PASS`, 실패하면 실패한 항목명이 출력되고 종료코드 1.
|
||||||
|
|
||||||
|
# 연간 목표·주간 회의록 UI 테스트 (jsdom)
|
||||||
|
|
||||||
|
`goals.html`·`goal_meeting.html` + `static/project.js` — 칸 저장 직렬화·늦은 응답·503·초안 보호·구조 변경 중단·이번주 실적 %·
|
||||||
|
실적 미확인 표시·⋮ 메뉴(키보드·터치 클릭)·매출 갱신 안내를 가짜 서버(지연·실패를 직접 만듦)로 검증한다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python tests/js/render_goals.py # → tests/js/.out/goals_*.html · meeting_*.html
|
||||||
|
node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom 또는 NODE_PATH)
|
||||||
|
```
|
||||||
|
|
||||||
|
실제 브라우저 레이아웃·입력기·터치 기기는 아니다(그건 헤드리스 크롬으로 따로 확인).
|
||||||
|
|||||||
@@ -0,0 +1,664 @@
|
|||||||
|
// 연간 목표(goals.html)·주간 회의록(goal_meeting.html) + static/project.js UI 회귀 테스트 — jsdom.
|
||||||
|
// 서버는 가짜(fetch 대체)로 두고 지연(deferred)·순서 역전·503·연속 입력을 직접 만든다. 실제 브라우저 레이아웃·입력기·터치 기기는 아니다.
|
||||||
|
//
|
||||||
|
// python tests/js/render_goals.py # 템플릿 렌더 → tests/js/.out/goals_*.html · meeting_*.html
|
||||||
|
// npm install jsdom # (최초 1회, 또는 NODE_PATH 로 jsdom 이 있는 node_modules 지정)
|
||||||
|
// node tests/js/goals_meeting_ui.test.js
|
||||||
|
//
|
||||||
|
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const { JSDOM, VirtualConsole } = require("jsdom");
|
||||||
|
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 180000);
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, "..", "..");
|
||||||
|
const OUT = path.join(__dirname, ".out");
|
||||||
|
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||||
|
const PAGE = {};
|
||||||
|
["goals_admin", "goals_ro", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
|
||||||
|
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
|
||||||
|
});
|
||||||
|
const GOALS_URL = "http://localhost/project/goals/2026";
|
||||||
|
const MEET_URL = "http://localhost/project/goals/2026/meetings/9?week=2026-09-28";
|
||||||
|
|
||||||
|
const fails = [];
|
||||||
|
function check(name, cond, extra) {
|
||||||
|
if (cond) console.log("PASS " + name);
|
||||||
|
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||||
|
}
|
||||||
|
function deferred() {
|
||||||
|
let resolve, reject;
|
||||||
|
const p = new Promise(function (a, b) { resolve = a; reject = b; });
|
||||||
|
return { promise: p, resolve: resolve, reject: reject };
|
||||||
|
}
|
||||||
|
function settle(n) {
|
||||||
|
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 40)) return r(); setImmediate(spin); })(); });
|
||||||
|
}
|
||||||
|
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
||||||
|
const unhandled = [];
|
||||||
|
process.on("unhandledRejection", function (e) { unhandled.push(String(e && e.message || e)); });
|
||||||
|
|
||||||
|
// env.route(method, re, fn(url, body, call)) — fn 이 {status, body, text} 또는 "NETWORK" 를 돌려준다(Promise 가능)
|
||||||
|
function makeEnv(html, url, opts) {
|
||||||
|
opts = opts || {};
|
||||||
|
const vc = new VirtualConsole();
|
||||||
|
const env = { calls: [], routes: [], navigations: 0, toasts: [], prompts: [], inflight: {}, maxInflight: {} };
|
||||||
|
vc.on("jsdomError", function (e) { if (/navigation/i.test(String(e && e.message))) env.navigations++; });
|
||||||
|
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: url, virtualConsole: vc });
|
||||||
|
const w = dom.window, d = w.document;
|
||||||
|
env.w = w; env.d = d;
|
||||||
|
w.__PJ_TEST__ = true;
|
||||||
|
w.console.error = function () {};
|
||||||
|
w.scrollTo = function () {};
|
||||||
|
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
|
||||||
|
w.erpConfirm = function () { return Promise.resolve(true); };
|
||||||
|
w.erpPrompt = function (msg, def) { env.prompts.push(msg); return Promise.resolve(opts.promptAnswer != null ? opts.promptAnswer : "새 이름"); };
|
||||||
|
w.erpAlert = function () {};
|
||||||
|
if (opts.storage) Object.keys(opts.storage).forEach(function (k) { w.localStorage.setItem(k, opts.storage[k]); });
|
||||||
|
if (opts.session) Object.keys(opts.session).forEach(function (k) { w.sessionStorage.setItem(k, opts.session[k]); });
|
||||||
|
env.route = function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); };
|
||||||
|
w.fetch = async function (u, o) {
|
||||||
|
const method = (o && o.method) || "GET";
|
||||||
|
let body = o && o.body;
|
||||||
|
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
|
||||||
|
const call = { method: method, url: String(u), body: body, keepalive: !!(o && o.keepalive), done: false };
|
||||||
|
env.calls.push(call);
|
||||||
|
const key = method + " " + String(u).replace(/^https?:\/\/[^/]+/, "");
|
||||||
|
env.inflight[key] = (env.inflight[key] || 0) + 1;
|
||||||
|
env.maxInflight[key] = Math.max(env.maxInflight[key] || 0, env.inflight[key]);
|
||||||
|
try {
|
||||||
|
for (const r of env.routes) {
|
||||||
|
if (r.method === method && r.re.test(String(u))) {
|
||||||
|
const out = await r.fn(String(u), body, call);
|
||||||
|
if (out === "NETWORK") throw new TypeError("Failed to fetch");
|
||||||
|
const status = out.status || 200;
|
||||||
|
return { ok: status < 400, status: status, statusText: "x",
|
||||||
|
json: async function () { return out.body || {}; }, text: async function () { return out.text || ""; } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; }, text: async function () { return ""; } };
|
||||||
|
} finally {
|
||||||
|
env.inflight[key]--;
|
||||||
|
call.done = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
env.puts = function (re) { return env.calls.filter(function (c) { return c.method === "PUT" && re.test(c.url); }); };
|
||||||
|
env.toastText = function () { const t = d.querySelector(".erp-toast"); return t ? t.textContent : ""; };
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
async function boot(env) {
|
||||||
|
if (env.d.readyState === "loading") await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
|
||||||
|
env.w.eval(JS);
|
||||||
|
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||||
|
await settle();
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
function type(env, node, value) {
|
||||||
|
node.value = value;
|
||||||
|
node.dispatchEvent(new env.w.Event("input", { bubbles: true }));
|
||||||
|
}
|
||||||
|
function fire(env, node, name) { node.dispatchEvent(new env.w.Event(name, { bubbles: name !== "blur" && name !== "focus" })); }
|
||||||
|
function key(env, node, k, extra) {
|
||||||
|
const e = new env.w.KeyboardEvent("keydown", Object.assign({ key: k, bubbles: true, cancelable: true }, extra || {}));
|
||||||
|
node.dispatchEvent(e);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
// 블록 하나가 예외로 멈춰도 나머지 블록은 계속(예외는 FAIL 로)
|
||||||
|
async function section(fn) {
|
||||||
|
try { await fn(); } catch (e) { check("블록 예외 없음: " + String(e && e.message || e).slice(0, 120), false); }
|
||||||
|
}
|
||||||
|
function itemLabel(b) { return (b.querySelector(".pj-ctxmenu-label") || b).textContent.trim(); }
|
||||||
|
function unload(env) {
|
||||||
|
const e = new env.w.Event("beforeunload", { cancelable: true });
|
||||||
|
env.w.dispatchEvent(e);
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 가짜 서버 — 목표 표(글 칸 상태를 기억해 화면 GET 에 반영) ───────────────
|
||||||
|
function goalsServer(env, st) {
|
||||||
|
st = Object.assign({ cells: {}, areaAdded: false, cellHook: null, metricHook: null, getHook: null }, st || {});
|
||||||
|
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
|
||||||
|
env.route("PUT", /\/project\/api\/goals\/rows\/\d+\/cells\/\d+$/, async function (u, body, call) {
|
||||||
|
const m = u.match(/rows\/(\d+)\/cells\/(\d+)/);
|
||||||
|
if (st.cellHook) { const r = await st.cellHook(u, body, call); if (r) return r; }
|
||||||
|
st.cells[m[1] + ":" + m[2]] = body.body;
|
||||||
|
return { body: { ok: true } };
|
||||||
|
});
|
||||||
|
env.route("PUT", /\/project\/api\/goals\/2026\/metrics$/, async function (u, body, call) {
|
||||||
|
if (st.metricHook) { const r = await st.metricHook(u, body, call); if (r) return r; }
|
||||||
|
const n = Number(String(body.value).replace(/[,\s]/g, ""));
|
||||||
|
st.metric = String(body.value);
|
||||||
|
return { body: { ok: true, label: body.value === "" ? "" : n.toLocaleString("en-US") } };
|
||||||
|
});
|
||||||
|
env.route("POST", /\/project\/api\/goals\/2026\/areas$/, function () { st.areaAdded = true; return { body: { ok: true } }; });
|
||||||
|
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/rows$/, function () { return { status: 201, body: { ok: true } }; });
|
||||||
|
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/move$/, function () { return { body: { ok: true } }; });
|
||||||
|
env.route("POST", /\/project\/api\/goals\/areas\/\d+\/merge$/, function () { st.merged = true; return { body: { ok: true, row_id: 10, start: 1 } }; });
|
||||||
|
env.route("GET", /\/project\/goals\/2026$/, async function () {
|
||||||
|
if (st.getHook) await st.getHook();
|
||||||
|
st.gets = (st.gets || 0) + 1;
|
||||||
|
let html = PAGE.goals_admin.replace(/(<textarea class="pj-goal-text"[^>]*data-row="(\d+)" data-month="(\d+)"[^>]*>)([\s\S]*?)(<\/textarea>)/g,
|
||||||
|
function (all, open, row, month, text, close) {
|
||||||
|
const k = row + ":" + month;
|
||||||
|
return open + (k in st.cells ? st.cells[k].replace(/&/g, "&").replace(/</g, "<") : text) + close;
|
||||||
|
});
|
||||||
|
if (st.areaAdded) {
|
||||||
|
html = html.replace(/(<\/tbody>\s*)(<\/table>)/, '$1<tbody class="pj-goal-area" data-area-id="3" data-color="" style="--goal-bg: #fff">' +
|
||||||
|
'<tr data-row-id="30"><th class="pj-goal-c1 pj-goal-area-name" rowspan="1"><span class="pj-goal-area-text">새 영역</span></th>' +
|
||||||
|
'<th class="pj-goal-c2 pj-goal-row-label"><span class="pj-goal-row-text"></span></th>' +
|
||||||
|
'<td class="pj-goal-texttd pj-goal-year-col" data-month="0" data-span="1" data-rspan="1"><textarea class="pj-goal-text" rows="1" data-row="30" data-month="0"></textarea></td>' +
|
||||||
|
"</tr></tbody>$2");
|
||||||
|
}
|
||||||
|
return { text: html };
|
||||||
|
});
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 가짜 서버 — 회의록 ────────────────────────────────────────────────
|
||||||
|
function meetServer(env, st) {
|
||||||
|
st = Object.assign({ items: {}, head: {}, itemHook: null, headHook: null, getHook: null, syncHook: null, page: PAGE.meeting_admin }, st || {});
|
||||||
|
env.route("GET", /\/project\/api\//, function () { return { body: {} }; });
|
||||||
|
const amount = function (v) { if (v === "" || v == null) return null; return Number(String(v).replace(/[,\s원]/g, "")); };
|
||||||
|
env.route("PUT", /\/project\/api\/goals\/meeting-items\/\d+$/, async function (u, body, call) {
|
||||||
|
const id = Number(u.match(/meeting-items\/(\d+)/)[1]);
|
||||||
|
if (st.itemHook) { const r = await st.itemHook(id, body, call); if (r) return r; }
|
||||||
|
const it = st.items[id] = Object.assign(st.items[id] || { id: id }, {});
|
||||||
|
Object.keys(body).forEach(function (k) { it[k] = /amount$/.test(k) ? amount(body[k]) : body[k]; });
|
||||||
|
return { body: { ok: true, item: Object.assign({ target_amount: null, result_amount: null }, it) } };
|
||||||
|
});
|
||||||
|
env.route("PUT", /\/project\/api\/goals\/meetings\/2026-09-28$/, async function (u, body, call) {
|
||||||
|
if (st.headHook) { const r = await st.headHook(body, call); if (r) return r; }
|
||||||
|
Object.assign(st.head, body);
|
||||||
|
const out = { ok: true };
|
||||||
|
if ("week_target" in body) { out.week_target = amount(body.week_target); st.head.week_target = out.week_target; }
|
||||||
|
return { body: out };
|
||||||
|
});
|
||||||
|
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/items$/, function () { return { status: 201, body: { ok: true, id: 9 } }; });
|
||||||
|
env.route("POST", /\/project\/api\/goals\/meeting-items\/\d+\/move$/, function () { return { body: { ok: true } }; });
|
||||||
|
env.route("GET", /\/project\/goals\/2026\/meetings\/9/, async function () {
|
||||||
|
st.gets = (st.gets || 0) + 1;
|
||||||
|
const page = st.page;
|
||||||
|
if (st.getHook) { const r = await st.getHook(); if (r) return r; }
|
||||||
|
return { text: page };
|
||||||
|
});
|
||||||
|
env.route("POST", /\/performance\/api\/sync$/, async function (u, body) {
|
||||||
|
st.syncCalls = (st.syncCalls || 0) + 1;
|
||||||
|
if (st.syncHook) return st.syncHook(body);
|
||||||
|
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to, shops: [{ name: "쿠팡", state: "done", active: true }], overall: {} } } };
|
||||||
|
});
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
|
||||||
|
(async function () {
|
||||||
|
// ════════════════════ [1] 회의록 글 — A→B 연속 입력과 늦은 A 응답 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const gate = deferred();
|
||||||
|
const st = meetServer(env, { itemHook: async function (id, body, call) { if (body.content === "draft A") await gate.promise; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "draft A"); ta.blur();
|
||||||
|
await settle();
|
||||||
|
ta.focus(); type(env, ta, "draft B");
|
||||||
|
await settle();
|
||||||
|
check("[1] A 진행 중엔 같은 칸 두 번째 요청을 보내지 않음(직렬화)", env.puts(/meeting-items\/1$/).length === 1);
|
||||||
|
gate.resolve();
|
||||||
|
await wait(900); await settle();
|
||||||
|
const puts = env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; });
|
||||||
|
check("[1] A 응답 뒤 B 가 뒤이어 저장됨(PUT A→B)", JSON.stringify(puts) === JSON.stringify(["draft A", "draft B"]), puts);
|
||||||
|
check("[1] 최종 서버 값 = B", st.items[1].content === "draft B", st.items[1]);
|
||||||
|
check("[1] 화면 = B", ta.value === "draft B");
|
||||||
|
check("[1] 같은 칸 동시 요청 최대 1", env.maxInflight["PUT /project/api/goals/meeting-items/1"] === 1, env.maxInflight);
|
||||||
|
const e = unload(env);
|
||||||
|
check("[1] 저장 끝난 뒤 페이지 떠남 = 경고 없음", !e.defaultPrevented);
|
||||||
|
});
|
||||||
|
// 지연·중복 blur·빠른 연속 입력 — 응답 순서와 무관하게 최신 값이 남는다
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const gates = [];
|
||||||
|
const st = meetServer(env, { itemHook: async function () { const g = deferred(); gates.push(g); await g.promise; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "x1"); ta.blur(); fire(env, ta, "blur"); fire(env, ta, "blur");
|
||||||
|
ta.focus(); type(env, ta, "x12"); type(env, ta, "x123"); ta.blur();
|
||||||
|
await settle();
|
||||||
|
check("[1b] 중복 blur·연속 입력에도 진행 중 요청 1개", env.puts(/meeting-items\/1$/).length === 1);
|
||||||
|
gates[0].resolve(); await settle();
|
||||||
|
check("[1b] 첫 응답 뒤 최신 값으로 한 번 더", env.puts(/meeting-items\/1$/).length === 2 && env.puts(/meeting-items\/1$/)[1].body.content === "x123",
|
||||||
|
env.puts(/meeting-items\/1$/).map(function (c) { return c.body.content; }));
|
||||||
|
gates[1].resolve(); await settle();
|
||||||
|
await wait(50); await settle();
|
||||||
|
check("[1b] 최종 서버 값 = 마지막 입력", st.items[1].content === "x123" && env.puts(/meeting-items\/1$/).length === 2, st.items[1]);
|
||||||
|
});
|
||||||
|
// 저장 실패 → dirty·초안 유지, 페이지 떠남 = keepalive 재전송 + 이탈 경고 + 초안 백업, 다음에 열면 되살림
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
let fail = true;
|
||||||
|
const st = meetServer(env, { itemHook: function () { if (fail) return { status: 503, body: { detail: "temporary" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "important"); ta.blur();
|
||||||
|
await settle();
|
||||||
|
check("[1c] 실패해도 글 그대로", ta.value === "important");
|
||||||
|
check("[1c] 실패 표시(빨간 테두리)", ta.closest("td").classList.contains("is-save-failed"));
|
||||||
|
check("[1c] 실패 안내 토스트", /저장 실패/.test(env.toastText()), env.toastText());
|
||||||
|
const draft = JSON.parse(env.w.localStorage.getItem("pj_draft:meet:item:1:content") || "null");
|
||||||
|
check("[1c] 초안 백업(localStorage)", draft && draft.draft === "important" && draft.base === "original", draft);
|
||||||
|
const before = env.puts(/meeting-items\/1$/).length;
|
||||||
|
const e = unload(env);
|
||||||
|
await settle();
|
||||||
|
const after = env.puts(/meeting-items\/1$/);
|
||||||
|
check("[1c] 페이지 떠남 — 실패한 칸을 keepalive 로 다시 보냄", after.length === before + 1 && after[after.length - 1].keepalive && after[after.length - 1].body.content === "important",
|
||||||
|
after.map(function (c) { return [c.body.content, c.keepalive]; }));
|
||||||
|
check("[1c] 페이지 떠남 — 실패 칸이 있으면 이탈 경고", e.defaultPrevented === true);
|
||||||
|
// 다음에 열기 — 서버엔 아직 original(keepalive 도 실패) → 초안을 되살려 다시 저장
|
||||||
|
const env2 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": JSON.stringify(draft) } });
|
||||||
|
const st2 = meetServer(env2);
|
||||||
|
await boot(env2);
|
||||||
|
const ta2 = env2.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
check("[1c] 다시 열면 초안 되살림", ta2.value === "important");
|
||||||
|
await wait(900); await settle();
|
||||||
|
check("[1c] 되살린 초안 자동 저장", st2.items[1] && st2.items[1].content === "important", st2.items[1]);
|
||||||
|
check("[1c] 저장 뒤 초안 백업 지움", env2.w.localStorage.getItem("pj_draft:meet:item:1:content") === null);
|
||||||
|
// 다른 곳에서 바뀐 칸(base ≠ 서버 값) — 되살리지 않는다
|
||||||
|
const stale = JSON.stringify({ base: "someone else", draft: "old draft", at: Date.now() });
|
||||||
|
const env3 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": stale } });
|
||||||
|
meetServer(env3);
|
||||||
|
await boot(env3);
|
||||||
|
check("[1c] 서버 값이 바뀐 칸은 초안을 덮어쓰지 않음", env3.d.querySelector('tr[data-item="1"] textarea.pj-meet-text').value === "original");
|
||||||
|
fail = false; void st;
|
||||||
|
});
|
||||||
|
// 진행 중 저장이 있으면 줄 작업(위로)은 그 저장이 끝난 뒤에, 저장 실패면 줄 작업을 하지 않는다
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const gate = deferred();
|
||||||
|
let fail = false;
|
||||||
|
meetServer(env, { itemHook: async function (id, body) { if ("content" in body) { await gate.promise; if (fail) return { status: 503, body: { detail: "x" } }; } } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "pending text"); ta.blur();
|
||||||
|
await settle();
|
||||||
|
fail = true;
|
||||||
|
env.d.querySelector('tr[data-item="1"] th.pj-meet-c-label').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||||
|
const up = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return itemLabel(b) === "위로"; });
|
||||||
|
up.click();
|
||||||
|
await settle();
|
||||||
|
check("[1d] 저장 진행 중엔 줄 이동 요청을 보내지 않음", !env.calls.some(function (c) { return /\/move$/.test(c.url); }));
|
||||||
|
gate.resolve();
|
||||||
|
await settle(); await wait(20); await settle();
|
||||||
|
check("[1d] 저장 실패 → 줄 이동 취소(글 유지, 새로고침 없음)", !env.calls.some(function (c) { return /\/move$/.test(c.url); }) && ta.value === "pending text" && env.navigations === 0,
|
||||||
|
{ nav: env.navigations });
|
||||||
|
});
|
||||||
|
|
||||||
|
// ════════════════════ [2] 숫자 — 늦은 응답이 최신 입력을 덮지 않음 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||||
|
const gates = [];
|
||||||
|
const st = goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { const g = deferred(); gates.push(g); await g.promise; } } });
|
||||||
|
await boot(env);
|
||||||
|
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
|
||||||
|
inp.focus(); inp.value = "200"; fire(env, inp, "change"); inp.blur();
|
||||||
|
await settle();
|
||||||
|
inp.focus(); type(env, inp, "300");
|
||||||
|
gates[0].resolve();
|
||||||
|
await settle();
|
||||||
|
check("[2] 늦은 200 응답 뒤에도 입력 중인 300 유지", inp.value === "300", inp.value);
|
||||||
|
inp.blur();
|
||||||
|
await settle(); await wait(10); await settle();
|
||||||
|
const vals = env.puts(/metrics$/).map(function (c) { return c.body.value; });
|
||||||
|
check("[2] 300 확정 → 최종 서버 값 300(요청 순서 200→300)", st.metric === "300" && JSON.stringify(vals) === '["200","300"]', vals);
|
||||||
|
check("[2] 같은 칸 동시 요청 최대 1(순서 역전 불가)", env.maxInflight["PUT /project/api/goals/2026/metrics"] === 1);
|
||||||
|
check("[2] 확정 뒤 서버 표기", inp.value === "300");
|
||||||
|
});
|
||||||
|
await section(async function () { // 실패 응답 — 요청 뒤 새로 입력한 값을 예전 값으로 되돌리지 않는다 / 그대로면 입력 유지 + 실패 표시, Esc = 저장된 값
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||||
|
const gate = deferred();
|
||||||
|
goalsServer(env, { metricHook: async function (u, body) { if (body.value === "200") { await gate.promise; return { status: 503, body: { detail: "down" } }; } } });
|
||||||
|
await boot(env);
|
||||||
|
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
|
||||||
|
inp.focus(); inp.value = "200"; inp.blur();
|
||||||
|
await settle();
|
||||||
|
inp.focus(); type(env, inp, "300");
|
||||||
|
gate.resolve(); await settle();
|
||||||
|
check("[2b] 200 실패 응답이 새 입력 300 을 되돌리지 않음", inp.value === "300", inp.value);
|
||||||
|
type(env, inp, "200"); inp.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[2b] 실패한 값 그대로면 입력 유지 + 실패 표시", inp.value === "200" && inp.parentElement.classList.contains("is-save-failed"));
|
||||||
|
const e = unload(env);
|
||||||
|
check("[2b] 미저장 숫자 칸이 있으면 이탈 경고", e.defaultPrevented === true);
|
||||||
|
inp.focus(); key(env, inp, "Escape");
|
||||||
|
check("[2b] Esc = 저장된 값(100)으로", inp.value === "100", inp.value);
|
||||||
|
});
|
||||||
|
await section(async function () { // 회의록 정량 목표·지난주 결과 — 늦은 응답이 새 초안을 덮지 않음
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const gate = deferred();
|
||||||
|
const st = meetServer(env, { itemHook: async function (id, body) { if (body.target_amount === "200" || body.result_amount === "70") await gate.promise; } });
|
||||||
|
await boot(env);
|
||||||
|
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
|
||||||
|
tin.focus(); tin.value = "200"; tin.blur(); await settle();
|
||||||
|
tin.focus(); type(env, tin, "300");
|
||||||
|
const rin = env.d.querySelector('tr[data-item="2"] input[data-field="result_amount"]');
|
||||||
|
rin.focus(); rin.value = "70"; rin.blur(); await settle();
|
||||||
|
rin.focus(); type(env, rin, "75");
|
||||||
|
gate.resolve(); await settle();
|
||||||
|
check("[2c] 정량 목표 늦은 응답이 300 초안 유지", tin.value === "300", tin.value);
|
||||||
|
check("[2c] 지난주 결과 늦은 응답이 75 초안 유지", rin.value === "75", rin.value);
|
||||||
|
tin.blur(); rin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[2c] 최종 서버 정량 목표 300 · 지난주 결과(7일 전 주 줄 902) 75", st.items[1].target_amount === 300 && st.items[902].result_amount === 75, st.items);
|
||||||
|
check("[2c] 지난주 달성률 = 75/200", env.d.querySelector('tr[data-item="2"] [data-rate]').textContent.trim() === "37.5%",
|
||||||
|
env.d.querySelector('tr[data-item="2"] [data-rate]').textContent);
|
||||||
|
});
|
||||||
|
await section(async function () { // 금주 목표 저장 — 새로고침하지 않고 숫자 칸만 다시(다른 칸의 미저장 글 보존)
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const st = meetServer(env, { itemHook: function (id, body) { if ("content" in body) return { status: 503, body: { detail: "x" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
const gets0 = st.gets || 0;
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "unsaved note");
|
||||||
|
const tgt = env.d.getElementById("pj-meet-target");
|
||||||
|
tgt.focus(); tgt.value = "2,000"; tgt.blur();
|
||||||
|
await settle(); await wait(10); await settle();
|
||||||
|
check("[2d] 금주 목표 저장 = 서버 확정값", st.head.week_target === 2000 && tgt.value === "2,000", st.head);
|
||||||
|
check("[2d] 페이지 새로고침 없음", env.navigations === 0);
|
||||||
|
check("[2d] 숫자 칸만 다시 받음(GET 1회 더)", (st.gets || 0) === gets0 + 1, st.gets);
|
||||||
|
check("[2d] 다른 칸 미저장 글 유지", ta.value === "unsaved note");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||||
|
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "temporary save failure" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('textarea.pj-goal-text[data-row="10"][data-month="1"]');
|
||||||
|
ta.focus(); type(env, ta, "unsaved important plan");
|
||||||
|
env.d.getElementById("pj-goal-area-add").click();
|
||||||
|
await settle(); await wait(20); await settle();
|
||||||
|
check("[3] 글 저장 실패 → 영역 추가 요청 안 보냄", !env.calls.some(function (c) { return c.method === "POST" && /\/areas$/.test(c.url); }),
|
||||||
|
env.calls.map(function (c) { return c.method + " " + c.url; }));
|
||||||
|
check("[3] 표를 다시 받지 않음", !st.gets);
|
||||||
|
check("[3] 미저장 계획 그대로", env.d.querySelector('textarea.pj-goal-text[data-row="10"][data-month="1"]').value === "unsaved important plan");
|
||||||
|
check("[3] 실패 안내", /저장/.test(env.toastText()), env.toastText());
|
||||||
|
});
|
||||||
|
await section(async function () { // 진행 중 저장 → 그 저장이 끝난 뒤에 영역 추가, 성공하면 표 교체(새 영역 보임, 저장된 글 유지)
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||||
|
const gate = deferred();
|
||||||
|
const st = goalsServer(env, { cellHook: async function () { await gate.promise; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('textarea.pj-goal-text[data-row="10"][data-month="1"]');
|
||||||
|
ta.focus(); type(env, ta, "plan v2"); ta.blur();
|
||||||
|
await settle();
|
||||||
|
env.d.getElementById("pj-goal-area-add").click();
|
||||||
|
await settle();
|
||||||
|
check("[3b] 진행 중 저장이 끝나기 전엔 영역 추가 안 보냄", !env.calls.some(function (c) { return c.method === "POST"; }));
|
||||||
|
gate.resolve();
|
||||||
|
await settle(); await wait(20); await settle();
|
||||||
|
const order = env.calls.filter(function (c) { return c.method !== "GET" || /goals\/2026$/.test(c.url); }).map(function (c) { return c.method + " " + c.url.replace(/^https?:\/\/[^/]+/, ""); });
|
||||||
|
check("[3b] 순서: 글 PUT → 영역 POST → 표 GET", order.join(" | ") === "PUT /project/api/goals/rows/10/cells/1 | POST /project/api/goals/2026/areas | GET /project/goals/2026", order);
|
||||||
|
check("[3b] 새 영역이 그 자리에 보임(새로고침 없음)", !!env.d.querySelector('tbody.pj-goal-area[data-area-id="3"]') && env.navigations === 0);
|
||||||
|
check("[3b] 저장된 글 유지", env.d.querySelector('textarea.pj-goal-text[data-row="10"][data-month="1"]').value === "plan v2");
|
||||||
|
});
|
||||||
|
await section(async function () { // 표를 받는 사이에 새로 입력 → 저장 후 다시 받아 교체(입력 유실 없음)
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||||
|
const gate = deferred();
|
||||||
|
let first = true;
|
||||||
|
const st = goalsServer(env, { getHook: async function () { if (first) { first = false; await gate.promise; } } });
|
||||||
|
await boot(env);
|
||||||
|
env.d.getElementById("pj-goal-area-add").click();
|
||||||
|
await settle();
|
||||||
|
const ta = env.d.querySelector('textarea.pj-goal-text[data-row="11"][data-month="1"]');
|
||||||
|
ta.focus(); type(env, ta, "typed during refresh");
|
||||||
|
gate.resolve();
|
||||||
|
await settle(); await wait(30); await settle();
|
||||||
|
check("[3c] 받는 사이 입력한 글 저장됨", st.cells["11:1"] === "typed during refresh", st.cells);
|
||||||
|
check("[3c] 교체된 표에도 그 글", env.d.querySelector('textarea.pj-goal-text[data-row="11"][data-month="1"]').value === "typed during refresh");
|
||||||
|
check("[3c] 표를 다시 받음(2회)", st.gets === 2, st.gets);
|
||||||
|
});
|
||||||
|
await section(async function () { // 병합 — 저장 실패면 병합 요청 안 보냄
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||||
|
const st = goalsServer(env, { cellHook: function () { return { status: 503, body: { detail: "x" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('textarea.pj-goal-text[data-row="10"][data-month="1"]');
|
||||||
|
ta.focus(); type(env, ta, "draft before merge");
|
||||||
|
const a = env.d.querySelector('td.pj-goal-texttd[data-month="1"]'), b = env.d.querySelector('tr[data-row-id="10"] td.pj-goal-texttd[data-month="2"]');
|
||||||
|
a.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0 }));
|
||||||
|
b.dispatchEvent(new env.w.MouseEvent("mouseover", { bubbles: true }));
|
||||||
|
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||||
|
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }));
|
||||||
|
const merge = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(function (x) { return /셀 병합/.test(itemLabel(x)); });
|
||||||
|
check("[3d] 끌어 고른 뒤 우클릭 → 셀 병합 메뉴(기존 동작)", !!merge);
|
||||||
|
if (merge) merge.click();
|
||||||
|
await settle(); await wait(20); await settle();
|
||||||
|
check("[3d] 저장 실패 → 병합 요청 안 보냄, 글 유지", !st.merged && ta.value === "draft before merge");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ════════════════════ [7] 정량 목표 저장 → 이번주 실적 % 즉시 갱신, 다시 그리기와 엇갈려도 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||||
|
const st = meetServer(env);
|
||||||
|
await boot(env);
|
||||||
|
const slot = function () { return env.d.querySelector('tr[data-item="1"] .pj-meet-week-slot').textContent.trim(); };
|
||||||
|
check("[7] 처음 = 실적 100 · 목표 100 → 100%", /100%/.test(slot()), slot());
|
||||||
|
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
|
||||||
|
tin.focus(); tin.value = "200"; tin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 목표 200 저장 → 50%", /· 50%$/.test(slot()), slot());
|
||||||
|
tin.focus(); tin.value = "0"; tin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 목표 0 → % 없음", slot() === "이번주 실적 100", slot());
|
||||||
|
tin.focus(); tin.value = ""; tin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 목표 삭제 → % 없음", slot() === "이번주 실적 100", slot());
|
||||||
|
// 다시 그리기(옛 화면: 목표 100·100%)가 목표 저장 뒤에 도착해도 옛 비율이 들어오지 않는다
|
||||||
|
const gate = deferred();
|
||||||
|
st.getHook = async function () { await gate.promise; };
|
||||||
|
const p = env.w.eval("null"); void p;
|
||||||
|
tin.focus(); tin.value = "400"; tin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 목표 400 → 25%", /· 25%$/.test(slot()), slot());
|
||||||
|
gate.resolve(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 늦게 온 옛 화면(100%)이 덮지 않음 — 지금 목표 기준 25%", /· 25%$/.test(slot()), slot());
|
||||||
|
// 저장 실패 — 확정 목표(400)는 그대로라 25% 유지, 입력값은 남김
|
||||||
|
st.itemHook = function () { return { status: 503, body: { detail: "x" } }; };
|
||||||
|
tin.focus(); tin.value = "800"; tin.blur(); await settle(); await wait(10); await settle();
|
||||||
|
check("[7] 저장 실패 → 비율은 확정값(25%), 입력 800 유지", /· 25%$/.test(slot()) && tin.value === "800", [slot(), tin.value]);
|
||||||
|
});
|
||||||
|
await section(async function () { // 실적 조회 실패 화면 — 미확인(0원·0% 아님)
|
||||||
|
const env = makeEnv(PAGE.meeting_err, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||||
|
meetServer(env, { page: PAGE.meeting_err });
|
||||||
|
await boot(env);
|
||||||
|
const kpi = Array.from(env.d.querySelectorAll(".pj-meet-kpi")).map(function (k) { return k.textContent.replace(/\s+/g, " ").trim(); });
|
||||||
|
const mtd = kpi.find(function (t) { return /월 누적 실적/.test(t); });
|
||||||
|
check("[6] 월 누적 = 미확인(0원 아님)", /미확인/.test(mtd) && !/0원|0 원/.test(mtd), mtd);
|
||||||
|
check("[6] 주당 필요 = 미확인(목표로 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /주당 필요/.test(t); })));
|
||||||
|
check("[6] 전주 결과·금주 실적 = 미확인", /미확인/.test(kpi.find(function (t) { return /전주 결과/.test(t); })) && /미확인/.test(kpi.find(function (t) { return /금주 현재 실적/.test(t); })));
|
||||||
|
const row = env.d.querySelector('tr[data-item="1"]');
|
||||||
|
check("[6] 쇼핑몰 연결 줄 결과 = 미확인, 직접 입력 칸으로 바뀌지 않음", /미확인/.test(row.querySelector(".pj-meet-c-result").textContent) && !row.querySelector(".pj-meet-c-result input"));
|
||||||
|
check("[6] 이번주 실적 미확인 · 달성률 비움", /미확인/.test(row.querySelector(".pj-meet-week-slot").textContent) && row.querySelector("[data-rate]").textContent.trim() === "");
|
||||||
|
check("[6] 회의록 입력은 그대로 가능", !!row.querySelector("textarea.pj-meet-text") && !!env.d.getElementById("pj-meet-target"));
|
||||||
|
check("[6] 조회 실패 안내 문구", /미확인/.test(env.d.querySelector(".pj-meet-perf-warn").textContent));
|
||||||
|
});
|
||||||
|
await section(async function () { // 지난주 리뷰 머리 = 지난주(9/21~) — 지난주 회의록에 없는 줄 안내
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||||
|
meetServer(env);
|
||||||
|
await boot(env);
|
||||||
|
check("[5] 지난주 리뷰 머리 = 09/21 ~ 09/27", /09\/21 ~ 09\/27/.test(env.d.querySelector("th.is-prev").textContent));
|
||||||
|
check("[5] 새 줄 = 지난주 회의록에 없는 줄", /지난주 회의록에 없는 줄/.test(env.d.querySelector('tr[data-item="3"]').textContent));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ════════════════════ [8] 구역·항목 메뉴 — ⋮ 버튼(키보드·터치) + 우클릭 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "줄 이름" });
|
||||||
|
goalsServer(env);
|
||||||
|
await boot(env);
|
||||||
|
const btns = env.d.querySelectorAll(".pj-goal-menu-btn");
|
||||||
|
check("[8] 관리자: 구역 2 + 항목 4 메뉴 버튼", btns.length === 6, btns.length);
|
||||||
|
const areaBtn = env.d.querySelector('tbody[data-area-id="1"] .pj-goal-menu-btn[data-goal-menu="area"]');
|
||||||
|
check("[8] 접근성 이름", areaBtn.getAttribute("aria-label") === "상품 구역 메뉴" && areaBtn.getAttribute("aria-haspopup") === "menu");
|
||||||
|
check("[8] Tab 으로 갈 수 있는 버튼", areaBtn.tagName === "BUTTON" && areaBtn.tabIndex === 0);
|
||||||
|
areaBtn.focus();
|
||||||
|
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 })); // Enter/Space → click(detail 0)
|
||||||
|
let menu = env.d.querySelector(".pj-ctxmenu");
|
||||||
|
check("[8] 키보드로 열기 → role=menu, 첫 항목 포커스", menu && menu.getAttribute("role") === "menu" && env.d.activeElement === menu.querySelector(".pj-ctxmenu-item"));
|
||||||
|
check("[8] aria-expanded=true", areaBtn.getAttribute("aria-expanded") === "true");
|
||||||
|
key(env, env.d.activeElement, "ArrowDown");
|
||||||
|
check("[8] ↓ 로 다음 항목", env.d.activeElement === menu.querySelectorAll(".pj-ctxmenu-item")[1]);
|
||||||
|
await settle();
|
||||||
|
key(env, env.d.activeElement, "Escape");
|
||||||
|
check("[8] Esc 닫기 → 버튼으로 포커스 복귀", !env.d.querySelector(".pj-ctxmenu") && env.d.activeElement === areaBtn && areaBtn.getAttribute("aria-expanded") === "false");
|
||||||
|
// 키보드로 항목 실행 — "줄 추가(구역 맨 아래)"
|
||||||
|
areaBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
|
||||||
|
menu = env.d.querySelector(".pj-ctxmenu");
|
||||||
|
const add = Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).find(function (b) { return /줄 추가/.test(itemLabel(b)); });
|
||||||
|
add.focus(); add.click();
|
||||||
|
await settle(); await wait(20); await settle();
|
||||||
|
check("[8] 메뉴 항목 실행 → 줄 추가 API", env.calls.some(function (c) { return c.method === "POST" && /areas\/1\/rows$/.test(c.url); }));
|
||||||
|
// 터치(탭) — 포인터 터치 뒤 click(detail 1)
|
||||||
|
const rowBtn = env.d.querySelector('tr[data-row-id="20"] .pj-goal-menu-btn[data-goal-menu="row"]');
|
||||||
|
rowBtn.dispatchEvent(new env.w.Event("pointerdown", { bubbles: true }));
|
||||||
|
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
|
||||||
|
menu = env.d.querySelector(".pj-ctxmenu");
|
||||||
|
const labels = menu ? Array.from(menu.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel) : [];
|
||||||
|
check("[8] 탭(click) → 줄 메뉴(우클릭과 같은 항목)", labels.indexOf("위에 줄 추가") >= 0 && labels.indexOf("아래에 줄 추가") >= 0 && labels.indexOf("줄 삭제") >= 0, labels);
|
||||||
|
check("[8] 터치로 연 메뉴도 ↑↓·Esc 가능(메뉴에 포커스)", env.d.activeElement === menu);
|
||||||
|
// 다시 누르면 닫힘(토글) — 마우스는 mousedown 이 먼저 닫는다
|
||||||
|
env.d.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
|
||||||
|
rowBtn.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true }));
|
||||||
|
await settle();
|
||||||
|
rowBtn.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
|
||||||
|
check("[8] 열린 메뉴 버튼 다시 누름 = 닫힘", !env.d.querySelector(".pj-ctxmenu"));
|
||||||
|
// 우클릭은 그대로
|
||||||
|
env.d.querySelector('tbody[data-area-id="2"] th.pj-goal-area-name').dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 3, clientY: 3 }));
|
||||||
|
const ctx = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||||
|
check("[8] 우클릭 메뉴 그대로(색·위로·줄 추가·삭제)", ctx.indexOf("색 바꾸기") >= 0 && ctx.indexOf("위로") >= 0 && ctx.indexOf("영역 삭제") >= 0, ctx);
|
||||||
|
key(env, env.d.body, "Escape");
|
||||||
|
// 이름 칸 — Tab 으로 와서 Enter = 이름 수정, 한글 조합 중 Enter 는 무시
|
||||||
|
const name = env.d.querySelector('tr[data-row-id="10"] .pj-goal-row-text');
|
||||||
|
check("[8] 이름 칸 Tab 접근(tabindex=0)", name.getAttribute("tabindex") === "0");
|
||||||
|
name.focus();
|
||||||
|
key(env, name, "Enter", { isComposing: true });
|
||||||
|
check("[8] 한글 조합 중 Enter 는 편집 시작 안 함", name.isContentEditable !== true && name.contentEditable !== "true");
|
||||||
|
key(env, name, "Enter");
|
||||||
|
check("[8] Enter → 이름 수정", name.contentEditable === "true");
|
||||||
|
key(env, name, "Escape");
|
||||||
|
});
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.goals_ro, GOALS_URL);
|
||||||
|
goalsServer(env);
|
||||||
|
await boot(env);
|
||||||
|
check("[8] 보기 전용: 메뉴 버튼·이름 편집 없음", !env.d.querySelector(".pj-goal-menu-btn") && !env.d.querySelector("[data-goal-edit]"));
|
||||||
|
const th = env.d.querySelector("th.pj-goal-area-name");
|
||||||
|
th.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||||
|
check("[8] 보기 전용: 우클릭 편집 메뉴 없음", !env.d.querySelector(".pj-ctxmenu"));
|
||||||
|
// 분기 접기는 보기 전용도
|
||||||
|
const qth = env.d.querySelector('th.pj-goal-fold-th[data-h="1"]');
|
||||||
|
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
|
||||||
|
check("[회귀] 분기 머리 클릭 → 접힘(보기 전용도)", qth.classList.contains("is-folded") && env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-shrunk"));
|
||||||
|
check("[회귀] 접기 상태 기억", /"1":true/.test(env.w.localStorage.getItem("pj_goal_fold_q") || ""));
|
||||||
|
});
|
||||||
|
await section(async function () { // 회귀 — 열 너비 끌기·고정 열 변수·스크롤 위치 되살리기
|
||||||
|
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { session: { pj_goal_scroll: JSON.stringify(["/project/goals/2026", 120, 45]) } });
|
||||||
|
goalsServer(env);
|
||||||
|
await boot(env);
|
||||||
|
const pane = env.d.getElementById("pj-goal-pane");
|
||||||
|
check("[회귀] 스크롤 위치 되살림", pane.scrollLeft === 120 && pane.scrollTop === 45, [pane.scrollLeft, pane.scrollTop]);
|
||||||
|
const h = env.d.querySelector('.pj-goal-colresize[data-col="c1"]');
|
||||||
|
h.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 100 }));
|
||||||
|
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 140 }));
|
||||||
|
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||||
|
const table = env.d.getElementById("pj-goal-table");
|
||||||
|
check("[회귀] 1열 너비 끌기 → --goal-c1-w 112px·기억", table.style.getPropertyValue("--goal-c1-w") === "112px" && /"c1":112/.test(env.w.localStorage.getItem("pj_goal_col_w") || ""),
|
||||||
|
table.style.getPropertyValue("--goal-c1-w"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const st = meetServer(env);
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
const box = env.d.getElementById("pj-meet-sync");
|
||||||
|
check("[9] 정상 갱신 → 안내 숨김(조용)", st.syncCalls === 1 && box.hidden === true);
|
||||||
|
check("[9] 갱신 뒤 숫자 칸 다시 그림(GET)", (st.gets || 0) >= 1);
|
||||||
|
});
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const st = meetServer(env, { syncHook: function (body) {
|
||||||
|
return { body: { joined: false, job: { id: "j1", finished: true, from: body.from, to: body.to,
|
||||||
|
shops: [{ name: "쿠팡", state: "done", active: true }, { name: "네이버", state: "error", label: "인증 오류", active: true }], overall: {} } } };
|
||||||
|
} });
|
||||||
|
await boot(env);
|
||||||
|
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||||
|
ta.focus(); type(env, ta, "editing while sync");
|
||||||
|
await wait(20); await settle();
|
||||||
|
const box = env.d.getElementById("pj-meet-sync"), btn = env.d.getElementById("pj-meet-sync-btn");
|
||||||
|
check("[9] 일부 실패 → 안내 보임 + 실패 쇼핑몰 이름", !box.hidden && box.dataset.state === "partial" && /네이버\(인증 오류\)/.test(box.textContent), box.textContent);
|
||||||
|
check("[9] 일부 실패를 전체 성공처럼 쓰지 않음 + 서버 기록 시각", !/갱신 성공 10\/01 14:20.*전체/.test(box.textContent) && /마지막 갱신 성공 10\/01 14:20/.test(box.textContent), box.textContent);
|
||||||
|
check("[9] 재시도 버튼", !btn.hidden);
|
||||||
|
check("[9] 갱신·다시 그리기 중에도 편집 글 유지", ta.value === "editing while sync");
|
||||||
|
const rec = JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28"));
|
||||||
|
check("[9] 기록 = partial(성공으로 기록하지 않음)", rec.state === "partial");
|
||||||
|
btn.click(); await wait(20); await settle();
|
||||||
|
check("[9] 재시도 → 다시 부름", st.syncCalls === 2);
|
||||||
|
});
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const st = meetServer(env, { syncHook: function () { return { status: 500, body: { detail: "서버 오류" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
const box = env.d.getElementById("pj-meet-sync");
|
||||||
|
check("[9] 실패 → 식별 가능한 안내 + 재시도", !box.hidden && box.dataset.state === "error" && /실패/.test(box.textContent) && !env.d.getElementById("pj-meet-sync-btn").hidden, box.textContent);
|
||||||
|
st.syncHook = null;
|
||||||
|
env.d.getElementById("pj-meet-sync-btn").click(); await wait(20); await settle();
|
||||||
|
check("[9] 재시도 성공 → 안내 사라짐", box.hidden === true);
|
||||||
|
});
|
||||||
|
await section(async function () {
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
const st = meetServer(env, { syncHook: function () { return { status: 403, body: { detail: "권한 없음" } }; } });
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
const box = env.d.getElementById("pj-meet-sync");
|
||||||
|
check("[9] 403 → 권한 없음 설명, 재시도 버튼 없음", box.dataset.state === "noperm" && env.d.getElementById("pj-meet-sync-btn").hidden);
|
||||||
|
check("[9] 403 기억 → 같은 세션 자동 재호출 안 함", JSON.parse(env.w.sessionStorage.getItem("pj_meet_sync:2026-09-28")).state === "noperm");
|
||||||
|
void st;
|
||||||
|
});
|
||||||
|
await section(async function () { // 권한 없음(서버가 can_sync=0) — API 를 아예 부르지 않는다
|
||||||
|
const env = makeEnv(PAGE.meeting_ro, MEET_URL);
|
||||||
|
const st = meetServer(env, { page: PAGE.meeting_ro });
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
check("[9] 실적 권한 없음 → sync API 호출 0", !st.syncCalls && !env.calls.some(function (c) { return /performance/.test(c.url); }));
|
||||||
|
check("[9] 권한 없음 설명(저장된 실적·마지막 갱신 시각)", /권한이 없어/.test(env.d.getElementById("pj-meet-sync").textContent) && /10\/01 14:20/.test(env.d.getElementById("pj-meet-sync").textContent));
|
||||||
|
check("[9] 보기 전용: 입력칸 없음", !env.d.querySelector("textarea.pj-meet-text") && !env.d.getElementById("pj-meet-target"));
|
||||||
|
});
|
||||||
|
await section(async function () { // 10분 제한 — 최근 기록이 있으면 다시 부르지 않고 그 상태만(일부 실패면 안내 유지)
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "partial", bad: ["네이버"] }) } });
|
||||||
|
const st = meetServer(env);
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
check("[9] 10분 안 = 다시 부르지 않음, 일부 실패 안내 유지", !st.syncCalls && env.d.getElementById("pj-meet-sync").dataset.state === "partial");
|
||||||
|
});
|
||||||
|
await section(async function () { // 다른 사람 업데이트에 합류했는데 기간이 이 주를 다 덮지 못하면 한 번 더
|
||||||
|
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||||
|
let n = 0;
|
||||||
|
const st = meetServer(env, { syncHook: function (body) {
|
||||||
|
n++;
|
||||||
|
if (n === 1) return { body: { joined: true, job: { id: "other", finished: true, from: "2026-09-29", to: "2026-10-01", shops: [], overall: {} } } };
|
||||||
|
return { body: { joined: false, job: { id: "mine", finished: true, from: body.from, to: body.to, shops: [], overall: {} } } };
|
||||||
|
} });
|
||||||
|
await boot(env);
|
||||||
|
await wait(20); await settle();
|
||||||
|
check("[9] 합류한 작업이 기간을 못 덮으면 이 주 기간으로 한 번 더", st.syncCalls === 2 && env.d.getElementById("pj-meet-sync").hidden);
|
||||||
|
});
|
||||||
|
await section(async function () { // 회귀 — 참석자 고르기(칩·저장)
|
||||||
|
const html = PAGE.meeting_admin.replace("window.PJ_MEET_MEMBERS = []", 'window.PJ_MEET_MEMBERS = [{"email":"a@test.local","name":"에이","avatar":""}]');
|
||||||
|
const env = makeEnv(html, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||||
|
const st = meetServer(env);
|
||||||
|
await boot(env);
|
||||||
|
env.d.getElementById("pj-meet-attend-add").click();
|
||||||
|
const cb = env.d.querySelector('.pj-meet-pick input[type=checkbox][data-email="a@test.local"]');
|
||||||
|
cb.checked = true; cb.dispatchEvent(new env.w.Event("change", { bubbles: true }));
|
||||||
|
await settle();
|
||||||
|
check("[회귀] 참석자 고르기 → 칩 + 저장", !!env.d.querySelector('.pj-meet-chip[data-key="a@test.local"]') && st.head.attendees === "a@test.local", st.head);
|
||||||
|
});
|
||||||
|
|
||||||
|
clearTimeout(WATCHDOG);
|
||||||
|
const realUnhandled = unhandled.filter(function (m) { return !/Not implemented/.test(m); });
|
||||||
|
check("처리 안 된 Promise 거부 없음", realUnhandled.length === 0, realUnhandled);
|
||||||
|
console.log(fails.length ? fails.length + " FAIL" : "ALL PASS");
|
||||||
|
process.exit(fails.length ? 1 : 0);
|
||||||
|
})().catch(function (e) { console.error(e); process.exit(1); });
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""연간 목표(goals.html)·주간 회의록(goal_meeting.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||||
|
|
||||||
|
python tests/js/render_goals.py # → tests/js/.out/goals_admin.html · goals_ro.html · meeting_admin.html · meeting_err.html · meeting_ro.html
|
||||||
|
|
||||||
|
칸 배치는 실제 라우터 도우미(_goal_area_layout·_goal_label_spans)로 만든다. DB·실적 모듈은 쓰지 않는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import jinja2
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
sys.path.insert(0, ROOT)
|
||||||
|
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||||
|
|
||||||
|
from app.modules.project import store # noqa: E402
|
||||||
|
from app.modules.project.router import _goal_area_layout, _goal_label_spans # noqa: E402
|
||||||
|
|
||||||
|
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
|
||||||
|
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||||
|
ME = "me@test.local"
|
||||||
|
|
||||||
|
|
||||||
|
def board() -> dict:
|
||||||
|
rows_a = [{"id": 10, "label": "신제품", "cells": {0: "연간 계획", 1: "original"}, "merges": {}},
|
||||||
|
{"id": 11, "label": "리뉴얼", "cells": {}, "merges": {}}]
|
||||||
|
rows_b = [{"id": 20, "label": "쿠팡", "cells": {2: "행사"}, "merges": {}},
|
||||||
|
{"id": 21, "label": "", "cells": {}, "merges": {}}]
|
||||||
|
areas = [{"id": 1, "name": "상품", "color": "#fde2e4", "rows": rows_a},
|
||||||
|
{"id": 2, "name": "유통", "color": "", "rows": rows_b}]
|
||||||
|
for a in areas:
|
||||||
|
_goal_area_layout(a["rows"], 10)
|
||||||
|
_goal_label_spans(a["rows"])
|
||||||
|
return {
|
||||||
|
"year": 2026, "sales_unit": "만원", "halves": True, "quarters": True,
|
||||||
|
"metrics": {"sales": {"target_label": {1: "100", 2: "100"}, "actual_label": {1: "50"}},
|
||||||
|
"roas": {"target_label": {}, "actual_label": {}}},
|
||||||
|
"areas": areas,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def goals_ctx(admin: bool) -> dict:
|
||||||
|
return {
|
||||||
|
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||||
|
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||||
|
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
|
||||||
|
"months": list(range(1, 13)),
|
||||||
|
"quarters": [(q, list(range(q * 3 - 2, q * 3 + 1)), store.GOAL_QUARTER_COL[q], f"{q}분기") for q in (1, 2, 3, 4)],
|
||||||
|
"this_month": 10, "goal_area_colors": list(store.GOAL_AREA_COLORS),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def meeting_view(err: bool) -> dict:
|
||||||
|
"""회의록 2026-09-28 주 — 유통 쿠팡(쇼핑몰 연결, 이번주 실적 100, 정량 목표 100), 상품1(직접 입력 결과)."""
|
||||||
|
prev_cou = {"id": 901, "week_start": "2026-09-21", "content": "지난주 행사", "target_amount": 100, "result_amount": None,
|
||||||
|
"status": "", "marketplace_code": "coupang", "period": "9/21~9/27", "not_started": False,
|
||||||
|
"market_off": False, "auto_error": err, "auto_result": None if err else 80,
|
||||||
|
"result": None if err else 80, "market_name": "쿠팡"}
|
||||||
|
prev_p1 = {"id": 902, "week_start": "2026-09-21", "content": "샘플", "target_amount": 200, "result_amount": 100,
|
||||||
|
"status": "partial", "marketplace_code": "", "period": "9/21~9/27", "not_started": False,
|
||||||
|
"market_off": False, "auto_error": False, "auto_result": None, "result": 100, "market_name": ""}
|
||||||
|
it_cou = {"id": 1, "section": "유통", "section_color": "", "label": "쿠팡", "content": "original",
|
||||||
|
"target_amount": 100, "marketplace_code": "coupang", "market_name": "쿠팡", "market_off": False,
|
||||||
|
"market_unknown": err, "week_auto": None if err else 100, "week_error": err,
|
||||||
|
"prev": prev_cou, "rate": None if err else 80.0}
|
||||||
|
it_p1 = {"id": 2, "section": "상품", "section_color": "#fde2e4", "label": "상품1", "content": "",
|
||||||
|
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||||
|
"market_unknown": False, "week_auto": None, "week_error": False, "prev": prev_p1, "rate": 50.0}
|
||||||
|
it_new = {"id": 3, "section": "상품", "section_color": "#fde2e4", "label": "새 줄", "content": "",
|
||||||
|
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||||
|
"market_unknown": False, "week_auto": None, "week_error": False, "prev": None, "rate": None}
|
||||||
|
meeting = {"week_start": "2026-09-28", "week_target": 1000, "attendees": "", "notes": "메모 원본",
|
||||||
|
"items": [it_p1, it_new, it_cou],
|
||||||
|
"sections": [{"name": "상품", "color": "#fde2e4", "rows": [it_p1, it_new]},
|
||||||
|
{"name": "유통", "color": "", "rows": [it_cou]}]}
|
||||||
|
head = {"sales_unit": "원", "sales_target": 10000.0, "roas_target": None, "month_target_won": 10000,
|
||||||
|
"mtd": None if err else 0, "mtd_end": "2026-09-27", "weeks_left": 1,
|
||||||
|
"need_per_week": None if err else 10000, "prev_target": 500, "prev_exists": True,
|
||||||
|
"prev_result": None if err else 0, "week_result": None if err else 0,
|
||||||
|
"perf": True, "perf_state": "error" if err else "ok",
|
||||||
|
"unknown": ["mtd", "prev_result", "week_result"] if err else [],
|
||||||
|
"fresh_oldest": "" if err else "10/01 14:20",
|
||||||
|
"fresh_tip": "" if err else "매출 자료(실적 모듈) 쇼핑몰별 마지막 갱신 성공 — 쿠팡 10/01 14:20"}
|
||||||
|
return {"meeting": meeting, "head": head, "markets": [] if err else [{"code": "coupang", "name": "쿠팡"}]}
|
||||||
|
|
||||||
|
|
||||||
|
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
|
||||||
|
view = meeting_view(err)
|
||||||
|
return {
|
||||||
|
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||||
|
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
|
||||||
|
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
|
||||||
|
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
|
||||||
|
"days": []}],
|
||||||
|
"cal_weeks": [], "week": "2026-09-28", "week_n": 4, "week_end": "2026-10-04",
|
||||||
|
"prev_week": "2026-09-21", "prev_week_end": "2026-09-27", "sync_from": "2026-09-21", "sync_to": "2026-10-01",
|
||||||
|
"can_sync": can_sync, "meeting_status": store.MEETING_STATUS, "meet_members": [], "month_plan": None,
|
||||||
|
"attendee_list": [], **copy.deepcopy(view),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||||
|
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||||
|
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||||
|
]))
|
||||||
|
env.globals["pj_kr_holidays"] = {}
|
||||||
|
os.makedirs(OUT_DIR, exist_ok=True)
|
||||||
|
pages = {
|
||||||
|
"goals_admin.html": ("project/goals.html", goals_ctx(True)),
|
||||||
|
"goals_ro.html": ("project/goals.html", goals_ctx(False)),
|
||||||
|
"meeting_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False)),
|
||||||
|
"meeting_err.html": ("project/goal_meeting.html", meeting_ctx(True, True)),
|
||||||
|
"meeting_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False)),
|
||||||
|
}
|
||||||
|
for name, (tpl, ctx) in pages.items():
|
||||||
|
html = env.get_template(tpl).render(**ctx)
|
||||||
|
path = os.path.join(OUT_DIR, name)
|
||||||
|
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||||
|
print("rendered:", path)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""마이그레이션 018(주간 회의록 줄 연결키 line_key) 백필 검증 — 로컬 테스트용 PostgreSQL 에서만.
|
||||||
|
|
||||||
|
예전 코드가 만든 데이터 모양(carry_from 사슬·역순 생성·끊긴 연결·같은 이름 줄)을 임시 스키마에 만들고
|
||||||
|
scripts/sql/project_db_018_meeting_line_keys.sql 을 두 번 돌려(멱등) 결과를 확인한다.
|
||||||
|
전부 한 트랜잭션 안에서 하고 마지막에 ROLLBACK — 테스트 DB 에 아무것도 남기지 않는다(DROP 없음).
|
||||||
|
|
||||||
|
PROJECT_TEST_DB_URL=postgresql://postgres@127.0.0.1:55432/project_db \
|
||||||
|
python tests/test_meeting_line_keys_migration.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
|
||||||
|
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||||
|
|
||||||
|
DDL = """
|
||||||
|
CREATE TABLE goal_meetings (
|
||||||
|
week_start DATE PRIMARY KEY CHECK (EXTRACT(ISODOW FROM week_start) = 1),
|
||||||
|
week_target BIGINT NULL, attendees TEXT NOT NULL DEFAULT '', notes TEXT NOT NULL DEFAULT '',
|
||||||
|
created_by TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_by TEXT NOT NULL DEFAULT '', updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE goal_meeting_items (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
week_start DATE NOT NULL REFERENCES goal_meetings(week_start) ON DELETE CASCADE,
|
||||||
|
section TEXT NOT NULL DEFAULT '', section_color TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT '',
|
||||||
|
content TEXT NOT NULL DEFAULT '', target_amount BIGINT NULL, result_amount BIGINT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT '', marketplace_code TEXT NOT NULL DEFAULT '',
|
||||||
|
carry_from BIGINT NULL REFERENCES goal_meeting_items(id) ON DELETE SET NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0, updated_by TEXT NOT NULL DEFAULT '', updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def migration_sql() -> str:
|
||||||
|
"""018 파일에서 psql 메타 명령(\\set·\\connect)과 BEGIN/COMMIT 을 뺀 본문 — 바깥 트랜잭션(ROLLBACK) 안에서 돌린다."""
|
||||||
|
path = os.path.join(ROOT, "scripts", "sql", "project_db_018_meeting_line_keys.sql")
|
||||||
|
with open(path, encoding="utf-8") as fh:
|
||||||
|
lines = [ln for ln in fh.read().splitlines()
|
||||||
|
if not ln.startswith("\\") and ln.strip() not in ("BEGIN;", "COMMIT;")]
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if not ENABLED:
|
||||||
|
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||||
|
return 0
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
|
||||||
|
schema = "mig018_" + uuid.uuid4().hex[:8]
|
||||||
|
W = [date(2026, 9, 7) + timedelta(days=7 * i) for i in range(5)] # 9/7 9/14 9/21 9/28 10/5 (월요일)
|
||||||
|
with psycopg.connect(DSN, row_factory=dict_row) as conn: # autocommit 아님 — 끝에 rollback
|
||||||
|
conn.execute(f"CREATE SCHEMA {schema}")
|
||||||
|
conn.execute(f"SET LOCAL search_path TO {schema}")
|
||||||
|
conn.execute(DDL)
|
||||||
|
for w in W:
|
||||||
|
conn.execute("INSERT INTO goal_meetings (week_start) VALUES (%s)", (w,))
|
||||||
|
|
||||||
|
def add(week, section, label, carry=None, order=0):
|
||||||
|
return conn.execute(
|
||||||
|
"INSERT INTO goal_meeting_items (week_start, section, label, carry_from, sort_order) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s) RETURNING id", (week, section, label, carry, order),
|
||||||
|
).fetchone()["id"]
|
||||||
|
|
||||||
|
# 9/14 = 양식으로 처음(사슬 뿌리) — 같은 구역에 같은 이름 "기타" 두 줄
|
||||||
|
a_cou = add(W[1], "유통", "쿠팡", order=0)
|
||||||
|
a_et1 = add(W[1], "유통", "기타", order=1)
|
||||||
|
a_et2 = add(W[1], "유통", "기타", order=2)
|
||||||
|
a_meta = add(W[1], "마케팅", "메타", order=3)
|
||||||
|
# 9/28 을 먼저 만듦(예전 코드: 앞선 가장 가까운 9/14 를 원본으로) → 9/21 을 나중에(역시 9/14 원본)
|
||||||
|
b_cou = add(W[3], "유통", "쿠팡", a_cou, 0)
|
||||||
|
b_et1 = add(W[3], "유통", "기타", a_et1, 1)
|
||||||
|
b_et2 = add(W[3], "유통", "기타", a_et2, 2)
|
||||||
|
b_meta = add(W[3], "마케팅", "메타 광고", a_meta, 3) # 이름 바꾼 줄
|
||||||
|
b_new = add(W[3], "유통", "쿠팡", None, 4) # 9/28 에 새로 추가한 같은 이름 줄
|
||||||
|
c_cou = add(W[2], "유통", "쿠팡", a_cou, 0)
|
||||||
|
c_et1 = add(W[2], "유통", "기타", a_et1, 1)
|
||||||
|
c_et2 = add(W[2], "유통", "기타", a_et2, 2)
|
||||||
|
c_meta = add(W[2], "마케팅", "메타", a_meta, 3)
|
||||||
|
# 10/5 = 9/28 원본 — 9/28 의 새 줄도 이어받음
|
||||||
|
d_cou = add(W[4], "유통", "쿠팡", b_cou, 0)
|
||||||
|
d_new = add(W[4], "유통", "쿠팡", b_new, 1)
|
||||||
|
# 9/7 = 앞 주를 지웠다 다시 만든 흔적 — 연결 끊김(carry_from NULL), 같은 이름이지만 붙이면 안 됨
|
||||||
|
e_cou = add(W[0], "유통", "쿠팡", None, 0)
|
||||||
|
|
||||||
|
sql = migration_sql()
|
||||||
|
conn.execute(sql)
|
||||||
|
key = lambda i: conn.execute("SELECT line_key FROM goal_meeting_items WHERE id = %s", (i,)).fetchone()["line_key"] # noqa: E731
|
||||||
|
first = {i: key(i) for i in (a_cou, b_cou, c_cou, d_cou, a_et1, a_et2, b_et1, b_et2, c_et1, c_et2,
|
||||||
|
a_meta, b_meta, c_meta, b_new, d_new, e_cou)}
|
||||||
|
conn.execute(sql) # 두 번째 — 멱등(키가 바뀌지 않아야)
|
||||||
|
second = {i: key(i) for i in first}
|
||||||
|
|
||||||
|
checks = [
|
||||||
|
("모든 줄에 키", conn.execute("SELECT count(*) AS n FROM goal_meeting_items WHERE line_key IS NULL").fetchone()["n"] == 0),
|
||||||
|
("역순 생성: 9/28 쿠팡 ↔ 9/21 쿠팡 같은 키", first[b_cou] == first[c_cou] == first[a_cou] == first[d_cou]),
|
||||||
|
("같은 이름 '기타' 두 줄은 서로 다른 키", first[a_et1] != first[a_et2]),
|
||||||
|
("'기타' 각 줄이 자기 사슬로만", first[b_et1] == first[c_et1] == first[a_et1] and first[b_et2] == first[c_et2] == first[a_et2]),
|
||||||
|
("이름 바꾼 줄도 같은 키", first[b_meta] == first[c_meta] == first[a_meta]),
|
||||||
|
("새로 추가한 같은 이름 줄은 다른 키", first[b_new] != first[b_cou] and first[d_new] == first[b_new]),
|
||||||
|
("끊긴 연결(carry_from NULL)은 이름이 같아도 붙이지 않음", first[e_cou] != first[a_cou]),
|
||||||
|
("두 번 돌려도 같은 키(멱등)", first == second),
|
||||||
|
("NOT NULL 제약", conn.execute(
|
||||||
|
"SELECT is_nullable FROM information_schema.columns WHERE table_schema = %s "
|
||||||
|
"AND table_name = 'goal_meeting_items' AND column_name = 'line_key'", (schema,)).fetchone()["is_nullable"] == "NO"),
|
||||||
|
]
|
||||||
|
# UNIQUE(week_start, line_key) — 같은 주 같은 키는 막힌다
|
||||||
|
try:
|
||||||
|
with conn.transaction():
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET line_key = %s WHERE id = %s", (first[b_cou], b_new))
|
||||||
|
checks.append(("한 주 안 같은 키 금지(UNIQUE)", False))
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
checks.append(("한 주 안 같은 키 금지(UNIQUE)", True))
|
||||||
|
conn.rollback() # 아무것도 남기지 않는다
|
||||||
|
|
||||||
|
bad = [n for n, ok in checks if not ok]
|
||||||
|
for n, ok in checks:
|
||||||
|
print(("PASS " if ok else "FAIL ") + n)
|
||||||
|
print("ALL PASS" if not bad else f"{len(bad)} FAIL")
|
||||||
|
return 1 if bad else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -20,7 +20,7 @@ import tempfile
|
|||||||
import threading
|
import threading
|
||||||
import types
|
import types
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import timedelta
|
from datetime import date, timedelta
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
@@ -456,6 +456,504 @@ def test_store_date_range_unit():
|
|||||||
raise AssertionError(args)
|
raise AssertionError(args)
|
||||||
|
|
||||||
|
|
||||||
|
def test_store_goal_merge_unit():
|
||||||
|
from app.modules.project import store
|
||||||
|
assert store.validate_goal_merge(3, 1) == (1, 3)
|
||||||
|
assert store.validate_goal_merge(10, 12) == (10, 12)
|
||||||
|
assert store.validate_goal_month(13, allow_year=True) == 13
|
||||||
|
assert store.validate_goal_month(16, allow_year=True) == 16
|
||||||
|
for bad in (17, -1):
|
||||||
|
try:
|
||||||
|
store.validate_goal_month(bad, allow_year=True)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
raise AssertionError(bad)
|
||||||
|
# 분기를 넘는 병합(3~4월, 6~7월, 7~12월)은 거절
|
||||||
|
for args in ((3, 4), (6, 7), (7, 12), (3, 3), (0, 2), (11, 13)):
|
||||||
|
try:
|
||||||
|
store.validate_goal_merge(*args)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
raise AssertionError(args)
|
||||||
|
|
||||||
|
|
||||||
|
def test_store_goal_quarters_unit():
|
||||||
|
"""분기 칸(2026-10-01 상·하반기 → 1~4분기): 칸 순서·묶음·사각형 범위."""
|
||||||
|
from app.modules.project import store
|
||||||
|
assert store.GOAL_COL_ORDER == (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
|
||||||
|
assert [store.goal_quarter_of(m) for m in (1, 3, 4, 6, 7, 9, 10, 12)] == [1, 1, 2, 2, 3, 3, 4, 4]
|
||||||
|
assert store.GOAL_QUARTER_COL == {1: 13, 2: 15, 3: 14, 4: 16}
|
||||||
|
assert store.goal_col_group(13) == "q1" and store.goal_col_group(14) == "q3"
|
||||||
|
assert store.goal_col_group(5) == store.goal_col_group(6) != store.goal_col_group(7)
|
||||||
|
assert store.validate_goal_rect_cols(4, 6) == (4, 3)
|
||||||
|
assert store.validate_goal_rect_cols(15, 15) == (15, 1)
|
||||||
|
for a, b in ((3, 4), (3, 13), (6, 15), (0, 1)):
|
||||||
|
try:
|
||||||
|
store.validate_goal_rect_cols(a, b)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
raise AssertionError((a, b))
|
||||||
|
assert store.MEETING_TEMPLATE["마케팅"][0] == "메타"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def test_goal_halves_and_merges():
|
||||||
|
year = 2060 + int(RUN, 16) % 40
|
||||||
|
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None
|
||||||
|
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
|
||||||
|
try:
|
||||||
|
board = ST.get_goal_board(year=year)
|
||||||
|
assert board["halves"] is True, "마이그레이션 014 적용 필요"
|
||||||
|
assert board["quarters"] is True, "마이그레이션 017 적용 필요"
|
||||||
|
rid = board["areas"][0]["rows"][0]["id"]
|
||||||
|
aid0 = board["areas"][0]["id"]
|
||||||
|
cell = lambda m, body, who=ADMIN: req( # noqa: E731
|
||||||
|
"PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body})
|
||||||
|
# 분기 글 칸(13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기), 범위 밖(17)은 400, 비관리자는 403
|
||||||
|
for m, body in ((13, "1분기 글"), (15, "2분기 글"), (14, "3분기 글"), (16, "4분기 글")):
|
||||||
|
assert cell(m, body).status_code == 200, m
|
||||||
|
assert cell(17, "x").status_code == 400
|
||||||
|
assert cell(13, "y", BOB).status_code == 403
|
||||||
|
for m, body in ((2, "이월"), (3, "삼월")):
|
||||||
|
assert cell(m, body).status_code == 200
|
||||||
|
merge = lambda s, e: req( # noqa: E731 — 엑셀식 병합 API(한 줄 가로)
|
||||||
|
"POST", f"/project/api/goals/areas/{aid0}/merge", ADMIN,
|
||||||
|
json={"row_from": rid, "row_to": rid, "col_from": s, "col_to": e})
|
||||||
|
# 분기를 넘는 병합(3~4월, 사이에 1분기 칸)·한 칸 병합은 400
|
||||||
|
assert merge(3, 4).status_code == 400 and merge(4, 4).status_code == 400
|
||||||
|
r = merge(2, 3)
|
||||||
|
assert r.status_code == 200 and r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 2, "row_span": 1}, r.text
|
||||||
|
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
|
||||||
|
assert cells[2] == "이월\n삼월" and 3 not in cells
|
||||||
|
# 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만)
|
||||||
|
assert cell(3, "늦은 저장").status_code == 400
|
||||||
|
# 걸친 병합은 흡수: 1~2 → 1~3, 글은 월 순서대로 이어진다
|
||||||
|
r = merge(1, 2)
|
||||||
|
assert r.json() == {"ok": True, "row_id": rid, "start": 1, "span": 3, "row_span": 1}, r.text
|
||||||
|
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||||||
|
assert row["merges"] == {1: (3, 1)} and row["cells"][1] == "이월\n삼월" and 2 not in row["cells"]
|
||||||
|
assert row["cells"][13] == "1분기 글" and row["cells"][15] == "2분기 글" and row["cells"][16] == "4분기 글"
|
||||||
|
# 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 200
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 404
|
||||||
|
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||||||
|
assert row["merges"] == {} and row["cells"][1] == "이월\n삼월"
|
||||||
|
# 로아스 % 표기(입력에 % 가 있어도 숫자로 저장)
|
||||||
|
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
|
||||||
|
json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"})
|
||||||
|
assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499
|
||||||
|
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
|
||||||
|
json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"})
|
||||||
|
assert r.json()["label"] == "1,200"
|
||||||
|
# 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용
|
||||||
|
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
|
||||||
|
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400
|
||||||
|
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200
|
||||||
|
assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200
|
||||||
|
# 줄 추가 — 기준 줄 위/아래(ref_row_id + place), 없으면 맨 끝. 다른 영역 줄 기준은 404, place 오류는 400
|
||||||
|
add = lambda body, who=ADMIN: req( # noqa: E731
|
||||||
|
"POST", f"/project/api/goals/areas/{aid}/rows", who, json=body)
|
||||||
|
labels = lambda: [r["label"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||||
|
before = labels()
|
||||||
|
assert add({"label": "끝"}).status_code == 201
|
||||||
|
assert add({"label": "아래", "ref_row_id": rid, "place": "below"}).status_code == 201
|
||||||
|
assert add({"label": "위", "ref_row_id": rid, "place": "above"}).status_code == 201
|
||||||
|
assert labels() == ["위", before[0], "아래"] + before[1:] + ["끝"], labels()
|
||||||
|
areas = ST.get_goal_board(year=year)["areas"]
|
||||||
|
if len(areas) > 1:
|
||||||
|
assert add({"label": "x", "ref_row_id": areas[1]["rows"][0]["id"]}).status_code == 404
|
||||||
|
assert add({"label": "x", "ref_row_id": rid, "place": "left"}).status_code == 400
|
||||||
|
assert add({"label": "x", "ref_row_id": "abc"}).status_code == 400
|
||||||
|
assert add({"label": "x"}, BOB).status_code == 403
|
||||||
|
finally:
|
||||||
|
ST.delete_goal_year(year=year)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 연간 목표 — 엑셀식 사각형 병합 · 주간 회의록(마이그레이션 015)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def test_goal_rect_merges():
|
||||||
|
"""세로 병합(같은 영역 연속 줄)·연간/반기 칸 세로 병합, 걸친 병합 흡수, 가린 칸 저장 거절,
|
||||||
|
줄 끼우기/지우기에 따라 row_span 증감, 세로 병합에 걸린 줄 이동 거절, 다른 영역 줄 404."""
|
||||||
|
year = 2060 + (int(RUN, 16) + 7) % 40
|
||||||
|
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None
|
||||||
|
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
|
||||||
|
try:
|
||||||
|
assert ST.get_goal_board(year=year)["rect"] is True, "마이그레이션 015 적용 필요"
|
||||||
|
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
|
||||||
|
rows = lambda: ST.get_goal_board(year=year)["areas"][0]["rows"] # noqa: E731
|
||||||
|
while len(rows()) < 4: # 이전 연도 구조를 복사해 줄이 더 있을 수도 — 앞 4줄로 시험
|
||||||
|
req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "채움"})
|
||||||
|
r1, r2, r3, r4 = [r["id"] for r in rows()][:4]
|
||||||
|
put = lambda rid, m, body: req("PUT", f"/project/api/goals/rows/{rid}/cells/{m}", ADMIN, json={"body": body}) # noqa: E731
|
||||||
|
assert put(r1, 0, "연간1").status_code == 200 and put(r2, 0, "연간2").status_code == 200
|
||||||
|
assert put(r2, 4, "사월2").status_code == 200
|
||||||
|
merge = lambda a, b, c0, c1, who=ADMIN: req( # noqa: E731
|
||||||
|
"POST", f"/project/api/goals/areas/{aid}/merge", who,
|
||||||
|
json={"row_from": a, "row_to": b, "col_from": c0, "col_to": c1})
|
||||||
|
# 연간 칸 세로 3줄 — 글은 위에서부터 이어 붙어 맨 위 칸에
|
||||||
|
r = merge(r1, r3, 0, 0)
|
||||||
|
assert r.status_code == 200 and r.json() == {"ok": True, "row_id": r1, "start": 0, "span": 1, "row_span": 3}, r.text
|
||||||
|
b = rows()
|
||||||
|
assert b[0]["merges"] == {0: (1, 3)} and b[0]["cells"][0] == "연간1\n연간2" and 0 not in b[1]["cells"]
|
||||||
|
assert put(r2, 0, "가린 칸").status_code == 400 # 가려진 칸 저장 거절
|
||||||
|
# 연간 + 1월 가로(묶음이 다름)·비관리자·다른 영역 줄 → 400·403·404
|
||||||
|
assert merge(r1, r1, 0, 1).status_code == 400
|
||||||
|
assert merge(r1, r2, 3, 4, BOB).status_code == 403
|
||||||
|
other = ST.get_goal_board(year=year)["areas"]
|
||||||
|
if len(other) > 1:
|
||||||
|
assert merge(r1, other[1]["rows"][0]["id"], 3, 3).status_code == 404
|
||||||
|
# 분기를 넘는 사각형(3~4월)은 400
|
||||||
|
assert merge(r1, r2, 3, 4).status_code == 400
|
||||||
|
# 사각형 2줄 × 2칸(4~5월) → 걸친 병합으로 넓히기: 5월 r2 ~ 6월 r3 → 4~6월 × r1~r3
|
||||||
|
assert merge(r1, r2, 4, 5).json()["row_span"] == 2
|
||||||
|
r = merge(r2, r3, 5, 6)
|
||||||
|
assert r.json() == {"ok": True, "row_id": r1, "start": 4, "span": 3, "row_span": 3}, r.text
|
||||||
|
assert rows()[0]["cells"].get(4) == "사월2"
|
||||||
|
# 2분기 칸(15) 세로 병합(017)
|
||||||
|
r = merge(r1, r2, 15, 15)
|
||||||
|
assert r.status_code == 200 and r.json()["start"] == 15 and r.json()["row_span"] == 2, r.text
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/15", ADMIN).status_code == 200
|
||||||
|
# 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(r4)은 위로 못 감(r3 이 걸림) / 병합 해제 뒤엔 됨
|
||||||
|
assert req("POST", f"/project/api/goals/rows/{r2}/move", ADMIN, json={"direction": 1}).status_code == 400
|
||||||
|
assert req("POST", f"/project/api/goals/rows/{r4}/move", ADMIN, json={"direction": -1}).status_code == 400
|
||||||
|
# 병합 안쪽에 줄 끼우기 → row_span +1, 가려진 줄 지우기 → -1
|
||||||
|
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
|
||||||
|
json={"label": "끼움", "ref_row_id": r1, "place": "below"}).status_code == 201
|
||||||
|
assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)}
|
||||||
|
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
|
||||||
|
json={"label": "아래", "ref_row_id": r4, "place": "below"}).status_code == 201
|
||||||
|
assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)} # 병합 밖이면 그대로
|
||||||
|
ins = rows()[1]["id"]
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{ins}", ADMIN).status_code == 200
|
||||||
|
assert rows()[0]["merges"] == {0: (1, 3), 4: (3, 3)}
|
||||||
|
# 해제 — 글은 왼쪽 위 칸에
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200
|
||||||
|
b = rows()
|
||||||
|
assert b[0]["merges"] == {4: (3, 3)} and b[0]["cells"][0] == "연간1\n연간2"
|
||||||
|
assert put(r2, 0, "이제 됨").status_code == 200
|
||||||
|
finally:
|
||||||
|
ST.delete_goal_year(year=year)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_goal_label_groups():
|
||||||
|
"""항목 칸(2열) 묶음(016): 3열 추가(same_label) 아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이 첫 줄(이름 넘겨받음),
|
||||||
|
묶음 첫 줄 삭제 → 다음 줄이 첫 줄(이름 넘겨받음), 묶인 줄 이동 400, 항목 칸 나누기, 새 연도 복사에 묶음 유지."""
|
||||||
|
year = 2060 + (int(RUN, 16) + 13) % 40
|
||||||
|
for y in (year, year + 1):
|
||||||
|
ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None
|
||||||
|
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
|
||||||
|
try:
|
||||||
|
assert ST.get_goal_board(year=year)["groups"] is True, "마이그레이션 016 적용 필요"
|
||||||
|
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
|
||||||
|
rows = lambda: [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||||
|
ids = lambda: [r["id"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
|
||||||
|
first = ids()[0]
|
||||||
|
assert req("PUT", f"/project/api/goals/rows/{first}", ADMIN, json={"label": "마케팅1"}).status_code == 200
|
||||||
|
add = lambda body: req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json=body) # noqa: E731
|
||||||
|
assert add({"ref_row_id": first, "place": "below", "same_label": True}).status_code == 201
|
||||||
|
assert rows()[:2] == [("마케팅1", False), ("", True)]
|
||||||
|
# 같은 항목 칸 위(첫 줄 위) — 새 줄이 첫 줄, 이름을 넘겨받고 예전 첫 줄은 이어 붙음
|
||||||
|
r = add({"ref_row_id": first, "place": "above", "same_label": True})
|
||||||
|
assert r.status_code == 201
|
||||||
|
assert rows()[:3] == [("마케팅1", False), ("", True), ("", True)], rows()
|
||||||
|
assert ids()[1] == first
|
||||||
|
assert add({"same_label": True}).status_code == 400 # 기준 줄 없음
|
||||||
|
# 묶인 줄 이동 거절
|
||||||
|
assert req("POST", f"/project/api/goals/rows/{first}/move", ADMIN, json={"direction": 1}).status_code == 400
|
||||||
|
# 묶음 첫 줄 삭제 → 다음 줄이 첫 줄 + 이름
|
||||||
|
head = ids()[0]
|
||||||
|
assert req("DELETE", f"/project/api/goals/rows/{head}", ADMIN).status_code == 200
|
||||||
|
assert rows()[:2] == [("마케팅1", False), ("", True)], rows()
|
||||||
|
# 새 연도 복사 — 묶음 유지
|
||||||
|
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year + 1}).status_code == 201
|
||||||
|
nxt = [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year + 1)["areas"][0]["rows"]]
|
||||||
|
assert nxt[:2] == [("마케팅1", False), ("", True)], nxt
|
||||||
|
# 항목 칸 나누기
|
||||||
|
r = req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", ADMIN)
|
||||||
|
assert r.status_code == 200 and r.json()["split"] == 1
|
||||||
|
assert rows()[:2] == [("마케팅1", False), ("", False)]
|
||||||
|
assert req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", BOB).status_code == 403
|
||||||
|
finally:
|
||||||
|
for y in (year, year + 1):
|
||||||
|
ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None
|
||||||
|
|
||||||
|
|
||||||
|
def test_goal_meetings():
|
||||||
|
"""주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기
|
||||||
|
(carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한."""
|
||||||
|
base = date(2001, 1, 1) + timedelta(days=7 * (int(RUN, 16) % 400)) # 월요일(앞선 회의록이 없을 먼 과거)
|
||||||
|
assert base.weekday() == 0
|
||||||
|
w1, w2 = base, base + timedelta(days=7)
|
||||||
|
for w in (w2, w1):
|
||||||
|
try:
|
||||||
|
ST.delete_meeting(week_start=w)
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
assert req("POST", f"/project/api/goals/meetings/{w1}", BOB, json={"year": w1.year}).status_code == 403
|
||||||
|
assert req("POST", f"/project/api/goals/meetings/{w1 + timedelta(days=1)}", ADMIN, json={}).status_code == 400
|
||||||
|
r = req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year})
|
||||||
|
assert r.status_code == 201 and r.json()["created"] is True, r.text
|
||||||
|
assert req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year}).json()["created"] is False
|
||||||
|
m1 = ST.get_meeting(week_start=w1)
|
||||||
|
secs = [s for s in dict.fromkeys(it["section"] for it in m1["items"])]
|
||||||
|
assert secs[:4] == ["상품", "마케팅", "컨텐츠", "유통"], secs
|
||||||
|
coupang = next(it for it in m1["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||||
|
assert coupang["marketplace_code"] == "coupang"
|
||||||
|
assert next(it for it in m1["items"] if it["section"] == "마케팅" and it["label"] == "네이버")["marketplace_code"] == ""
|
||||||
|
put = lambda iid, body, who=ADMIN: req("PUT", f"/project/api/goals/meeting-items/{iid}", who, json=body) # noqa: E731
|
||||||
|
r = put(coupang["id"], {"content": "추석 타임딜", "target_amount": "1,200만"})
|
||||||
|
assert r.status_code == 200 and r.json()["item"]["target_amount"] == 12_000_000, r.text
|
||||||
|
assert put(coupang["id"], {"target_amount": "abc"}).status_code == 400
|
||||||
|
assert put(coupang["id"], {"status": "bogus"}).status_code == 400
|
||||||
|
assert put(coupang["id"], {"content": "x"}, BOB).status_code == 403
|
||||||
|
assert req("PUT", f"/project/api/goals/meetings/{w1}", ADMIN,
|
||||||
|
json={"week_target": "3천만", "attendees": "대표", "notes": "메모"}).status_code == 200
|
||||||
|
# 다음 주 — 줄을 이어받고 전주 칸(prev)에 지난주 할 일·목표
|
||||||
|
assert req("POST", f"/project/api/goals/meetings/{w2}", ADMIN, json={"year": w2.year}).status_code == 201
|
||||||
|
m2 = ST.get_meeting(week_start=w2)
|
||||||
|
assert len(m2["items"]) == len(m1["items"]) and all(it["content"] == "" for it in m2["items"])
|
||||||
|
c2 = next(it for it in m2["items"] if it["carry_from"] == coupang["id"])
|
||||||
|
assert c2["prev"]["content"] == "추석 타임딜" and c2["prev"]["target_amount"] == 12_000_000
|
||||||
|
assert m2["prev_meeting"] == {"week_start": w1.isoformat(), "week_target": 30_000_000}
|
||||||
|
# 지난주 결과·평가는 지난 회의록 줄에 저장
|
||||||
|
assert put(coupang["id"], {"result_amount": "1.5억", "status": "done"}).json()["item"]["result_amount"] == 150_000_000
|
||||||
|
# 줄 추가(기준 줄 아래)·이동(같은 구역 안)·삭제, 새 구역
|
||||||
|
r = req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN,
|
||||||
|
json={"section": "유통", "label": "롯데온", "ref_item_id": c2["id"], "place": "below"})
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
new_id = r.json()["id"]
|
||||||
|
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
|
||||||
|
assert labels[labels.index("쿠팡") + 1] == "롯데온"
|
||||||
|
assert next(it for it in ST.get_meeting(week_start=w2)["items"] if it["id"] == new_id)["marketplace_code"] == "lotteon"
|
||||||
|
assert req("POST", f"/project/api/goals/meeting-items/{new_id}/move", ADMIN, json={"direction": -1}).status_code == 200
|
||||||
|
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
|
||||||
|
assert labels.index("롯데온") < labels.index("쿠팡")
|
||||||
|
assert req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN, json={"section": "물류"}).status_code == 201
|
||||||
|
assert ST.get_meeting(week_start=w2)["items"][-1]["section"] == "물류"
|
||||||
|
assert req("DELETE", f"/project/api/goals/meeting-items/{new_id}", ADMIN).status_code == 200
|
||||||
|
# 화면 — 그 달 주차 탭, 회의록 줄
|
||||||
|
page = req("GET", f"/project/goals/{w2.year}/meetings/{w2.month}?week={w2}", BOB)
|
||||||
|
assert page.status_code == 200 and page.text.startswith("project/goal_meeting.html"), page.text
|
||||||
|
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", BOB)
|
||||||
|
assert v.status_code == 200 and v.json()["meeting"]["week_start"] == w2.isoformat()
|
||||||
|
# 지난 회의록을 지우면 다음 주 전주 칸은 비고(carry_from NULL), 회의록은 남는다
|
||||||
|
assert req("DELETE", f"/project/api/goals/meetings/{w1}", ADMIN).status_code == 200
|
||||||
|
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w2)["items"])
|
||||||
|
finally:
|
||||||
|
for w in (w2, w1):
|
||||||
|
try:
|
||||||
|
ST.delete_meeting(week_start=w)
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _meet_weeks(seed: int, n: int) -> list[date]:
|
||||||
|
"""지난 주들(실적 기간이 "진행 전"이 아니게) — test_goal_meetings(2001~2008)와 겹치지 않는 2010~2018 의 월요일 n 개."""
|
||||||
|
base = date(2010, 1, 4) + timedelta(days=7 * ((int(RUN, 16) + seed * 60) % 400))
|
||||||
|
assert base.weekday() == 0
|
||||||
|
return [base + timedelta(days=7 * i) for i in range(n)]
|
||||||
|
|
||||||
|
|
||||||
|
def _drop_meetings(weeks: list[date]) -> None:
|
||||||
|
for w in weeks:
|
||||||
|
try:
|
||||||
|
ST.delete_meeting(week_start=w)
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _create_meeting(w: date) -> None:
|
||||||
|
r = req("POST", f"/project/api/goals/meetings/{w}", ADMIN, json={"year": w.year})
|
||||||
|
assert r.status_code == 201, r.text
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# [G4·G5] 회의록 "지난주" — 정확히 7일 전 주, 생성 순서·이름 변경·같은 이름·삭제/재생성과 무관(018 line_key)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def test_meeting_prev_week_links():
|
||||||
|
"""지난주 = 정확히 7일 전 주 회의록의 같은 연결키 줄. 018 미적용이면 carry_from 이 7일 전 주일 때만."""
|
||||||
|
w0, w1, w2, w3 = _meet_weeks(1, 4)
|
||||||
|
_drop_meetings([w0, w1, w2, w3])
|
||||||
|
with ST._pool.connection() as conn: # noqa: SLF001
|
||||||
|
keyed = ST._meeting_keys(conn) # noqa: SLF001
|
||||||
|
print(" meeting line_key(018):", "applied" if keyed else "not applied — carry_from fallback")
|
||||||
|
try:
|
||||||
|
# ① 역순 생성 — 다음 주(w3)를 먼저(양식), 앞 주(w2)를 나중에
|
||||||
|
_create_meeting(w3)
|
||||||
|
_create_meeting(w2)
|
||||||
|
m3 = ST.get_meeting(week_start=w3)
|
||||||
|
assert m3["prev_meeting"] is not None and m3["prev_meeting"]["week_start"] == w2.isoformat()
|
||||||
|
if keyed:
|
||||||
|
assert all(it["prev"] is not None for it in m3["items"]), "역순 생성인데 지난주 줄이 빠짐"
|
||||||
|
for it in m3["items"]:
|
||||||
|
assert it["prev"]["week_start"] == w2.isoformat()
|
||||||
|
assert (it["prev"]["section"], it["prev"]["label"]) == (it["section"], it["label"])
|
||||||
|
# 다른 구역의 같은 이름(마케팅 "네이버" ↔ 유통 "네이버")이 섞이지 않는다
|
||||||
|
navers = [it for it in m3["items"] if it["label"] == "네이버"]
|
||||||
|
assert len(navers) == 2 and len({it["prev"]["id"] for it in navers}) == 2
|
||||||
|
assert all(it["prev"]["section"] == it["section"] for it in navers)
|
||||||
|
else:
|
||||||
|
assert all(it["prev"] is None for it in m3["items"]), "018 미적용 — 역순 생성 연결은 안 됨(문서화된 제한)"
|
||||||
|
# ② 지난주(w2) 결과를 w2 줄에 저장 → w3 화면에서 보인다(그 주 데이터만)
|
||||||
|
m2 = ST.get_meeting(week_start=w2)
|
||||||
|
cou2 = next(it for it in m2["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||||
|
assert req("PUT", f"/project/api/goals/meeting-items/{cou2['id']}", ADMIN,
|
||||||
|
json={"content": "w2 쿠팡 행사", "target_amount": "100", "result_amount": "50"}).status_code == 200
|
||||||
|
cou3 = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||||
|
if keyed:
|
||||||
|
assert cou3["prev"]["id"] == cou2["id"] and cou3["prev"]["content"] == "w2 쿠팡 행사"
|
||||||
|
# ③ 이름 변경·순서 이동에도 연결 유지
|
||||||
|
assert req("PUT", f"/project/api/goals/meeting-items/{cou3['id']}", ADMIN, json={"label": "쿠팡 로켓"}).status_code == 200
|
||||||
|
assert req("POST", f"/project/api/goals/meeting-items/{cou3['id']}/move", ADMIN, json={"direction": -1}).status_code == 200
|
||||||
|
again = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["id"] == cou3["id"])
|
||||||
|
assert again["prev"]["id"] == cou2["id"]
|
||||||
|
# ④ 같은 이름의 새 줄은 지난주와 연결되지 않고, 기존 줄 연결도 그대로
|
||||||
|
r = req("POST", f"/project/api/goals/meetings/{w3}/items", ADMIN,
|
||||||
|
json={"section": "유통", "label": "쿠팡", "ref_item_id": cou3["id"], "place": "below"})
|
||||||
|
new_id = r.json()["id"]
|
||||||
|
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||||
|
assert items3[new_id]["prev"] is None and items3[cou3["id"]]["prev"]["id"] == cou2["id"]
|
||||||
|
# ⑤ 앞 주 삭제 → 지난주 칸 빔, 다시 만들면(앞선 회의록 없음 → 다음 주 w3 양식·키) 다시 연결
|
||||||
|
ST.delete_meeting(week_start=w2)
|
||||||
|
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w3)["items"])
|
||||||
|
_create_meeting(w2)
|
||||||
|
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
|
||||||
|
assert items3[cou3["id"]]["prev"] is not None and items3[cou3["id"]]["prev"]["week_start"] == w2.isoformat()
|
||||||
|
assert items3[cou3["id"]]["prev"]["content"] == "" # 새 회의록 — 예전 글이 섞이지 않는다
|
||||||
|
# ⑥ 한 주 건너뜀 — w0 를 만들고 w1 없이 w2 를 보면 지난주(w1) 자료 없음(w0 결과를 지난주로 보이지 않음)
|
||||||
|
_drop_meetings([w2, w3])
|
||||||
|
_create_meeting(w0)
|
||||||
|
cou0 = next(it for it in ST.get_meeting(week_start=w0)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
|
||||||
|
req("PUT", f"/project/api/goals/meeting-items/{cou0['id']}", ADMIN, json={"target_amount": "100", "result_amount": "50"})
|
||||||
|
_create_meeting(w2)
|
||||||
|
m2 = ST.get_meeting(week_start=w2)
|
||||||
|
assert m2["prev_meeting"] is None and all(it["prev"] is None for it in m2["items"])
|
||||||
|
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||||
|
assert v["head"]["prev_exists"] is False and v["head"]["prev_target"] is None
|
||||||
|
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||||
|
# w1 을 만들면 w2 의 지난주 = w1(그 주 줄, 비어 있음) — w0 의 50/100 이 아니다
|
||||||
|
_create_meeting(w1)
|
||||||
|
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
|
||||||
|
assert v["head"]["prev_exists"] is True
|
||||||
|
prevs = [it["prev"] for it in v["meeting"]["items"] if it["prev"]]
|
||||||
|
if keyed:
|
||||||
|
assert prevs and all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||||
|
assert all(p["week_start"] == w1.isoformat() for p in prevs)
|
||||||
|
assert all(it["rate"] is None for it in v["meeting"]["items"])
|
||||||
|
finally:
|
||||||
|
_drop_meetings([w0, w1, w2, w3])
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# [G6] 실적 조회 장애 ≠ 0원 — 목록 장애·매출 조회 장애·부분 실패·정상 0건·미연결·집계 쇼핑몰 없음
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
class _FakePerf:
|
||||||
|
def __init__(self, *, list_error=False, sales_error=None, markets=None, amounts=None):
|
||||||
|
self.list_error, self.sales_error = list_error, sales_error or (lambda a, b: False)
|
||||||
|
self.markets = markets if markets is not None else [
|
||||||
|
{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True}]
|
||||||
|
self.amounts = amounts or {}
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
if self.list_error:
|
||||||
|
raise RuntimeError("perf db down")
|
||||||
|
return self.markets
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
self.calls.append((start, end))
|
||||||
|
if self.sales_error(start, end):
|
||||||
|
raise RuntimeError("sales query failed")
|
||||||
|
return {(d, c): v for (d, c), v in self.amounts.items() if start <= d <= end and c in codes}
|
||||||
|
|
||||||
|
def statuses(self):
|
||||||
|
return {"coupang": {"last_success_sync_at": "2026-10-01T14:20:00+09:00"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_meeting_perf_unknown_vs_zero():
|
||||||
|
"""실적 모듈 장애는 미확인(None + head.unknown), 정상 무매출만 0. 의존하는 필요 매출·달성률도 미확인."""
|
||||||
|
from app.modules.project import store
|
||||||
|
|
||||||
|
(w,) = _meet_weeks(2, 1)
|
||||||
|
# 그 달 셋째 주 — 월 누적(1일~지난주 일요일)과 전주 결과(지난주 월~일) 조회 기간이 서로 다르게
|
||||||
|
weeks = store.month_weeks(w.year, w.month)
|
||||||
|
w = weeks[2][0]
|
||||||
|
month_first = date(w.year, w.month, 1)
|
||||||
|
_drop_meetings([w, w - timedelta(days=7)])
|
||||||
|
orig_targets = ST.goal_month_targets
|
||||||
|
ST.goal_month_targets = lambda **kw: {"sales_unit": "원", "sales_target": 1000.0, "sales_actual": None, "roas_target": None}
|
||||||
|
try:
|
||||||
|
_create_meeting(w - timedelta(days=7))
|
||||||
|
_create_meeting(w)
|
||||||
|
prev = ST.get_meeting(week_start=w - timedelta(days=7))
|
||||||
|
cou_prev = next(it for it in prev["items"] if it["label"] == "쿠팡")
|
||||||
|
req("PUT", f"/project/api/goals/meeting-items/{cou_prev['id']}", ADMIN, json={"target_amount": "100"})
|
||||||
|
url = f"/project/api/goals/meetings/{w}?year={w.year}&month={w.month}"
|
||||||
|
|
||||||
|
def view(perf):
|
||||||
|
APP.state.performance_store = perf
|
||||||
|
try:
|
||||||
|
r = req("GET", url, ADMIN)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
return r.json()
|
||||||
|
finally:
|
||||||
|
APP.state.performance_store = None
|
||||||
|
|
||||||
|
def coupang_row(v):
|
||||||
|
return next(it for it in v["meeting"]["items"] if it["label"] == "쿠팡" and it["section"] == "유통")
|
||||||
|
|
||||||
|
# 실적 모듈 미연결 — perf False, 값 없음(미확인 아님)
|
||||||
|
v = view(None)
|
||||||
|
assert v["head"]["perf"] is False and v["head"]["perf_state"] == "off" and v["head"]["unknown"] == []
|
||||||
|
# 쇼핑몰 목록 장애 — 0 이 아니라 미확인, 필요 매출도 계산하지 않음, 회의록은 열림
|
||||||
|
v = view(_FakePerf(list_error=True))
|
||||||
|
h = v["head"]
|
||||||
|
assert h["perf"] is True and h["perf_state"] == "error"
|
||||||
|
assert h["mtd"] is None and h["prev_result"] is None and h["need_per_week"] is None
|
||||||
|
assert {"mtd", "prev_result"} <= set(h["unknown"]), h
|
||||||
|
row = coupang_row(v)
|
||||||
|
assert row["prev"]["auto_error"] is True and row["prev"]["result"] is None and row["rate"] is None
|
||||||
|
assert row["market_unknown"] is True and row["market_off"] is False
|
||||||
|
assert v["markets"] == []
|
||||||
|
# 매출 조회 장애(목록은 정상) — 전부 미확인
|
||||||
|
v = view(_FakePerf(sales_error=lambda a, b: True))
|
||||||
|
h = v["head"]
|
||||||
|
assert h["perf_state"] == "ok" and h["mtd"] is None and h["need_per_week"] is None
|
||||||
|
assert {"mtd", "prev_result"} <= set(h["unknown"])
|
||||||
|
assert coupang_row(v)["prev"]["auto_error"] is True and coupang_row(v)["rate"] is None
|
||||||
|
# 정상 조회 0 건 — 진짜 0원(미확인 아님), 필요 매출 = 목표 ÷ 남은 주
|
||||||
|
v = view(_FakePerf())
|
||||||
|
h = v["head"]
|
||||||
|
assert h["mtd"] == 0 and h["prev_result"] == 0 and h["unknown"] == [], h
|
||||||
|
assert h["need_per_week"] == 1000 // h["weeks_left"]
|
||||||
|
row = coupang_row(v)
|
||||||
|
assert row["prev"]["auto_result"] == 0 and row["prev"]["auto_error"] is False and row["rate"] == 0.0
|
||||||
|
assert h["fresh_oldest"] == "10/01 14:20" and "쿠팡 10/01 14:20" in h["fresh_tip"]
|
||||||
|
# 부분 실패 — 월 누적(1일부터) 조회만 실패: 누적·필요 매출만 미확인, 전주 결과·줄 결과는 정상
|
||||||
|
prev_start = w - timedelta(days=7)
|
||||||
|
v = view(_FakePerf(sales_error=lambda a, b: a == month_first and a != prev_start,
|
||||||
|
amounts={(prev_start, "coupang"): 70}))
|
||||||
|
h = v["head"]
|
||||||
|
assert "mtd" in h["unknown"] and "prev_result" not in h["unknown"], h
|
||||||
|
assert h["mtd"] is None and h["need_per_week"] is None and h["prev_result"] == 70
|
||||||
|
assert coupang_row(v)["prev"]["auto_result"] == 70 and coupang_row(v)["rate"] == 70.0
|
||||||
|
# 매출 집계 쇼핑몰 없음 — 0 원으로 보이지 않게(empty, 미확인도 아님)
|
||||||
|
v = view(_FakePerf(markets=[{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": False}]))
|
||||||
|
assert v["head"]["perf_state"] == "empty" and v["head"]["mtd"] is None and v["head"]["unknown"] == []
|
||||||
|
# 금주 목표 저장 응답 = 서버 확정값(원 정수)
|
||||||
|
r = req("PUT", f"/project/api/goals/meetings/{w}", ADMIN, json={"week_target": "120만"})
|
||||||
|
assert r.status_code == 200 and r.json()["week_target"] == 1_200_000
|
||||||
|
finally:
|
||||||
|
ST.goal_month_targets = orig_targets
|
||||||
|
_drop_meetings([w, w - timedelta(days=7)])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
if not ENABLED:
|
if not ENABLED:
|
||||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||||
|
|||||||
Reference in New Issue
Block a user