diff --git a/.gitignore b/.gitignore index 56d90a8..eeeb312 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,8 @@ KING-DESKTOP.XML # Excel 가 파일을 열 때 만드는 잠금 파일 ~$* + +# 테스트 도구(docs/TESTING.md) +.pytest_cache/ +tests/js/node_modules/ +tests/js/package-lock.json diff --git a/app/modules/cafe24/tests/test_cafe24.py b/app/modules/cafe24/tests/test_cafe24.py index 1aafc91..ceba0e7 100644 --- a/app/modules/cafe24/tests/test_cafe24.py +++ b/app/modules/cafe24/tests/test_cafe24.py @@ -25,8 +25,25 @@ SECRET = "unit-test-secret" # wait_for_description 은 실물 카페24 API 의 쓰기 직후 읽기 지연을 흡수하려고 # 실제로 sleep 한다. 가짜 클라이언트는 그 지연을 재현하지 않으므로(항상 같은 # 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로 -# 기다릴 필요는 없다. -products.time.sleep = lambda *_a, **_k: None +# 기다릴 필요는 없다. products.time 은 공유 time 모듈이라 import 때 바꾸면 다른 테스트의 +# time.sleep 까지 바뀐다 — 이 파일 테스트 동안만 바꾼다(pytest fixture / 직접 실행은 _run_all, 검토 F10). +_NO_SLEEP = lambda *_a, **_k: None # noqa: E731 + +try: + import pytest +except ImportError: # 직접 실행은 pytest 없이도 돈다 + pytest = None + +if pytest is not None: + @pytest.fixture(autouse=True, scope="module") + def _no_sleep_in_this_file(): + prev = products.time.sleep + products.time.sleep = _NO_SLEEP + try: + yield + finally: + products.time.sleep = prev + # 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히. logging.getLogger("cafe24").setLevel(logging.CRITICAL) @@ -1725,6 +1742,7 @@ def test_client_maybe_applied_classification(): def _run_all(): + products.time.sleep = _NO_SLEEP # 직접 실행 = 이 프로세스는 이 파일 테스트만 fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)] for fn in fns: fn() diff --git a/app/modules/notice/db.py b/app/modules/notice/db.py index 77b62c7..bd25f8a 100644 --- a/app/modules/notice/db.py +++ b/app/modules/notice/db.py @@ -2,7 +2,7 @@ from __future__ import annotations -from datetime import datetime +from datetime import datetime, timezone from typing import Any from psycopg import errors as psycopg_errors @@ -17,6 +17,12 @@ def _iso(v: Any) -> str: return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else "" +def _version(v: Any) -> str: + """공지 내용 버전 = updated_at(마이크로초까지, UTC) — 고치기·취소 때마다 바뀐다. 받는 사람 화면이 바뀐 내용을 다시 그리고, + [확인]이 어느 내용을 읽고 누른 것인지 서버가 가린다(2026-10-15 검토 F07).""" + return v.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S%f") if isinstance(v, datetime) else "" + + class NoticeStore: def __init__(self, pool: Any) -> None: self._pool = pool @@ -39,6 +45,7 @@ class NoticeStore: "show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]), "created_by": r["created_by"], "created_at": _iso(r["created_at"]), "updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")), + "version": _version(r.get("updated_at")), "cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "", } @@ -167,14 +174,37 @@ class NoticeStore: self._run(run) return self.get_notice(notice_id=notice_id) # type: ignore[return-value] - def ack(self, *, notice_id: int, email: str) -> bool: - """[확인] — 처음이면 True(이미 확인했으면 False). 받는 사람·표시 시각 확인은 라우터가 먼저 한다.""" - def run() -> bool: + def ack(self, *, notice_id: int, email: str, version: str | None = None, now: datetime | None = None) -> str: + """[확인] — 결과: "acked"(처음) · "already"(이미 확인 — 여러 번 눌러도 한 번) · "stale"(그 사이 내용이 바뀜 — 읽은 + version 이 지금과 다름) · "denied"(받는 사람이 아님·띄울 시각 전·취소·없음). + + 받는 사람·표시 시각·취소 확인과 기록이 **한 트랜잭션**(2026-10-15 검토 F08): 공지 행을 FOR SHARE 로 잠그고 조건을 본 뒤 + 기록한다 — 동시에 취소·고치기가 들어오면 그 쪽이 먼저 끝나거나(그러면 바뀐 행으로 다시 판정) 이 기록 뒤로 기다린다. + version 이 없으면(예전 화면) 내용 확인은 건너뛴다.""" + em = pj_store.norm_str(email, lower=True) + + def run() -> str: with self._conn() as conn: - r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) " - "ON CONFLICT DO NOTHING RETURNING notice_id", - (notice_id, pj_store.norm_str(email, lower=True))).fetchone() - return r is not None + with conn.transaction(): + n = conn.execute( + "SELECT n.id, n.updated_at FROM urgent_notices n " + "WHERE n.id = %s AND n.cancelled_at IS NULL AND n.show_at <= %s " + " AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t " + " WHERE t.notice_id = n.id AND t.user_email = %s)) " + "FOR SHARE OF n", + (notice_id, now or datetime.now(KST), em), + ).fetchone() + if n is None: + return "denied" + done = conn.execute("SELECT 1 FROM urgent_notice_acks WHERE notice_id = %s AND user_email = %s", + (notice_id, em)).fetchone() + if done is not None: + return "already" + if version and version != _version(n["updated_at"]): + return "stale" + r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) " + "ON CONFLICT DO NOTHING RETURNING notice_id", (notice_id, em)).fetchone() + return "acked" if r is not None else "already" return self._run(run) # ── 이미지 ────────────────────────────────────────────── diff --git a/app/modules/notice/router.py b/app/modules/notice/router.py index c0055f5..54b248e 100644 --- a/app/modules/notice/router.py +++ b/app/modules/notice/router.py @@ -62,7 +62,7 @@ def _call(fn: Any, **kw: Any) -> Any: def _public(n: dict[str, Any]) -> dict[str, Any]: """받는 사람 화면에 보내는 값 — 받는 사람 목록·확인 현황은 빼고.""" - return {k: n[k] for k in ("id", "title", "body_html", "show_at", "created_by")} + return {k: n.get(k, "") for k in ("id", "title", "body_html", "show_at", "created_by", "version")} # ── 화면 ───────────────────────────────────────────────────── @@ -100,15 +100,18 @@ def api_pending(request: Request) -> JSONResponse: @router.post("/api/{notice_id}/ack") -def api_ack(request: Request, notice_id: int) -> JSONResponse: - """[확인] — 받는 사람이고 이미 띄워진(취소 안 된) 공지만. 여러 번 눌러도 한 번 기록.""" +def api_ack(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse: + """[확인] — 받는 사람이고 띄울 시각이 지난, 취소 안 된 공지만(검증과 기록을 저장소가 한 트랜잭션에서, 검토 F08). + 여러 번 눌러도 한 번 기록. payload.version = 화면에 띄운 내용의 버전 — 그 사이 고쳐졌으면 409(바뀐 내용을 다시 읽게, F07).""" user = _user(request) st = _store(request) - n = _call(st.get_notice, notice_id=notice_id) - if n is None or not st.is_recipient(notice=n, email=user["email"]): + version = str((payload or {}).get("version") or "").strip() or None + result = _call(st.ack, notice_id=notice_id, email=user["email"], version=version) + if result == "denied": raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.") - _call(st.ack, notice_id=notice_id, email=user["email"]) - return JSONResponse({"ok": True}) + if result == "stale": + raise HTTPException(status_code=409, detail="공지 내용이 수정되었습니다. 바뀐 내용을 확인한 뒤 다시 [확인]을 눌러 주세요.") + return JSONResponse({"ok": True, "result": result}) @router.get("/images/{image_id}") diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html index 11d8ae6..0de3232 100644 --- a/app/modules/notice/templates/notice/admin.html +++ b/app/modules/notice/templates/notice/admin.html @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/performance/adapters/base.py b/app/modules/performance/adapters/base.py index 3b80c69..c338b1d 100644 --- a/app/modules/performance/adapters/base.py +++ b/app/modules/performance/adapters/base.py @@ -131,6 +131,16 @@ class SaleEvent: raise ValueError("취소/반품 금액은 음수(또는 0)여야 합니다.") +def credential_fingerprint(credentials: Any, keys: Iterable[str]) -> str: + """토큰을 발급한 인증정보 묶음의 지문(SHA-256 16진수) — 원문은 남기지 않는다(2026-10-15 검토 F04). + 저장된 토큰은 이 지문이 지금 인증정보(연결 테스트의 새 입력값 포함)와 같을 때만 다시 쓴다 — + 계정·키를 바꾸면 이전 계정 토큰을 쓰지 않고, 같은 값을 다시 저장하면 토큰을 새로 받지 않는다.""" + import hashlib # noqa: WPS433 + + raw = "\x1f".join(f"{k}={(credentials.get(k) or '').strip()}" for k in keys) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + class CredentialAccessor(Protocol): def get(self, key: str) -> str: ... diff --git a/app/modules/performance/adapters/coupang.py b/app/modules/performance/adapters/coupang.py index 4af7927..18d1419 100644 --- a/app/modules/performance/adapters/coupang.py +++ b/app/modules/performance/adapters/coupang.py @@ -70,6 +70,12 @@ KST_OFFSET = timedelta(hours=9) class GatewayTimeout(ApiError): """쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다.""" + + +class TooManyPages(ApiError): + """한 번 조회가 끝까지 받았는지 확인되지 않음(쪽 수 상한·커서 반복) — 조회 기간을 줄여 다시 부른다(F05).""" + + # 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목) PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"}) PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"}) @@ -300,6 +306,11 @@ class CoupangAdapter(MarketplaceAdapter): try: body = res.json() except ValueError: + if res.status_code < 400: + # HTTP 200 이어도 JSON 이 아니면(점검·프록시 안내 페이지 등) 수집 실패 — 빈 목록으로 보면 기간 교체 때 + # 그 기간 매출이 지워진다(2026-10-15 검토 F01). 오류 응답(4xx·5xx)은 아래에서 글자로 안내한다. + raise ApiError(f"쿠팡 {what} 응답이 JSON 이 아닙니다(HTTP {res.status_code}) — 점검 중일 수 있어 " + "저장하지 않았습니다. 잠시 뒤 다시 시도하세요.") from None body = {} if not isinstance(body, dict): body = {"data": body} @@ -321,18 +332,38 @@ class CoupangAdapter(MarketplaceAdapter): return body raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.") + @staticmethod + def _page_rows(body: dict[str, Any], what: str) -> list[dict[str, Any]]: + """한 쪽의 주문 목록 — `data` 가 목록이어야 한다. 목록이 아니면 빈 목록(주문 0건)과 구분해 실패로(F01): + `data` 가 없거나 다른 형식이면 오류, `data: null` 은 성공 표시(code 200·OK/SUCCESS)가 함께 있을 때만 빈 목록.""" + data = body.get("data") + if isinstance(data, list): + return [r for r in data if isinstance(r, dict)] + code, msg = body.get("code"), str(body.get("message") or "").strip().upper() + if "data" in body and data is None and (code in (200, "200") or msg in ("OK", "SUCCESS")): + return [] + raise ApiError(f"쿠팡 {what} 응답 형식이 예상과 다릅니다(주문 목록 data 없음) — 저장하지 않았습니다. 잠시 뒤 다시 시도하세요.") + def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]: + """nextToken 으로 끝까지 받는다. 끝(다음 쪽 없음)을 확인하지 못하면 TooManyPages — 일부만 받은 목록으로 + 기간을 교체하지 않게(2026-10-15 검토 F05). 부르는 쪽이 기간을 나눠 다시 부른다. + - MAX_PAGES 를 다 써도 다음 쪽이 남음 · 같은 nextToken 이 다시 옴(커서 반복) → TooManyPages + - 빈 쪽인데 다음 쪽이 있으면 따라간다(예전엔 거기서 끝난 것으로 봤다)""" + what = "로켓그로스 주문" if rg else "발주서" out: list[dict[str, Any]] = [] token: str | None = None + seen: set[str] = set() for _ in range(MAX_PAGES): body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg) - rows = [r for r in (body.get("data") or []) if isinstance(r, dict)] if isinstance(body.get("data"), list) else [] - out.extend(rows) + out.extend(self._page_rows(body, what)) nxt = str(body.get("nextToken") or "").strip() - if not nxt or not rows or nxt == token: - break + if not nxt: + return out # 마지막 쪽 확인 + if nxt in seen: + raise TooManyPages(f"쿠팡 {what} 다음 쪽 표시가 반복돼 끝까지 받았는지 확인할 수 없습니다 — 저장하지 않았습니다.") + seen.add(nxt) token = nxt - return out + raise TooManyPages(f"쿠팡 {what} 한 번 조회가 {MAX_PAGES}쪽을 넘었습니다 — 일부만 받은 채 저장하지 않았습니다.") def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]: """판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가. @@ -362,6 +393,11 @@ class CoupangAdapter(MarketplaceAdapter): continue raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] " "— 잠시 뒤 다시 시도하세요.") from None + except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패 + if size_by_status[st] > 1: + size_by_status[st] = max(1, size_by_status[st] // 2) + continue + raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루, 상태 {st}]") from None except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게 raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None rows.extend(part) @@ -391,6 +427,11 @@ class CoupangAdapter(MarketplaceAdapter): continue raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] " "— 잠시 뒤 다시 시도하세요.") from None + except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패 + if size > 1: + size = max(1, size // 2) + continue + raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루]") from None except ApiError as exc: raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None rows.extend(part) diff --git a/app/modules/performance/adapters/gsshop.py b/app/modules/performance/adapters/gsshop.py index f71ffdc..5d26eca 100644 --- a/app/modules/performance/adapters/gsshop.py +++ b/app/modules/performance/adapters/gsshop.py @@ -36,6 +36,7 @@ from datetime import date, datetime, timedelta from typing import Any, Iterable from .base import ( + credential_fingerprint, AdapterContext, AdapterError, ApiError, @@ -143,7 +144,8 @@ class GsshopAdapter(MarketplaceAdapter): "운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.") def __init__(self) -> None: - self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드) + # (협력사코드·운영 KEY 지문) → 통과한 (키 변형, 암호화 모드). 키를 바꾸면 예전 방식을 쓰지 않는다(검토 F04) + self._mode: dict[str, tuple[str, str]] = {} def credential_fields(self) -> list[CredentialField]: # 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게. @@ -191,7 +193,8 @@ class GsshopAdapter(MarketplaceAdapter): def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]: """토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다.""" sup, key = self._creds(ctx) - known = self._mode.get(sup) + mode_key = self._mode_key(ctx) + known = self._mode.get(mode_key) if known: return self._call(ctx, path, params, known) tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES] @@ -202,7 +205,7 @@ class GsshopAdapter(MarketplaceAdapter): except AuthFailed as exc: last = exc continue - self._mode[sup] = how + self._mode[mode_key] = how return body raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. " "협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.") @@ -220,6 +223,9 @@ class GsshopAdapter(MarketplaceAdapter): out.extend(rows) if not body.get("hasMorePage") or not rows: break + else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 기간을 교체하지 않게(검토 F05) + raise ApiError(f"GS샵 {s.isoformat()}~{e.isoformat()} 조회가 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — " + "저장하지 않았습니다.") ctx.progress.step(items=len(out)) s = e + timedelta(days=1) return out @@ -261,15 +267,19 @@ class GsshopAdapter(MarketplaceAdapter): self.authenticate(ctx) sup, _ = self._creds(ctx) - self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다 + self._mode.pop(self._mode_key(ctx), None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다 day = today_kst() - timedelta(days=1) body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10}) total = body.get("totalCount") return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, " - f"토큰 {self._how_label(sup)}).") + f"토큰 {self._how_label(ctx)}).") - def _how_label(self, sup: str) -> str: - v, m = self._mode.get(sup, ("", "")) + @staticmethod + def _mode_key(ctx: AdapterContext) -> str: + return credential_fingerprint(ctx.credentials, ("vendor_code", "api_key")) + + def _how_label(self, ctx: AdapterContext) -> str: + v, m = self._mode.get(self._mode_key(ctx), ("", "")) return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}" # ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ───────── diff --git a/app/modules/performance/adapters/kakao.py b/app/modules/performance/adapters/kakao.py index 3f341c7..58959b7 100644 --- a/app/modules/performance/adapters/kakao.py +++ b/app/modules/performance/adapters/kakao.py @@ -264,6 +264,7 @@ class KakaoAdapter(MarketplaceAdapter): "size": PAGE_SIZE} out: list[dict[str, Any]] = [] token = "" + seen: set[str] = set() for _ in range(MAX_PAGES): body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})}) rows = [r for r in body.get("contents") or [] if isinstance(r, dict)] @@ -271,6 +272,11 @@ class KakaoAdapter(MarketplaceAdapter): token = str(body.get("token") or "") if not token or not rows: break + if token in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05) + raise ApiError(f"카카오 {d.isoformat()} 주문 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.") + seen.add(token) + else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 + raise ApiError(f"카카오 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]: diff --git a/app/modules/performance/adapters/naver.py b/app/modules/performance/adapters/naver.py index e979b7e..88eb51a 100644 --- a/app/modules/performance/adapters/naver.py +++ b/app/modules/performance/adapters/naver.py @@ -28,6 +28,7 @@ from datetime import date, datetime, timedelta from typing import Any, Iterable from .base import ( + credential_fingerprint, AdapterContext, AdapterError, ApiError, @@ -200,6 +201,9 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic return orders +# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint) +TOKEN_KEYS = ("client_id", "client_secret", "account_id") + class NaverAdapter(MarketplaceAdapter): code = "naver" name = "네이버" @@ -222,6 +226,8 @@ class NaverAdapter(MarketplaceAdapter): help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"), CredentialField("access_token", "Access Token", secret=True, required=False, internal=True), CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True), + # 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04) + CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True), ] # ── 인증 ────────────────────────────────────────────── @@ -233,7 +239,8 @@ class NaverAdapter(MarketplaceAdapter): 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: + same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS) + if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC: return tok return self._issue_token(ctx) @@ -266,6 +273,7 @@ class NaverAdapter(MarketplaceAdapter): expires_in = _won(body.get("expires_in")) or 3 * 3600 ctx.credentials.set("access_token", tok) ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in)) + ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS)) return tok def authenticate(self, ctx: AdapterContext) -> None: @@ -340,6 +348,8 @@ class NaverAdapter(MarketplaceAdapter): out.extend(items) if not items or not has_next(body, page, len(items)): break + else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 저장하지 않게(검토 F05) + raise ApiError(f"네이버 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: diff --git a/app/modules/performance/adapters/toss.py b/app/modules/performance/adapters/toss.py index 1ba3d1a..22e28e3 100644 --- a/app/modules/performance/adapters/toss.py +++ b/app/modules/performance/adapters/toss.py @@ -37,6 +37,7 @@ from datetime import date, datetime, timedelta, timezone from typing import Any, Iterable from .base import ( + credential_fingerprint, AdapterContext, AdapterError, ApiError, @@ -245,6 +246,9 @@ def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: return fields +# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint) +TOKEN_KEYS = ("api_key", "api_secret") + class TossAdapter(MarketplaceAdapter): code = "toss" name = "토스쇼핑" @@ -268,6 +272,8 @@ class TossAdapter(MarketplaceAdapter): 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), + # 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04) + CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True), ] # ── 인증 ────────────────────────────────────────────── @@ -279,7 +285,8 @@ class TossAdapter(MarketplaceAdapter): 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: + same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS) + if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC: return tok return self._issue_token(ctx) @@ -308,6 +315,7 @@ class TossAdapter(MarketplaceAdapter): 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)) + ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS)) return tok def authenticate(self, ctx: AdapterContext) -> None: @@ -383,6 +391,7 @@ class TossAdapter(MarketplaceAdapter): params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE} out: list[dict[str, Any]] = [] cursor = None + seen: set[str] = set() 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)] @@ -390,6 +399,11 @@ class TossAdapter(MarketplaceAdapter): cursor = body.get("nextCursor") if not cursor or not rows: break + if str(cursor) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05) + raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.") + seen.add(str(cursor)) + else: + raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]: @@ -398,6 +412,7 @@ class TossAdapter(MarketplaceAdapter): "toDate": b.isoformat(), "size": SETTLEMENT_SIZE} out: list[dict[str, Any]] = [] token = None + seen: set[str] = set() 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)] @@ -405,12 +420,18 @@ class TossAdapter(MarketplaceAdapter): token = body.get("nextToken") if not token or not rows: break + if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05) + raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.") + seen.add(str(token)) + else: + raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]: """클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지.""" out: list[dict[str, Any]] = [] token = None + seen: set[str] = set() 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)] @@ -418,6 +439,11 @@ class TossAdapter(MarketplaceAdapter): token = body.get("nextToken") if not token or not rows or body.get("hasNext") is False: break + if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05) + raise ApiError("토스 클레임 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.") + seen.add(str(token)) + else: + raise ApiError(f"토스 클레임 목록이 {CLAIM_MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out @staticmethod diff --git a/app/modules/performance/credentials.py b/app/modules/performance/credentials.py index 153f551..f718c66 100644 --- a/app/modules/performance/credentials.py +++ b/app/modules/performance/credentials.py @@ -140,13 +140,17 @@ class CredentialService: """빈 칸 = 기존 값 유지. clear 에 든 항목은 삭제. 저장한 항목 키 목록 반환.""" allowed = {f.key for f in adapter.visible_fields()} ring = self._ring_loader() + rows = self._store.credential_rows(adapter.code) saved = [] + changed = False # 화면 항목이 실제로 바뀌었나 — 바뀌었으면 그 인증정보로 받은 토큰 등 내부 값을 지운다(F04) for key, raw in values.items(): if key not in allowed: continue v = (raw or "").strip() if not v: continue + if not changed and self._stored_value(adapter.code, key, rows) != v: + changed = True self._store.upsert_credential( adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring), key_version=ring.current_version, user=user, @@ -154,9 +158,27 @@ class CredentialService: saved.append(key) for key in clear or []: if key in allowed and key not in saved: + if key in rows: + changed = True self._store.delete_credential(adapter.code, key) + if changed: + # 계정·키가 바뀌면 예전 계정으로 받은 토큰·만료 시각을 남기지 않는다. 같은 값을 다시 저장했으면 그대로 둔다 + # (토큰을 불필요하게 다시 받지 않게). 어댑터도 토큰을 발급 인증정보 지문에 묶어 한 번 더 막는다. + for f in adapter.credential_fields(): + if f.internal and f.key in rows: + self._store.delete_credential(adapter.code, f.key) return saved + def _stored_value(self, code: str, key: str, rows: dict[str, Any]) -> str | None: + """저장된 값 원문(서버 안에서만, 비교용) — 없거나 복호화할 수 없으면 None(= 바뀐 것으로 본다).""" + row = rows.get(key) + if not row: + return None + try: + return decrypt(row["encrypted_value"], aad=aad_for(code, key, self._ns), ring=self._ring_loader()) + except Exception: # noqa: BLE001 — 키 교체·손상 등: 비교할 수 없으니 바뀐 것으로 + return None + # ── 마스터 키 교체 후 재암호화 ───────────────────────── def reencrypt_all(self) -> dict[str, int]: """예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수).""" diff --git a/app/modules/performance/jobs.py b/app/modules/performance/jobs.py index f359d8e..632ca3e 100644 --- a/app/modules/performance/jobs.py +++ b/app/modules/performance/jobs.py @@ -93,6 +93,17 @@ class ShopProgress(Progress): with self._lock: self.state = "saving" + def begin_saving(self) -> None: + """수집이 끝나 저장으로 넘어간다 — 중지·취소 확인과 running → saving 전환을 **같은 잠금 안에서** 한다. + stop() 도 같은 잠금으로 state 를 보고 받아들이므로, [중지]가 이 전환보다 먼저면 여기서 Cancelled(저장 안 함), + 나중이면 stop() 이 False(저장 중이라 중지 불가)를 돌려준다 — 둘 다 받아들여지는 틈이 없다(2026-10-15 검토 F06). + 마지막 API 호출 중이나 collect() 정리 중에 받아들인 [중지]도 여기서 반영된다.""" + with self._lock: + if self.cancel_requested: + raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else + "사용자가 업데이트를 취소했습니다.") + self.state = "saving" + def finish(self, *, upserted: int, message: str = "") -> None: with self._lock: self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok" diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 17a8aff..ac85216 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -609,8 +609,7 @@ def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Bo src = _ad_source_or_404(code) _, ad_sync = _ad_services(store) values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()} - allowed = {f.key for f in src.visible_fields()} - cleared = {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values} + cleared = _cleared_keys(src, payload, values) return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None)) @@ -759,15 +758,23 @@ def api_save_credentials(request: Request, code: str, payload: dict[str, Any] = @router.post("/api/marketplaces/{code}/test") def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse: - """values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용).""" + """values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용), clear = 화면에서 비운 항목은 빈 값으로. + 광고 API 시험(/api/ad-sources/{code}/test)과 같은 요청·응답 계약 — 공통 설정 창이 둘 다 쓴다(검토 F09).""" store, user = common.require_store(request, admin=True) adapter = _code_or_404(store, code) _, sync = common.services(request, store) values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()} - result = sync.test_connection(code, values=values or None, user=user["email"]) + cleared = _cleared_keys(adapter, payload, values) + result = sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None) return JSONResponse(result) +def _cleared_keys(source: Any, payload: dict[str, Any], values: dict[str, str]) -> set[str]: + """요청의 clear 중 이 연동의 화면 항목이면서 새 값이 없는 것 — 연결 시험에서 빈 값으로 본다.""" + allowed = {f.key for f in source.visible_fields()} + return {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values} + + @router.get("/api/marketplaces/{code}/reconcile") def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse: """쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다.""" diff --git a/app/modules/performance/sync.py b/app/modules/performance/sync.py index f241165..91780d9 100644 --- a/app/modules/performance/sync.py +++ b/app/modules/performance/sync.py @@ -58,8 +58,8 @@ class SyncService: self._app_state = app_state def _ctx(self, adapter: MarketplaceAdapter, *, overrides: dict[str, str] | None = None, - persist: bool = True, user: str = "") -> AdapterContext: - acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user) + persist: bool = True, user: str = "", cleared: set[str] | None = None) -> AdapterContext: + acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user, cleared=cleared) return AdapterContext(code=adapter.code, credentials=acc, app_state=self._app_state) @staticmethod @@ -72,15 +72,17 @@ class SyncService: return "api_error", redact_text(f"예상하지 못한 오류: {type(exc).__name__}: {exc}", known) # ── 연결 테스트 ───────────────────────────────────────── - def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]: - """values 를 주면 저장하지 않은 새 입력값으로 시험(저장된 상태는 바꾸지 않음).""" + def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "", + cleared: set[str] | None = None) -> dict[str, Any]: + """values 를 주면 저장하지 않은 새 입력값으로, cleared = 화면에서 비운 항목은 저장값 대신 빈 값으로 시험한다. + 둘 중 하나라도 있으면 저장하지 않은 시험이라 연결 상태·토큰을 저장하지 않는다(광고 API 시험과 같은 계약, 검토 F09).""" adapter = get_adapter(code) if adapter is None: return {"ok": False, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."} - unsaved = bool(values) + unsaved = bool(values) or bool(cleared) ctx = None try: - ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user) + ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user, cleared=cleared) message = adapter.test_connection(ctx) status, ok = "ok", True except Exception as exc: # noqa: BLE001 — 어떤 오류든 상태로 바꿔 화면에 보여 준다 @@ -119,7 +121,8 @@ class SyncService: ctx.progress = progress fetched, events = adapter.collect(ctx, start, end) if progress is not None: - progress.saving() + # 중지 확인과 저장 시작을 한 잠금에서 — collect() 끝 무렵에 받아들인 [중지]면 여기서 Cancelled(저장 안 함) + progress.begin_saving() known = ctx.credentials.known_secrets() rows = [event_row(ev, known) for ev in events] # 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게). diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 92a77c6..ea438e4 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -596,6 +596,8 @@ def test_toss_reconcile_hides_personal(): ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T", access_token_expires_at=str(int(_t.time()) + 99999))) + from app.modules.performance.adapters import toss as _toss # 지금 인증정보로 받은 토큰(검토 F04 — 지문이 같아야 재사용) + ctx.credentials.set("access_token_for", _toss.credential_fingerprint(ctx.credentials, _toss.TOKEN_KEYS)) 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)] @@ -1558,6 +1560,8 @@ def test_naver_reconcile_hides_personal(): import time as _t ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T", access_token_expires_at=str(int(_t.time()) + 9999))) + # 저장된 토큰은 발급한 인증정보 지문과 같을 때만 다시 쓴다(검토 F04) — 지금 인증정보로 받은 토큰으로 + ctx.credentials.set("access_token_for", nv.credential_fingerprint(ctx.credentials, nv.TOKEN_KEYS)) rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")] orig = (httpx.get, nv.CALL_INTERVAL_SEC) httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response( diff --git a/app/modules/performance/tests/test_review_2026_10_15.py b/app/modules/performance/tests/test_review_2026_10_15.py new file mode 100644 index 0000000..8aafcd5 --- /dev/null +++ b/app/modules/performance/tests/test_review_2026_10_15.py @@ -0,0 +1,310 @@ +"""2026-10-15 코드 검토(docs/CODE_REVIEW_2026-10-15.md) 실적 항목 회귀 테스트 — DB·네트워크 없이(가짜 저장소·가짜 HTTP). + +F01 쿠팡 잘못된 응답(HTTP 200 + JSON 아님·data 없음)은 수집 실패 — 기존 매출 유지(replace_events 안 부름) +F04 인증정보가 바뀌면 이전 계정 토큰을 쓰지 않음(저장 때 내부 토큰 삭제 + 토큰-인증정보 지문), 같은 값 재저장은 유지 +F05 쪽 수 상한·커서 반복이면 부분 수집을 성공으로 내지 않음(쿠팡은 기간을 나눠 다시), 다른 어댑터도 실패로 +F06 collect() 끝 무렵 받아들인 [중지]는 저장 전에 반영, 저장을 시작했으면 [중지] 불가 +F09 쇼핑몰 연결 테스트도 clear(비운 칸)를 빈 값으로 시험하고, 저장하지 않은 시험은 연결 상태를 바꾸지 않음 +""" + +from __future__ import annotations + +import time +from datetime import date + +import httpx +import pytest + +from app.modules.performance.adapters import coupang as cp +from app.modules.performance.adapters import gsshop as gs +from app.modules.performance.adapters import kakao as kk +from app.modules.performance.adapters import naver as nv +from app.modules.performance.adapters import toss as ts +from app.modules.performance.adapters.base import AdapterContext, ApiError +from app.modules.performance.adapters.registry import get_adapter +from app.modules.performance.credentials import CredentialService +from app.modules.performance.sync import SyncService +from app.modules.performance.tests.test_performance import FakeStore, _naver_item, ring + + +class Creds(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 known_secrets(self): + return [] + + +def _cp_ctx(): + return AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK")) + + +@pytest.fixture +def no_wait(monkeypatch): + monkeypatch.setattr(cp, "CALL_INTERVAL_SEC", 0) + monkeypatch.setattr(cp, "RG_CALL_INTERVAL_SEC", 0) + monkeypatch.setattr(cp.time, "sleep", lambda *_a, **_k: None) + + +def _coupang_store_with_sales(): + """기존 쿠팡 매출 한 줄(10/12)이 있는 가짜 저장소 + 쿠팡 인증정보. replace_events 호출을 기록한다.""" + st = FakeStore() + st.events[("coupang", "SALE", "coupang:9")] = {"sales_date": date(2026, 10, 12), "amount": 15000, + "event_type": "SALE", "is_sample": False} + st.replaced = [] + orig = st.replace_events + + def replace(code, start, end, events, *, id_prefix=""): + st.replaced.append((code, start, end, list(events))) + return orig(code, start, end, events, id_prefix=id_prefix) + + st.replace_events = replace + creds = CredentialService(st, lambda: ring()) + creds.save(get_adapter("coupang"), {"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-1"}) + return st, creds + + +# ── F01 ───────────────────────────────────────────────────── +@pytest.mark.parametrize("response", [ + httpx.Response(200, text="maintenance"), # JSON 아님 + httpx.Response(200, json={"message": "점검 중입니다"}), # 주문 목록(data) 없음 + httpx.Response(200, json={"code": 200, "data": {"unexpected": True}}), # data 가 목록 아님 +]) +def test_f01_bad_200_response_fails_and_keeps_existing_sales(monkeypatch, no_wait, response): + st, creds = _coupang_store_with_sales() + monkeypatch.setattr(httpx, "get", lambda *a, **k: response) + r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12)) + assert not r["ok"] and r["status"] == "api_error", r + assert st.replaced == [] # 기간 교체(삭제)를 아예 하지 않음 + assert ("coupang", "SALE", "coupang:9") in st.events # 기존 매출 그대로 + assert st.status["coupang"]["ok"] is False and "저장하지 않았습니다" in r["message"] + + +def test_f01_empty_list_is_still_a_normal_empty_period(monkeypatch, no_wait): + """정상 빈 목록(data: [])은 주문 0건 — 기간 교체가 정상적으로 일어난다(실패와 구분).""" + st, creds = _coupang_store_with_sales() + monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [], "nextToken": ""})) + r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12)) + assert r["ok"], r + assert len(st.replaced) == 1 and st.replaced[0][3] == [] + + +def test_f01_page_rows_contract(): + assert cp.CoupangAdapter._page_rows({"code": 200, "data": []}, "발주서") == [] + assert cp.CoupangAdapter._page_rows({"code": 200, "message": "OK", "data": None}, "발주서") == [] # 성공 표시 + null + assert cp.CoupangAdapter._page_rows({"data": [{"a": 1}, "x"]}, "발주서") == [{"a": 1}] + for body in ({}, {"data": None}, {"message": "maintenance"}, {"data": "x"}): + with pytest.raises(ApiError): + cp.CoupangAdapter._page_rows(body, "발주서") + + +# ── F05 ───────────────────────────────────────────────────── +def test_f05_coupang_page_limit_and_repeated_cursor_raise(monkeypatch, no_wait): + ad = cp.CoupangAdapter() + monkeypatch.setattr(cp, "MAX_PAGES", 2) + n = {"i": 0} + + def endless(*a, **k): + n["i"] += 1 + return httpx.Response(200, json={"code": 200, "data": [{"orderId": n["i"]}], "nextToken": f"t{n['i']}"}) + + monkeypatch.setattr(httpx, "get", endless) + with pytest.raises(cp.TooManyPages): + ad._pages(_cp_ctx(), "/x", {}) + monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [{"a": 1}], "nextToken": "same"})) + with pytest.raises(cp.TooManyPages, match="반복"): + ad._pages(_cp_ctx(), "/x", {}) + + +def test_f05_coupang_splits_period_until_complete_or_fails(monkeypatch, no_wait): + """2일 조회가 쪽 수 상한을 넘으면 하루씩 나눠 끝까지 받는다. 하루도 넘치면 명확한 실패.""" + ad = cp.CoupangAdapter() + monkeypatch.setattr(cp, "MAX_PAGES", 3) + calls = [] + + def get(url, headers=None, timeout=None): + q = dict(p.split("=", 1) for p in url.split("?", 1)[1].split("&")) + calls.append((q["paidDateFrom"], q["paidDateTo"])) + if q["paidDateFrom"] != q["paidDateTo"]: # 여러 날 — 끝이 안 보임 + i = int(q.get("nextToken", "0")) + 1 + return httpx.Response(200, json={"data": [{"orderId": i}], "nextToken": str(i)}) + return httpx.Response(200, json={"data": [{"orderId": q["paidDateFrom"]}], "nextToken": ""}) + + monkeypatch.setattr(httpx, "get", get) + rows = ad._rg_orders(_cp_ctx(), date(2026, 10, 11), date(2026, 10, 12)) + assert sorted(r["orderId"] for r in rows) == ["20261011", "20261012"] # 부분 목록이 아니라 하루씩 전부 + assert ("20261011", "20261011") in calls and ("20261012", "20261012") in calls + + monkeypatch.setattr(httpx, "get", lambda url, headers=None, timeout=None: httpx.Response( + 200, json={"data": [{"orderId": 1}], "nextToken": str(time.perf_counter_ns())})) + with pytest.raises(ApiError, match="하루"): + ad._rg_orders(_cp_ctx(), date(2026, 10, 12), date(2026, 10, 12)) + + +def test_f05_other_adapters_fail_instead_of_partial(monkeypatch): + """네이버·카카오·토스·GS샵 — 상한 소진·커서 반복은 실패(일부만 받은 목록을 돌려주지 않음).""" + ctx = AdapterContext(code="x", credentials=Creds()) + d = date(2026, 10, 12) + + monkeypatch.setattr(nv, "MAX_PAGES", 2) + a = nv.NaverAdapter() + a._get = lambda ctx, path, params: {"data": {"contents": [_naver_item(f"O{params['page']}", f"P{params['page']}", + "2026-10-12", 1000)], + "pagination": {"page": params["page"], "hasNext": True}}} + with pytest.raises(ApiError, match="끝까지"): + a._day_items(ctx, d) + + k = kk.KakaoAdapter() + k._get = lambda ctx, path, params: {"contents": [{"orderId": "1"}], "token": "same"} + with pytest.raises(ApiError, match="반복"): + k._day_rows(ctx, d) + + t = ts.TossAdapter() + t._get = lambda ctx, path, params: {"results": [{"id": 1}], "nextCursor": "c"} + with pytest.raises(ApiError, match="반복"): + t._window_items(ctx, d, d) + t._get = lambda ctx, path, params: {"items": [{"id": 1}], "nextToken": "n"} + with pytest.raises(ApiError, match="반복"): + t._settlement_items(ctx, d, d) + with pytest.raises(ApiError, match="반복"): + t._claims(ctx) + + monkeypatch.setattr(gs, "MAX_PAGES", 2) + g = gs.GsshopAdapter() + g._get = lambda ctx, path, params: {"data": [{"ordNo": params["pageIdx"]}], "hasMorePage": True} + with pytest.raises(ApiError, match="끝까지"): + g._pages(ctx, gs.SALES_PATH, d, d) + + +# ── F06 ───────────────────────────────────────────────────── +def test_f06_stop_accepted_at_end_of_collect_is_not_saved(monkeypatch, no_wait): + from app.modules.performance import jobs + + st, creds = _coupang_store_with_sales() + job = jobs.SyncJob(user="t", start=None, end=None) + shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"] + ad = get_adapter("coupang") + + def collect(ctx, start, end): # 마지막 API 호출·정리 중에 [중지]가 들어온 상황 + assert job.stop_shop("coupang") is True + return 1, [] + + monkeypatch.setattr(ad, "collect", collect) + r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12), progress=shop) + assert r.get("cancelled") and r["status"] == "cancelled", r + assert st.replaced == [] and ("coupang", "SALE", "coupang:9") in st.events # 저장 안 함 + assert shop.state == "cancelled" and shop.message == "중지됨" + + +def test_f06_stop_after_saving_started_is_refused(): + from app.modules.performance import jobs + + job = jobs.SyncJob(user="t", start=None, end=None) + shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"] + shop.start() + shop.begin_saving() + assert shop.state == "saving" + assert job.stop_shop("coupang") is False and shop.stop_requested is False # 저장 중이면 중지 불가를 알림 + + +# ── F04 ───────────────────────────────────────────────────── +def _toss_svc(): + st = FakeStore() + svc = CredentialService(st, lambda: ring()) + ad = get_adapter("toss") + svc.save(ad, {"api_key": "k1", "api_secret": "s1"}) + acc = svc.accessor("toss") + acc.set("access_token", "OLD_ACCOUNT_TOKEN") + acc.set("access_token_expires_at", str(int(time.time()) + 86400)) + acc.set("access_token_for", ts.credential_fingerprint(acc, ts.TOKEN_KEYS)) + return st, svc, ad + + +def test_f04_same_values_keep_token_changed_values_drop_it(monkeypatch): + st, svc, ad = _toss_svc() + issued = [] + monkeypatch.setattr(httpx, "post", lambda *a, **k: issued.append(1) or httpx.Response( + 200, json={"access_token": "NEW_ACCOUNT_TOKEN", "expires_in": 3600})) + + svc.save(ad, {"api_key": "k1", "api_secret": "s1"}) # 같은 값 다시 저장 + assert ("toss", "access_token") in st.creds + ctx = AdapterContext(code="toss", credentials=svc.accessor("toss")) + assert ad._token(ctx) == "OLD_ACCOUNT_TOKEN" and issued == [] # 불필요한 재발급 없음 + + svc.save(ad, {"api_key": "k2"}) # 계정(키) 변경 + assert ("toss", "access_token") not in st.creds and ("toss", "access_token_expires_at") not in st.creds + ctx = AdapterContext(code="toss", credentials=svc.accessor("toss")) + assert ad._token(ctx) == "NEW_ACCOUNT_TOKEN" and issued == [1] + + +def test_f04_token_bound_to_credentials_even_without_save(monkeypatch): + """연결 테스트(저장 안 한 새 입력값)·예전 토큰(지문 없음)도 이전 계정 토큰을 쓰지 않는다 — 실제 수집과 같은 기준.""" + st, svc, ad = _toss_svc() + monkeypatch.setattr(httpx, "post", lambda *a, **k: httpx.Response(200, json={"access_token": "NEW", "expires_in": 3600})) + trial = AdapterContext(code="toss", credentials=svc.accessor("toss", overrides={"api_key": "k2"}, persist=False)) + assert ad._token(trial) == "NEW" + assert svc.accessor("toss").get("access_token") == "OLD_ACCOUNT_TOKEN" # 시험은 저장된 토큰을 건드리지 않음 + # 지문이 없는 예전 토큰(배포 전에 저장된 것)은 한 번 새로 받는다 + svc.accessor("toss").set("access_token_for", "") + real = AdapterContext(code="toss", credentials=svc.accessor("toss")) + assert ad._token(real) == "NEW" and svc.accessor("toss").get("access_token") == "NEW" + + +def test_f04_fingerprint_hides_values_and_gs_mode_cache_follows_key(): + fp = ts.credential_fingerprint(Creds(api_key="secret-key-1", api_secret="s"), ts.TOKEN_KEYS) + assert len(fp) == 64 and "secret" not in fp + a = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K1" * 16)) + b = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K2" * 16)) + assert gs.GsshopAdapter._mode_key(a) != gs.GsshopAdapter._mode_key(b) + + +# ── F09 ───────────────────────────────────────────────────── +def test_f09_shop_test_uses_empty_value_for_cleared_and_keeps_status(monkeypatch): + st = FakeStore() + svc = CredentialService(st, lambda: ring()) + ad = get_adapter("naver") + svc.save(ad, {"client_id": "cid", "client_secret": "$2a$04$abcdefghijklmnopqrstuu", "account_id": "OLD-SELLER"}) + st.status["naver"] = {"status": "ok", "ok": True, "error": ""} + seen = [] + monkeypatch.setattr(ad, "test_connection", lambda ctx: seen.append(ctx.credentials.get("account_id")) or "연결됨") + r = SyncService(st, svc).test_connection("naver", cleared={"account_id"}) + assert seen == [""] and r["ok"] and r["unsaved"] is True # 비운 칸은 빈 값, 저장 안 한 시험 + assert st.status["naver"] == {"status": "ok", "ok": True, "error": ""} # 연결 상태 그대로 + assert svc.accessor("naver").get("account_id") == "OLD-SELLER" # 저장값도 그대로 + r = SyncService(st, svc).test_connection("naver") # 저장값 그대로 시험은 상태 기록 + assert seen[-1] == "OLD-SELLER" and r["unsaved"] is False and st.status["naver"].get("test") + + +def test_f09_router_passes_clear_like_ad_test(monkeypatch): + import importlib + + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.modules.performance import common + + perf_router = importlib.import_module("app.modules.performance.router") + calls = [] + + class Sync: + def test_connection(self, code, *, values=None, user="", cleared=None): + calls.append((code, values, cleared)) + return {"ok": True, "status": "ok", "label": "정상 연결", "message": "연결됨", "unsaved": bool(values or cleared)} + + st = FakeStore() + st.list_marketplaces = lambda: [{"code": "naver", "name": "네이버"}] + monkeypatch.setattr(common, "require_store", lambda request, admin=False: (st, {"email": "king@x"})) + monkeypatch.setattr(common, "services", lambda request, store: (None, Sync())) + app = FastAPI() + app.include_router(perf_router.router) + c = TestClient(app) + r = c.post("/performance/api/marketplaces/naver/test", + json={"values": {"client_id": "new"}, "clear": ["account_id", "client_id", "nope"]}) + assert r.status_code == 200 and r.json()["unsaved"] is True + assert calls[-1] == ("naver", {"client_id": "new"}, {"account_id"}) # 새 값이 있는 칸·모르는 칸은 빼고 diff --git a/app/modules/project/db.py b/app/modules/project/db.py index 407fc86..777a777 100644 --- a/app/modules/project/db.py +++ b/app/modules/project/db.py @@ -680,6 +680,28 @@ class ProjectStore: assignee_allowed: Any = None, ) -> dict[str, Any]: """assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김).""" + with self._pool.connection() as conn: + with conn.transaction(): + row, done_at = self._insert_task( + conn, project_id=project_id, title=title, stage_id=stage_id, description=description, + assignee_email=assignee_email, assignee_name=assignee_name, priority=priority, + start_date=start_date, due_date=due_date, start_time=start_time, due_time=due_time, + created_by=created_by, parent_task_id=parent_task_id, assignee_allowed=assignee_allowed, + ) + out = self.get_task(task_id=row["id"]) + out["_newly_completed"] = done_at is not None + return out + + def _insert_task( + self, conn: Any, *, project_id: int, title: str, stage_id: int | None = None, description: str = "", + assignee_email: str = "", assignee_name: str = "", priority: str = "normal", + start_date: str | None = None, due_date: str | None = None, start_time: str | None = None, + due_time: str | None = None, created_by: str = "", parent_task_id: int | None = None, + assignee_allowed: Any = None, + ) -> tuple[dict[str, Any], Any]: + """업무 한 건 INSERT(+배정·완료 이력) — **부르는 쪽의 연결·트랜잭션 안에서**(커밋하지 않음). (행, 완료 시각|None). + create_task 와 회의록 [적용](apply_meeting_task — 줄 잠금과 같은 트랜잭션)이 같이 쓴다. 다른 풀 연결을 빌리지 + 않는다(assignee_allowed 는 사용자 목록만 보는 함수).""" ttl = store.validate_task_title(title) pr = store.validate_priority(priority) sd = store.validate_date(start_date) @@ -689,74 +711,70 @@ class ProjectStore: store.validate_date_range(sd, dd, sti, dti) assignee = store.norm_str(assignee_email, lower=True) done_at = None - with self._pool.connection() as conn: - with conn.transaction(): - if parent_task_id is not None: - # 세부 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이 - # 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다. - parent = conn.execute( - "SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,) - ).fetchone() - if not parent: - raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}") - # 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트 - # 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는 - # 프로젝트에 세부 업무를 만들 수 있었다). - if int(parent["project_id"]) != int(project_id): - raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.") - stage_id = None - elif stage_id not in (None, ""): - stage_id = self._check_stage_in_project(conn, stage_id, project_id) - else: - # stage 미지정 시 프로젝트의 첫 세션으로 - st = conn.execute( - "SELECT id FROM project_stages WHERE project_id = %s " - "ORDER BY sort_order ASC, id ASC LIMIT 1", - (project_id,), - ).fetchone() - stage_id = st["id"] if st else None - # 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는 - # 세션이 없어 해당 없음). - if not assignee and stage_id is not None: - assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id, - allowed=assignee_allowed) - # 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력). - if stage_id is not None: - done_row = conn.execute( - "SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,) - ).fetchone() - if done_row and done_row["is_done_stage"]: - done_at = now_kst() - nxt = conn.execute( - "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks " - "WHERE project_id = %s", - (project_id,), - ).fetchone() - row = conn.execute( - """ - INSERT INTO tasks - (project_id, stage_id, parent_task_id, title, description, - assignee_email, assignee_name, priority, start_date, due_date, - start_time, due_time, sort_order, created_by, completed_at) - VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) - RETURNING * - """, - ( - project_id, stage_id, parent_task_id, ttl, store.norm_str(description), - assignee, store.norm_str(assignee_name), pr, sd, dd, - sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at, - ), - ).fetchone() - if assignee: - self._log(conn, project_id=project_id, task_id=row["id"], - actor=created_by, action=store.ACTION_ASSIGNED, - detail=f"{ttl} → {assignee}") - if done_at is not None: - self._log(conn, project_id=project_id, task_id=row["id"], - actor=created_by, action=store.ACTION_COMPLETED, detail=ttl) - out = self.get_task(task_id=row["id"]) - out["_newly_completed"] = done_at is not None - return out + if parent_task_id is not None: + # 세부 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이 + # 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다. + parent = conn.execute( + "SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,) + ).fetchone() + if not parent: + raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}") + # 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트 + # 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는 + # 프로젝트에 세부 업무를 만들 수 있었다). + if int(parent["project_id"]) != int(project_id): + raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.") + stage_id = None + elif stage_id not in (None, ""): + stage_id = self._check_stage_in_project(conn, stage_id, project_id) + else: + # stage 미지정 시 프로젝트의 첫 세션으로 + st = conn.execute( + "SELECT id FROM project_stages WHERE project_id = %s " + "ORDER BY sort_order ASC, id ASC LIMIT 1", + (project_id,), + ).fetchone() + stage_id = st["id"] if st else None + # 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는 + # 세션이 없어 해당 없음). + if not assignee and stage_id is not None: + assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id, + allowed=assignee_allowed) + # 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력). + if stage_id is not None: + done_row = conn.execute( + "SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,) + ).fetchone() + if done_row and done_row["is_done_stage"]: + done_at = now_kst() + nxt = conn.execute( + "SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks " + "WHERE project_id = %s", + (project_id,), + ).fetchone() + row = conn.execute( + """ + INSERT INTO tasks + (project_id, stage_id, parent_task_id, title, description, + assignee_email, assignee_name, priority, start_date, due_date, + start_time, due_time, sort_order, created_by, completed_at) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) + RETURNING * + """, + ( + project_id, stage_id, parent_task_id, ttl, store.norm_str(description), + assignee, store.norm_str(assignee_name), pr, sd, dd, + sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at, + ), + ).fetchone() + if assignee: + self._log(conn, project_id=project_id, task_id=row["id"], + actor=created_by, action=store.ACTION_ASSIGNED, + detail=f"{ttl} → {assignee}") + if done_at is not None: + self._log(conn, project_id=project_id, task_id=row["id"], + actor=created_by, action=store.ACTION_COMPLETED, detail=ttl) + return row, done_at def move_subtask( self, *, task_id: int, parent_task_id: int, actor: str = "" @@ -3735,11 +3753,20 @@ class ProjectStore: return self._mt_row(row) return self._mt_call(run) - def apply_meeting_task(self, *, item_id: int, create: Any) -> tuple[dict[str, Any], bool]: - """[적용] — 줄을 잠그고 아직 작업이 없을 때만 create(줄, 상위 작업 id) 로 작업을 만들어 task_id 를 남긴다. - 작업 칸(parent_task_id)을 골랐으면 그 작업의 세부 작업으로(섹션 없이). (줄, 이번에 만들었는가). - 두 사람이 동시에 눌러도 작업은 하나. create 가 실패하면 줄은 그대로.""" - def run() -> tuple[int, bool]: + # [적용] 때 라우터가 권한·담당자를 확인한 줄 값 — 잠근 뒤 이 값이 그대로여야 만든다(그사이 고쳐졌으면 409) + MT_APPLY_KEYS = ("title", "project_id", "stage_id", "assignee_email", "parent_task_id") + + def apply_meeting_task(self, *, item_id: int, task_fields: dict[str, Any] | None, + expect: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool, dict[str, Any] | None]: + """[적용] — 줄을 잠그고 아직 업무가 없을 때만 업무를 만들어 task_id 를 남긴다. **업무 INSERT 와 줄 연결이 같은 연결· + 같은 트랜잭션**이라(2026-10-15 검토 F02) 연결 기록이 실패하면 업무도 롤백되고, 재시도·동시 클릭에도 업무는 하나다. + 트랜잭션 안에서는 이 연결 하나만 쓴다(같은 풀의 다른 연결을 기다리지 않음). + + task_fields = _insert_task 인자(라우터가 잠그기 전에 권한·담당자를 확인해 만든 값, project_id·parent_task_id 포함). + expect = 그 확인에 쓴 줄(get_meeting_task) — 잠근 줄의 MT_APPLY_KEYS 가 다르면 GoalCellConflict(다시 [적용]). + 작업 칸(parent_task_id)이면 그 업무의 세부 업무(섹션 없음) — 상위 업무가 같은 프로젝트에 아직 있는지 잠근 뒤 다시 본다. + 돌려주는 값: (줄, 이번에 만들었는가, 만든 업무|None). 알림·메일은 라우터가 커밋 뒤에.""" + def run() -> tuple[int, bool, tuple[int, Any] | None]: with self._mt_conn() as conn: with conn.transaction(): row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE", @@ -3748,20 +3775,26 @@ class ProjectStore: raise KeyError(item_id) self._check_meeting_open(conn, row["week_start"]) if row["task_id"] is not None: - return item_id, False + return item_id, False, None use = self._mt_row(row) + if task_fields is None or (expect is not None and any( + use.get(k) != expect.get(k) for k in self.MT_APPLY_KEYS)): + raise store.GoalCellConflict("그사이 줄이 바뀌었습니다. 새로고침한 뒤 다시 [적용]해 주세요.") parent_task = use.get("parent_task_id") if parent_task is not None: t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (parent_task,)).fetchone() if t is None or use["project_id"] is None or int(t["project_id"]) != int(use["project_id"]): raise ValueError("고른 업무가 없어졌거나 다른 프로젝트로 옮겨졌습니다. 업무 칸을 다시 고르세요.") - use = {**use, "stage_id": None} - task = create(use, parent_task) + task_row, done_at = self._insert_task(conn, **task_fields) conn.execute("UPDATE goal_meeting_tasks SET task_id = %s, updated_at = now() WHERE id = %s", - (int(task["id"]), item_id)) - return item_id, True - iid, made = self._mt_call(run) - return self.get_meeting_task(item_id=iid), made # type: ignore[return-value] + (int(task_row["id"]), item_id)) + return item_id, True, (int(task_row["id"]), done_at) + iid, made, info = self._mt_call(run) + task = None + if info is not None: + task = self.get_task(task_id=info[0]) + task["_newly_completed"] = info[1] is not None + return self.get_meeting_task(item_id=iid), made, task # type: ignore[return-value] def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]: """회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값.""" diff --git a/app/modules/project/router.py b/app/modules/project/router.py index 2000c79..0c6ebbd 100644 --- a/app/modules/project/router.py +++ b/app/modules/project/router.py @@ -1502,35 +1502,54 @@ def _create_task_for( request: Request, st: Any, user: dict[str, Any], project_id: int, payload: dict[str, Any], bg: BackgroundTasks, ) -> tuple[dict[str, Any], list[str]]: - """작업 만들기 공통(작업 창·회의록 작업 등록 [적용]) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그. - 돌려주는 값: (작업, 태그하지 못한 이메일).""" + """작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그. + 돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서.""" + project, followers = _task_create_checks(request, st, user, project_id, payload) + try: + task = st.create_task(**_task_create_fields(user, project_id, payload)) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) + except KeyError as exc: + raise HTTPException(status_code=404, detail=str(exc)) + return task, _task_created_effects(request, st, user, project, task, followers, bg) + + +def _task_create_checks(request: Request, st: Any, user: dict[str, Any], project_id: int, + payload: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: + """만들기 전 확인 — 권한(멤버)·프로젝트·담당자·협업자. (프로젝트, 협업자). DB 쓰기·잠금 없음.""" _require_manage(request, st, user, project_id) project = st.get_project(project_id=project_id) if project is None: raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.") _check_assignee(st, payload.get("assignee_email"), project_id) followers = _check_followers(st, payload.get("followers"), project_id) - try: - task = st.create_task( - project_id=project_id, - title=payload.get("title", ""), - stage_id=payload.get("stage_id"), - description=store.sanitize_description_html(payload.get("description", "")), - assignee_email=payload.get("assignee_email", ""), - assignee_name=payload.get("assignee_name", ""), - priority=payload.get("priority", "normal"), - start_date=payload.get("start_date"), - due_date=payload.get("due_date"), - start_time=payload.get("start_time"), - due_time=payload.get("due_time"), - created_by=user["email"], - parent_task_id=payload.get("parent_task_id"), - assignee_allowed=_registered_project_user, - ) - except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) - except KeyError as exc: - raise HTTPException(status_code=404, detail=str(exc)) + return project, followers + + +def _task_create_fields(user: dict[str, Any], project_id: int, payload: dict[str, Any]) -> dict[str, Any]: + """db.create_task / db._insert_task 인자.""" + return { + "project_id": project_id, + "title": payload.get("title", ""), + "stage_id": payload.get("stage_id"), + "description": store.sanitize_description_html(payload.get("description", "")), + "assignee_email": payload.get("assignee_email", ""), + "assignee_name": payload.get("assignee_name", ""), + "priority": payload.get("priority", "normal"), + "start_date": payload.get("start_date"), + "due_date": payload.get("due_date"), + "start_time": payload.get("start_time"), + "due_time": payload.get("due_time"), + "created_by": user["email"], + "parent_task_id": payload.get("parent_task_id"), + "assignee_allowed": _registered_project_user, + } + + +def _task_created_effects(request: Request, st: Any, user: dict[str, Any], project: dict[str, Any], + task: dict[str, Any], followers: list[str], bg: BackgroundTasks) -> list[str]: + """업무를 만든(커밋된) 뒤의 부가 처리 — 자동 협업자·배정/완료 알림·관리자 메일(백그라운드)·@태그. 태그 못 한 이메일.""" + project_id = int(task["project_id"]) # 만든 사람은 자동 협업자 + 만들 때 고른 협업자(세부 업무 추가 칸 등). 담당자는 협업자가 아니다(2026-10-13, # db.add_followers 가 담당자를 거른다 — 만든 사람이 담당자여도 빠진다). # 세부 업무는 만든 사람을 자동으로 넣지 않는다 — 고른 협업자만(2026-10-14 사용자 요청). @@ -1562,12 +1581,11 @@ def _create_task_for( # 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림. if task.pop("_newly_completed", False): _notify_completed(bg, request, st, project=project, task=task, actor=user["email"]) - skipped = _record_mentions( + return _record_mentions( st, task=task, emails=store.extract_mentions_from_html(task.get("description") or ""), actor=user["email"], project_name=project["name"], ) - return task, skipped _ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다." @@ -4013,24 +4031,35 @@ def api_delete_quick_task(request: Request, item_id: int) -> JSONResponse: @router.post("/api/goals/meeting-quick-tasks/{item_id}/apply") def api_apply_quick_task(request: Request, item_id: int, bg: BackgroundTasks) -> JSONResponse: - """[적용] — 그 줄로 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림). 줄을 잠그고 한 번만 — 이미 만들었으면 그 결과.""" + """[적용] — 그 줄로 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림). 줄을 잠그고 한 번만 — 이미 만들었으면 그 결과. + + 순서(2026-10-15 검토 F02): ① 잠그기 전에 줄을 읽어 권한·담당자·협업자를 확인(DB 잠금 없이) ② DB 한 트랜잭션에서 + 줄 잠금 → 이미 만들었으면 그대로 / 줄이 그사이 바뀌었으면 409 → 업무 INSERT → 줄에 task_id(같은 연결 — 실패하면 둘 다 + 롤백, 재시도·동시 클릭에도 업무 하나) ③ 커밋된 뒤에만 협업자·알림·메일.""" user = _require_user(request) st = _db_or_503(request) - - def create(row: dict[str, Any], parent_task_id: int | None) -> dict[str, Any]: - if not row["title"].strip(): - raise ValueError("업무 제목을 쓰세요.") - if row["project_id"] is None: - raise ValueError("프로젝트를 고르세요.") - rec = access.default_user_lookup(row["assignee_email"]) if row["assignee_email"] else None - # 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — _create_task_for 가 프로젝트 멤버를, create_task 가 같은 프로젝트를 확인 - payload = {"title": row["title"].strip(), "stage_id": None if parent_task_id else row["stage_id"], - "assignee_email": row["assignee_email"], - "assignee_name": (rec or {}).get("name") or (row["assignee_email"].split("@")[0] if row["assignee_email"] else ""), + snap = _goal_call(st.get_meeting_task, item_id=item_id) + if snap is None: + raise HTTPException(status_code=404, detail="업무 등록 줄을 찾을 수 없습니다.") + project = followers = fields = None + if snap["task_id"] is None: + if not (snap["title"] or "").strip(): + raise HTTPException(status_code=400, detail="업무 제목을 쓰세요.") + if snap["project_id"] is None: + raise HTTPException(status_code=400, detail="프로젝트를 고르세요.") + parent_task_id = snap.get("parent_task_id") + rec = access.default_user_lookup(snap["assignee_email"]) if snap["assignee_email"] else None + # 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — 확인은 작업 창과 같이 프로젝트 멤버, 같은 프로젝트는 DB 가 잠근 뒤 + payload = {"title": snap["title"].strip(), "stage_id": None if parent_task_id else snap["stage_id"], + "assignee_email": snap["assignee_email"], + "assignee_name": (rec or {}).get("name") or (snap["assignee_email"].split("@")[0] if snap["assignee_email"] else ""), "parent_task_id": parent_task_id} - return _create_task_for(request, st, user, int(row["project_id"]), payload, bg)[0] - - row, made = _goal_call(st.apply_meeting_task, item_id=item_id, create=create) + pid = int(snap["project_id"]) + project, followers = _task_create_checks(request, st, user, pid, payload) + fields = _task_create_fields(user, pid, payload) + row, made, task = _goal_call(st.apply_meeting_task, item_id=item_id, task_fields=fields, expect=snap) + if made and task is not None: + _task_created_effects(request, st, user, project, task, followers or [], bg) # 커밋 뒤에만 return JSONResponse({"task": _quick_view(st, user, [row])[0], "created": made}, status_code=201 if made else 200) diff --git a/app/modules/project/templates/project/goal_meeting.html b/app/modules/project/templates/project/goal_meeting.html index 53af271..a9c2125 100644 --- a/app/modules/project/templates/project/goal_meeting.html +++ b/app/modules/project/templates/project/goal_meeting.html @@ -1,7 +1,7 @@ {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -298,5 +298,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/goals.html b/app/modules/project/templates/project/goals.html index d88e6ce..f4b94d1 100644 --- a/app/modules/project/templates/project/goals.html +++ b/app/modules/project/templates/project/goals.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -207,5 +207,5 @@ {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/help.html b/app/modules/project/templates/project/help.html index e71c4d5..caf6bf6 100644 --- a/app/modules/project/templates/project/help.html +++ b/app/modules/project/templates/project/help.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} diff --git a/app/modules/project/templates/project/inbox.html b/app/modules/project/templates/project/inbox.html index dd12d96..1e0175d 100644 --- a/app/modules/project/templates/project/inbox.html +++ b/app/modules/project/templates/project/inbox.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -106,5 +106,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/modules/project/templates/project/mytasks.html b/app/modules/project/templates/project/mytasks.html index ea92b38..3ce2441 100644 --- a/app/modules/project/templates/project/mytasks.html +++ b/app/modules/project/templates/project/mytasks.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -100,5 +100,5 @@ "today": {{ today | tojson }} } - + {% endblock %} diff --git a/app/modules/project/templates/project/notifier.html b/app/modules/project/templates/project/notifier.html index 5195c67..f61e878 100644 --- a/app/modules/project/templates/project/notifier.html +++ b/app/modules/project/templates/project/notifier.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -108,5 +108,5 @@ }); })(); - + {% endblock %} diff --git a/app/modules/project/templates/project/project.html b/app/modules/project/templates/project/project.html index a43dd45..dac8d7b 100644 --- a/app/modules/project/templates/project/project.html +++ b/app/modules/project/templates/project/project.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + @@ -470,5 +470,5 @@ - + {% endblock %} diff --git a/app/modules/project/templates/project/trash.html b/app/modules/project/templates/project/trash.html index 06f1f54..516f1f3 100644 --- a/app/modules/project/templates/project/trash.html +++ b/app/modules/project/templates/project/trash.html @@ -1,7 +1,7 @@ {% extends "erp_base.html" %} {% block head_extra %} - + {% endblock %} @@ -70,5 +70,5 @@ {% include "project/_side_modals.html" %} {% include "project/_member_tasks_modal.html" %} - + {% endblock %} diff --git a/app/static/erp-notice.css b/app/static/erp-notice.css index afa9288..2681302 100644 --- a/app/static/erp-notice.css +++ b/app/static/erp-notice.css @@ -45,6 +45,9 @@ .erp-notice-body img[width] { height: auto; } .erp-notice-error { margin: 0; padding: 6px 10px; border-radius: 6px; background: #fdecec; color: #b42318; font-size: 13px; } .erp-notice-error[hidden] { display: none; } +/* 띄운 공지가 고쳐짐(2026-10-15 검토 F07) — 바뀐 내용을 다시 읽게 */ +.erp-notice-updated { margin: 0; padding: 6px 10px; border-radius: 6px; background: #fff4e5; color: #8a5300; font-size: 13px; } +.erp-notice-updated[hidden] { display: none; } .erp-notice-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 6px; border-top: 1px solid #eceef1; } .erp-notice-meta { font-size: 12.5px; color: #6b7079; } .erp-notice-ok { diff --git a/app/static/erp-notice.js b/app/static/erp-notice.js index 8f0888d..2cd6c8f 100644 --- a/app/static/erp-notice.js +++ b/app/static/erp-notice.js @@ -2,6 +2,8 @@ // · GET /notice/api/pending — 띄울 시각이 지났고 아직 [확인] 안 한 내 공지(오래된 것부터). 30초마다·창을 다시 볼 때. // · [확인]을 누를 때까지 닫히지 않는다(Esc·바깥 클릭으로 안 닫힘). 여러 건이면 차례대로(1/3). // · [확인] = POST /notice/api/{id}/ack — 실패하면 창을 그대로 두고 알린다. 다른 탭에서 확인하면 이 탭도 다음 확인 때 닫힌다. +// · 공지마다 내용 버전(version = 고친 시각) — 띄운 공지가 고쳐지면 다음 확인 때 바뀐 내용으로 다시 그리고 "수정됨"을 알린다. +// [확인]은 읽은 버전을 함께 보내, 그 사이 고쳐졌으면(409) 기록하지 않고 바뀐 내용을 다시 보여 준다(2026-10-15 검토 F07). // · 본문 HTML 은 서버가 정리한 것(이미지는 /notice/images/{id} 만). 수신함 오른쪽 작업 창(iframe) 안에서는 돌지 않는다. // · 024 미적용(503)·로그아웃(401)이면 조용히 멈춘다. (function () { @@ -35,9 +37,11 @@ if (!res.ok) return; const data = await res.json(); queue = Array.isArray(data.notices) ? data.notices : []; - // 다른 탭·다른 곳에서 확인했거나 취소된 공지는 닫는다 - if (shown && !queue.some(function (n) { return n.id === shown.id; })) close(); - if (!shown && queue.length) open(queue[0]); + // 다른 탭·다른 곳에서 확인했거나 취소된 공지는 닫는다. 같은 공지라도 내용이 고쳐졌으면(버전이 다르면) 다시 그린다 + const cur = shown ? queue.find(function (n) { return n.id === shown.id; }) : null; + if (shown && !cur) close(); + if (cur && (cur.version || "") !== (shown.version || "")) open(cur, true); + else if (!shown && queue.length) open(queue[0]); else if (shown) paintCount(); } catch (_) { // 네트워크 오류는 다음 주기에 다시 @@ -54,7 +58,7 @@ c.textContent = queue.length > 1 ? (i + 1) + " / " + queue.length : ""; c.hidden = queue.length <= 1; } - function open(n) { + function open(n, updated) { shown = n; if (!box) { box = document.createElement("div"); @@ -63,6 +67,7 @@ '
' + '
긴급 공지
' + '

' + + '' + '
' + '' + '
' + @@ -80,6 +85,7 @@ box.querySelector(".erp-notice-meta").textContent = [who(n.created_by), when(n.show_at)].filter(Boolean).join(" · "); box.querySelector(".erp-notice-error").hidden = true; + box.querySelector(".erp-notice-updated").hidden = !updated; box.querySelector(".erp-notice-body").scrollTop = 0; box.hidden = false; paintCount(); @@ -97,8 +103,20 @@ ok.disabled = true; err.hidden = true; try { - const res = await fetch("/notice/api/" + n.id + "/ack", { method: "POST", credentials: "same-origin" }); - if (!res.ok && res.status !== 404) throw new Error("HTTP " + res.status); // 404 = 취소·삭제됨 — 닫는다 + const res = await fetch("/notice/api/" + n.id + "/ack", { + method: "POST", credentials: "same-origin", + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ version: n.version || "" }), + }); + if (res.status === 409) { + // 읽는 사이 공지가 고쳐졌다 — 기록하지 않았다. 바뀐 내용을 받아 다시 그린다(창은 그대로) + ok.disabled = false; + await poll(); + if (shown && shown.id === n.id && (shown.version || "") === (n.version || "")) { + box.querySelector(".erp-notice-updated").hidden = false; // 다시 받지 못했어도 알린다 + } + return; + } + if (!res.ok && res.status !== 404) throw new Error("HTTP " + res.status); // 404 = 취소·삭제·예약 — 닫는다 try { localStorage.setItem("erp_notice_ack", String(n.id) + ":" + Date.now()); } catch (_) {} queue = queue.filter(function (x) { return x.id !== n.id; }); if (queue.length) open(queue[0]); else close(); diff --git a/app/static/project.css b/app/static/project.css index fc8733a..078c222 100644 --- a/app/static/project.css +++ b/app/static/project.css @@ -2703,6 +2703,14 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important; .pj-meet-pick-cell:hover { border-color: #cfd4da; background: #fafbfc; } .pj-meet-quick-apply { height: 26px; padding: 0 10px; border: none; border-radius: 6px; background: var(--pj-accent); color: #fff; font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; } .pj-meet-quick-apply:disabled { opacity: .5; cursor: default; } +/* 저장 실패한 줄(2026-10-15 검토 F03) — 초안은 그대로 두고 빨간 테두리 + [다시 저장] 아이콘 */ +.pj-meet-quick-table tr.is-unsaved input[data-field="title"] { border-color: #e8a3a3; background: #fff7f7; } +.pj-meet-quick-retry { + display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-right: 4px; vertical-align: middle; + border: none; border-radius: 6px; background: #fdecec; color: #c22b10; cursor: pointer; +} +.pj-meet-quick-retry .material-symbols-outlined { font-size: 17px; } +.pj-meet-quick-retry:hover { background: #f9d6d6; } .pj-meet-quick-actbox { display: flex; align-items: center; justify-content: flex-end; gap: 2px; flex-wrap: nowrap; } /* 체크·휴지통(또는 적용·×) 가로 한 줄 */ .pj-meet-quick-actbox .pj-meet-quick-del { margin-left: 0; } .pj-meet-quick-done { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; flex: none; border-radius: 6px; color: #1f8a4c; text-decoration: none; } diff --git a/app/static/project.js b/app/static/project.js index 6987450..906516a 100644 --- a/app/static/project.js +++ b/app/static/project.js @@ -11407,13 +11407,15 @@ }; const blank = function () { return { id: null, title: "", assignee: "", projectId: null, projectName: "", stageId: null, stageName: "", - parentTaskId: null, parentTaskTitle: "", taskId: null, registered: false, visible: true, taskExists: true, chain: null }; + parentTaskId: null, parentTaskTitle: "", taskId: null, registered: false, visible: true, taskExists: true, chain: null, + unsaved: new Set(), err: "" }; }; function fromServer(t) { return { id: t.id, title: t.title || "", assignee: t.assignee_email || "", projectId: t.project_id, projectName: t.project_name || "", stageId: t.stage_id, stageName: t.stage_name || "", parentTaskId: t.parent_task_id || null, parentTaskTitle: t.parent_task_title || "", taskId: t.task_id, - registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null }; + registered: !!t.registered, visible: t.visible !== false, taskExists: t.task_exists !== false, chain: null, + unsaved: new Set(), err: "" }; } let rows = []; let ready = false, unavailable = ""; @@ -11456,9 +11458,15 @@ } // ── 저장 — 줄마다 차례대로. 서버에 없는 줄은 처음 채울 때 만든다(지금 칸 전부를 보낸다) ── + // r.unsaved = 아직 저장이 확인되지 않은 칸(PUT 키, 서버에 줄이 없으면 "*") — 성공하면 빼고, 실패하면 남긴다. + // persist() 는 실패하면 거부되는 약속을 돌려준다(호출자가 await 하면 throw — [적용]이 이전 값으로 만들지 않게, 2026-10-15 + // 검토 F03). r.chain 은 늘 끝나는 약속이라 실패 뒤에도 다음 저장이 이어진다. 실패한 초안은 화면에 그대로 둔다. let pendingSaves = 0; + const FIELD_OF = { title: "title", assignee_email: "assignee", project_id: "projectId", stage_id: "stageId", parent_task_id: "parentTaskId" }; function persist(r, patch) { pendingSaves++; + const keys = r.id ? Object.keys(patch || {}) : ["*"]; + keys.forEach(function (k) { r.unsaved.add(k); }); const run = async function () { if (!r.id) { const res = await api("POST", listUrl, { @@ -11466,15 +11474,40 @@ parent_task_id: r.parentTaskId, }); r.id = res.task.id; + r.unsaved.clear(); // 줄 전체를 보냈다 } else { await api("PUT", rowUrl(r.id), patch); + keys.forEach(function (k) { r.unsaved.delete(k); }); + r.unsaved.delete("*"); } + if (!r.unsaved.size) r.err = ""; }; - r.chain = (r.chain || Promise.resolve()).then(run).catch(function (e) { - showToast("업무 등록 표 저장 실패: " + e.message, "error"); - if (e.status === 409 || e.status === 400) setTimeout(function () { load(true); }, 0); // 서버 상태로 되돌림 + const p = (r.chain || Promise.resolve()).then(run); + r.chain = p.then(function () {}, function (e) { + keys.forEach(function (k) { r.unsaved.add(k); }); + r.err = e.message || "저장 실패"; + showToast("업무 등록 표 저장 실패: " + r.err + " — 입력은 그대로 두었습니다. 다시 저장하세요.", "error"); + // 다른 사람이 먼저 [적용]한 줄(409)만 서버 상태로 — 그 밖의 실패는 초안을 지우지 않는다 + if (e.status === 409) setTimeout(function () { r.unsaved.clear(); r.err = ""; load(true); }, 0); + else render(); }).finally(function () { pendingSaves--; }); - return r.chain; + p.catch(function () {}); // 기다리지 않는 호출(칸 고르기 등)도 처리되지 않은 거부로 남지 않게 + return p; + } + // 이 줄에 저장 안 된 입력이 없게 — 치던 제목을 보내고, 앞선 저장을 기다리고, 실패해 남은 칸을 다시 보낸다. + // 끝까지 저장되지 않으면 throw(호출자 [적용]은 멈춘다). + async function saveRow(r) { + flushTitle(r); + await r.chain; + if (!r.id || r.unsaved.size) { + const patch = {}; + r.unsaved.forEach(function (k) { if (FIELD_OF[k]) patch[k] = r[FIELD_OF[k]]; }); + await persist(r, patch); + } + if (!r.id || r.unsaved.size) throw new Error(r.err || "저장되지 않은 칸이 있습니다"); + } + function hasUnsaved() { + return titleTimers.size > 0 || pendingSaves > 0 || rows.some(function (r) { return r.unsaved && r.unsaved.size > 0; }); } function cell(kind, text, placeholder, disabled, title) { return '' : "") + + '' + ''; } @@ -11517,7 +11553,7 @@ const taskCell = r.parentTaskId ? cell("task", "↳ " + (r.parentTaskTitle || "업무"), "", ro, "이 업무의 세부 업무로 등록") : cell("task", "", r.registered ? "—" : "새 업무", ro || !r.projectId, r.projectId ? "고르면 그 업무의 세부 업무로 등록(비우면 섹션에 새 업무)" : "프로젝트를 먼저 고르세요"); - return '" + + return '" + '' + titleCell + "" + "" + (r.assignee ? '