Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c7cc94a09c | |||
| edd5a97a9b | |||
| 5a4ceead3e | |||
| fa6bb33f11 | |||
| 5eaeee2f57 | |||
| 2e428aa07f | |||
| 4eda10df00 | |||
| 42d2671f80 | |||
| 66a99e2733 | |||
| 3ead7aa9f6 | |||
| e7b1e17579 | |||
| cd33c67df9 | |||
| 0bb23c32de | |||
| f0aae513af | |||
| 8ad8242c41 | |||
| 32877b1ce8 | |||
| 1550b5bb51 |
@@ -30,3 +30,8 @@ KING-DESKTOP.XML
|
||||
|
||||
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||
~$*
|
||||
|
||||
# 테스트 도구(docs/TESTING.md)
|
||||
.pytest_cache/
|
||||
tests/js/node_modules/
|
||||
tests/js/package-lock.json
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260918e" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
# ── 이미지 ──────────────────────────────────────────────
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261013i" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""광고 API 연동(구글 광고 등) — 광고 채널 하나 = 파일 하나 + registry.py 한 줄.
|
||||
|
||||
쇼핑몰 어댑터(adapters/)와 같은 모양(입력칸·연결 테스트·인증정보 접근자)을 따르되, 돌려주는 것은 매출 사건이 아니라
|
||||
"날짜별 광고비·ROAS·보고서 항목"(AdDay)이다. 저장은 ad_sync.py 가 perf_ad_spend(source='api')에.
|
||||
"""
|
||||
@@ -0,0 +1,70 @@
|
||||
"""광고 API 연동 — 공통 인터페이스.
|
||||
|
||||
광고 채널 코드(code)는 광고비 표 채널 코드(ad_spend.CHANNELS)와 같다 — 가져온 값은 그 채널 열로 들어간다.
|
||||
인증정보는 쇼핑몰 인증정보와 같은 방식(설정 화면 입력 → 마스터 키로 암호화 → perf_ad_credentials)이고,
|
||||
꺼낼 때는 ctx.credentials.get(key) 로만(서버 안에서만 복호화). 오류는 adapters.base 의 AdapterError 계열 —
|
||||
status 가 곧 연결 상태 코드(설정 화면 표시)다. 오류 문구에 비밀값을 넣지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from ..adapters.base import AdapterContext, CredentialField, NotConfigured
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdDay:
|
||||
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
|
||||
|
||||
day: date
|
||||
amount: int
|
||||
roas: Decimal | None = None
|
||||
metrics: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
class AdSource:
|
||||
code: str = "" # 광고비 채널 코드(google 등)
|
||||
name: str = "" # 설정 화면 이름
|
||||
docs_url: str = ""
|
||||
note: str = "" # 설정 창 맨 위 안내
|
||||
|
||||
# 인증정보 서비스(credentials.CredentialService)가 쇼핑몰 어댑터와 같은 방식으로 다루게 맞춘 속성
|
||||
@property
|
||||
def uses_shared_integration(self) -> bool:
|
||||
return False
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return []
|
||||
|
||||
def visible_fields(self) -> list[CredentialField]:
|
||||
return [f for f in self.credential_fields() if not f.internal]
|
||||
|
||||
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||
"""저장 전 검사. values 의 "__stored__" = 저장된 값이 있음(원문은 꺼내지 않음). 값 자체를 오류 문구에 넣지 않는다."""
|
||||
errors: list[str] = []
|
||||
for f in self.visible_fields():
|
||||
v = (values.get(f.key) or "").strip()
|
||||
if f.required and not v:
|
||||
errors.append(f"{f.label} 을(를) 입력하세요.")
|
||||
elif v and len(v) > 20000:
|
||||
errors.append(f"{f.label} 값이 너무 깁니다.")
|
||||
return errors
|
||||
|
||||
def is_configured(self, ctx: AdapterContext) -> bool:
|
||||
return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required)
|
||||
|
||||
def require_configured(self, ctx: AdapterContext) -> None:
|
||||
if not self.is_configured(ctx):
|
||||
raise NotConfigured("필수 인증정보가 입력되지 않았습니다. 실적 설정 → 광고 API 연동에서 입력하세요.")
|
||||
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
"""성공하면 사람이 읽을 짧은 문구. 실패는 AdapterError."""
|
||||
raise NotImplementedError
|
||||
|
||||
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||
"""기간(양 끝 포함)의 날짜별 광고비. 광고가 없던 날은 빠질 수 있다(저장 쪽이 그날의 예전 API 값을 지운다)."""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,302 @@
|
||||
"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목.
|
||||
|
||||
인증(2026-10-15 사용자: 서비스 계정 Explorer 승인)
|
||||
- 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx.
|
||||
서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다
|
||||
(2024-11 부터 도메인 전체 위임 없이 직접 추가 가능).
|
||||
- **개발자 토큰은 2026-09-09 폐지** — API 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙는다
|
||||
(Cloud Console → Google Ads API Overview 에서 신청). developer-token 머리글은 지금은 무시되고 다음 큰 버전부터 거부되므로
|
||||
보내지 않는다(입력칸도 없음, 예전에 저장한 값은 쓰지 않음).
|
||||
- 요청 머리글: Authorization(Bearer) · login-customer-id(MCC 를 거쳐 들어갈 때만).
|
||||
- Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
|
||||
|
||||
조회(REST googleAds:searchStream, GAQL)
|
||||
SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks,
|
||||
metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date BETWEEN 'from' AND 'to'
|
||||
- 날짜는 광고 계정 시간대 기준(한국 계정이면 KST). 광고가 없던 날은 행이 없을 수 있다.
|
||||
- 금액(광고비) = **부가세 포함**(2026-10-15 사용자 요청) = cost_micros ÷ 1,000,000 × 1.1 을 원 단위로 반올림
|
||||
(구글 광고 비용은 부가세 별도 — 쿠팡 광고비처럼 부가세 포함으로 맞춘다). 계정 통화가 KRW 가 아니면 저장하지 않는다.
|
||||
- ROAS(%) = 전환 가치 ÷ 비용(부가세 별도) × 100 — 구글 광고 화면 "전환 가치/비용"과 같은 값 그대로, 비용이 0 이면 없음.
|
||||
- 나머지 항목(노출수·클릭수·클릭률·전환수·전환 가치)은 광고비 탭 구글 머리글 → 일자별 표.
|
||||
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 구글은 버전을 약 1년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured
|
||||
from .base import AdDay, AdSource
|
||||
|
||||
SCOPE = "https://www.googleapis.com/auth/adwords"
|
||||
API_BASE = "https://googleads.googleapis.com"
|
||||
DEFAULT_VERSION = "v26" # 2026-10 기준 최신(구글 광고 API 는 매월 부 버전·분기마다 새 버전)
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
MAX_DAYS = 366
|
||||
VAT = Decimal("1.1") # 광고비 = 구글 비용 + 부가세 10%
|
||||
|
||||
# 일자별 표(광고비 탭 구글 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
|
||||
M_SPEND, M_COST = "광고비(부가세 포함)", "비용(부가세 별도)"
|
||||
M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "노출수", "클릭수", "클릭률(%)", "전환수", "전환 가치", "ROAS(%)"
|
||||
|
||||
# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
|
||||
_HINTS = {
|
||||
"CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION": "서비스 계정이 속한 Google Cloud 프로젝트에 운영 계정 접근 승인이 없습니다. "
|
||||
"Cloud Console → Google Ads API Overview 에서 그 프로젝트의 Explorer 이상 승인을 확인하세요.",
|
||||
"AUTHORIZATION_ERROR": "API 접근 승인 문제입니다. 서비스 계정이 속한 Cloud 프로젝트의 Google Ads API 승인 상태를 확인하세요.",
|
||||
"INVALID_LOGIN_CUSTOMER_ID": "[로그인 고객 ID(MCC)] 칸 문제입니다. 서비스 계정을 광고 계정에 직접 추가했다면 이 칸을 비우세요"
|
||||
"(칸을 지우고 [연결 테스트] → [저장]). MCC 에 추가했다면 서비스 계정을 추가한 그 MCC 번호여야 하고, "
|
||||
"고객 ID 의 광고 계정이 그 MCC 아래에 있어야 합니다.",
|
||||
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
|
||||
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
|
||||
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
|
||||
"NOT_ADS_USER": "서비스 계정이 구글 광고 사용자로 등록돼 있지 않습니다(액세스 및 보안에서 추가).",
|
||||
"INVALID_CUSTOMER_ID": "고객 ID 가 올바르지 않습니다(광고 계정 오른쪽 위 123-456-7890 형태 번호).",
|
||||
"CUSTOMER_NOT_FOUND": "고객 ID 의 광고 계정을 찾을 수 없습니다.",
|
||||
"SERVICE_ACCOUNT_NOT_ALLOWED": "이 계정은 서비스 계정 접근을 허용하지 않습니다.",
|
||||
}
|
||||
|
||||
_token_lock = threading.Lock()
|
||||
_token_cache: dict[str, tuple[str, float]] = {} # (서비스 계정 이메일, 키 ID) → (액세스 토큰, 만료 시각)
|
||||
|
||||
|
||||
def _digits(value: str) -> str:
|
||||
return re.sub(r"[\s\-]", "", value or "")
|
||||
|
||||
|
||||
def _http(ctx: AdapterContext) -> httpx.Client:
|
||||
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||
return httpx.Client(timeout=ctx.timeout_sec)
|
||||
|
||||
|
||||
def parse_service_account(raw: str) -> dict[str, Any]:
|
||||
"""서비스 계정 JSON 키 → dict. 형식이 틀리면 ValueError(문구에 키 내용을 넣지 않는다)."""
|
||||
try:
|
||||
info = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("서비스 계정 키가 JSON 형식이 아닙니다(구글 클라우드에서 내려받은 .json 파일 내용을 통째로 붙여 넣으세요).") from None
|
||||
if not isinstance(info, dict) or info.get("type") != "service_account":
|
||||
raise ValueError("서비스 계정 키가 아닙니다(\"type\": \"service_account\" 인 JSON 이어야 합니다).")
|
||||
for k in ("client_email", "private_key"):
|
||||
if not str(info.get(k) or "").strip():
|
||||
raise ValueError(f"서비스 계정 키에 {k} 가 없습니다.")
|
||||
return info
|
||||
|
||||
|
||||
def _won(micros: int, rate: Decimal = Decimal(1)) -> int:
|
||||
"""마이크로 단위 금액 × rate → 원(반올림). rate=VAT 면 부가세 포함."""
|
||||
return int((Decimal(int(micros)) * rate / Decimal(1_000_000)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def _num(v: Any) -> Decimal:
|
||||
"""REST 응답 숫자(int64 는 문자열, double 은 숫자, 0 은 아예 빠짐) → Decimal."""
|
||||
if v is None or v == "":
|
||||
return Decimal(0)
|
||||
return Decimal(str(v))
|
||||
|
||||
|
||||
def _google_error(resp: httpx.Response) -> tuple[str, str]:
|
||||
"""구글 오류 응답 → (오류 코드 이름, 사람이 읽을 문구). searchStream 오류는 배열에 싸여 올 수 있다."""
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
return "", f"HTTP {resp.status_code}"
|
||||
if isinstance(body, list):
|
||||
body = next((b for b in body if isinstance(b, dict) and b.get("error")), body[0] if body else {})
|
||||
err = (body or {}).get("error") or {}
|
||||
if isinstance(err, str): # 토큰 교환 오류 {"error": "invalid_grant", "error_description": "..."}
|
||||
return err, str((body or {}).get("error_description") or err)
|
||||
code_name, message = "", str(err.get("message") or f"HTTP {resp.status_code}")
|
||||
for d in err.get("details") or []:
|
||||
for e in (d or {}).get("errors") or []:
|
||||
ec = e.get("errorCode") or {}
|
||||
if ec:
|
||||
code_name = str(next(iter(ec.values())))
|
||||
if e.get("message"):
|
||||
message = str(e["message"])
|
||||
break
|
||||
if code_name:
|
||||
break
|
||||
return code_name, message
|
||||
|
||||
|
||||
class GoogleAdsSource(AdSource):
|
||||
code = "google"
|
||||
name = "구글 광고"
|
||||
docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts"
|
||||
note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. "
|
||||
"준비: ① Google Cloud 서비스 계정 JSON 키(그 Cloud 프로젝트가 Google Ads API Explorer 이상 승인) "
|
||||
"② 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분). "
|
||||
"개발자 토큰은 2026-09-09 폐지돼 필요 없습니다.")
|
||||
|
||||
def credential_fields(self) -> list[CredentialField]:
|
||||
return [
|
||||
CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890",
|
||||
help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."),
|
||||
CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근",
|
||||
help="서비스 계정을 관리자(MCC) 계정에 추가해 그 아래 광고 계정을 볼 때만 MCC 번호를 넣습니다."),
|
||||
CredentialField("service_account_json", "서비스 계정 키(JSON)", secret=True, multiline=True,
|
||||
help="Google Cloud → IAM → 서비스 계정 → 키 → JSON 으로 받은 파일 내용을 통째로 붙여 넣습니다. "
|
||||
"저장 후에는 화면에 다시 보이지 않습니다."),
|
||||
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
|
||||
help=f"비워 두면 {DEFAULT_VERSION}. 구글이 버전 종료를 알리면 새 버전(예: v27)으로 바꿉니다."),
|
||||
]
|
||||
|
||||
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||
errors = super().validate_credentials(values)
|
||||
for key, label in (("customer_id", "고객 ID"), ("login_customer_id", "로그인 고객 ID")):
|
||||
v = (values.get(key) or "").strip()
|
||||
if v and v != "__stored__" and not re.fullmatch(r"\d{10}", _digits(v)):
|
||||
errors.append(f"{label}는 숫자 10자리여야 합니다(예: 123-456-7890).")
|
||||
sa = (values.get("service_account_json") or "").strip()
|
||||
if sa and sa != "__stored__":
|
||||
try:
|
||||
parse_service_account(sa)
|
||||
except ValueError as exc:
|
||||
errors.append(str(exc))
|
||||
ver = (values.get("api_version") or "").strip()
|
||||
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}", ver):
|
||||
errors.append("API 버전은 v26 처럼 v 뒤에 숫자로 입력하세요.")
|
||||
return errors
|
||||
|
||||
# ── 인증 ──────────────────────────────────────────────
|
||||
def _access_token(self, ctx: AdapterContext, client: httpx.Client) -> str:
|
||||
try:
|
||||
info = parse_service_account(ctx.credentials.get("service_account_json"))
|
||||
except ValueError as exc:
|
||||
raise NotConfigured(str(exc)) from None
|
||||
cache_key = f"{info['client_email']}|{info.get('private_key_id', '')}"
|
||||
with _token_lock:
|
||||
hit = _token_cache.get(cache_key)
|
||||
if hit and hit[1] > time.time() + 120:
|
||||
return hit[0]
|
||||
from google.auth import crypt, jwt # noqa: WPS433 — google-auth(requirements)
|
||||
|
||||
try:
|
||||
signer = crypt.RSASigner.from_service_account_info(info)
|
||||
except Exception: # noqa: BLE001 — 키 내용은 문구에 넣지 않는다
|
||||
raise AuthFailed("서비스 계정 키의 private_key 를 읽을 수 없습니다(JSON 파일 내용을 그대로 붙여 넣었는지 확인).") from None
|
||||
now = int(time.time())
|
||||
token_uri = str(info.get("token_uri") or TOKEN_URI)
|
||||
assertion = jwt.encode(signer, {"iss": info["client_email"], "scope": SCOPE, "aud": token_uri,
|
||||
"iat": now, "exp": now + 3600})
|
||||
try:
|
||||
resp = client.post(token_uri, data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||
"assertion": assertion.decode() if isinstance(assertion, bytes) else assertion})
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||
if resp.status_code != 200:
|
||||
name, msg = _google_error(resp)
|
||||
raise AuthFailed(f"서비스 계정 인증 실패({name or resp.status_code}): {msg[:200]} — 키가 삭제·사용 중지되지 않았는지 확인하세요.")
|
||||
body = resp.json()
|
||||
token = str(body.get("access_token") or "")
|
||||
if not token:
|
||||
raise AuthFailed("구글 인증 서버가 액세스 토큰을 주지 않았습니다.")
|
||||
with _token_lock:
|
||||
_token_cache[cache_key] = (token, time.time() + int(body.get("expires_in") or 3600))
|
||||
return token
|
||||
|
||||
def _search(self, ctx: AdapterContext, query: str) -> list[dict[str, Any]]:
|
||||
"""GAQL 한 번 — searchStream 응답(묶음 배열)의 results 를 이어 붙여 돌려준다."""
|
||||
self.require_configured(ctx)
|
||||
cid = _digits(ctx.credentials.get("customer_id"))
|
||||
if not re.fullmatch(r"\d{10}", cid):
|
||||
raise NotConfigured("고객 ID 는 숫자 10자리여야 합니다.")
|
||||
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
|
||||
with _http(ctx) as client:
|
||||
token = self._access_token(ctx, client)
|
||||
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} # 개발자 토큰 없음(2026-09-09 폐지)
|
||||
login = _digits(ctx.credentials.get("login_customer_id"))
|
||||
if login:
|
||||
headers["login-customer-id"] = login
|
||||
ctx.progress.check()
|
||||
try:
|
||||
resp = client.post(f"{API_BASE}/{version}/customers/{cid}/googleAds:searchStream",
|
||||
headers=headers, json={"query": query})
|
||||
except httpx.HTTPError as exc:
|
||||
raise ApiError(f"구글 광고 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||
if resp.status_code == 404:
|
||||
raise ApiError(f"구글 광고 API 버전 {version} 을(를) 쓸 수 없습니다(종료됐을 수 있음) — 실적 설정에서 API 버전을 최신으로 바꾸세요.")
|
||||
if resp.status_code != 200:
|
||||
name, msg = _google_error(resp)
|
||||
hint = _HINTS.get(name, "")
|
||||
text = f"구글 광고 API 오류({name or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
|
||||
raise (AuthFailed if resp.status_code in (401, 403) else ApiError)(text)
|
||||
try:
|
||||
batches = resp.json()
|
||||
except ValueError:
|
||||
raise ApiError("구글 광고 API 응답을 읽을 수 없습니다.") from None
|
||||
if isinstance(batches, dict):
|
||||
batches = [batches]
|
||||
out: list[dict[str, Any]] = []
|
||||
for b in batches or []:
|
||||
out.extend((b or {}).get("results") or [])
|
||||
return out
|
||||
|
||||
# ── 연결 테스트 · 가져오기 ─────────────────────────────
|
||||
def test_connection(self, ctx: AdapterContext) -> str:
|
||||
rows = self._search(ctx, "SELECT customer.id, customer.descriptive_name, customer.currency_code, "
|
||||
"customer.time_zone FROM customer LIMIT 1")
|
||||
c = (rows[0].get("customer") if rows else None) or {}
|
||||
currency = c.get("currencyCode") or "?"
|
||||
msg = f"연결됨 — {c.get('descriptiveName') or '광고 계정'} · 통화 {currency} · 시간대 {c.get('timeZone') or '?'}"
|
||||
if currency != "KRW":
|
||||
msg += " (원화 계정이 아니라 광고비를 가져올 수 없습니다)"
|
||||
return msg
|
||||
|
||||
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
if (end - start).days + 1 > MAX_DAYS:
|
||||
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
|
||||
rows = self._search(
|
||||
ctx,
|
||||
"SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, "
|
||||
"metrics.conversions, metrics.conversions_value FROM customer "
|
||||
f"WHERE segments.date BETWEEN '{start.isoformat()}' AND '{end.isoformat()}'",
|
||||
)
|
||||
sums: dict[date, dict[str, Decimal]] = {}
|
||||
for r in rows:
|
||||
cur = ((r.get("customer") or {}).get("currencyCode") or "").upper()
|
||||
if cur and cur != "KRW":
|
||||
raise ApiError(f"광고 계정 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.")
|
||||
raw_day = (r.get("segments") or {}).get("date")
|
||||
try:
|
||||
day = date.fromisoformat(str(raw_day))
|
||||
except ValueError:
|
||||
continue
|
||||
m = r.get("metrics") or {}
|
||||
acc = sums.setdefault(day, {"cost": Decimal(0), "impr": Decimal(0), "clicks": Decimal(0),
|
||||
"conv": Decimal(0), "value": Decimal(0)})
|
||||
acc["cost"] += _num(m.get("costMicros"))
|
||||
acc["impr"] += _num(m.get("impressions"))
|
||||
acc["clicks"] += _num(m.get("clicks"))
|
||||
acc["conv"] += _num(m.get("conversions"))
|
||||
acc["value"] += _num(m.get("conversionsValue"))
|
||||
out: list[AdDay] = []
|
||||
for day in sorted(sums):
|
||||
a = sums[day]
|
||||
amount = _won(int(a["cost"]), VAT) # 광고비 = 부가세 포함
|
||||
cost = a["cost"] / Decimal(1_000_000)
|
||||
roas = (a["value"] / cost * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if cost > 0 else None
|
||||
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
|
||||
metrics = {
|
||||
M_SPEND: amount,
|
||||
M_COST: _won(int(a["cost"])),
|
||||
M_IMPR: int(a["impr"]),
|
||||
M_CLICKS: int(a["clicks"]),
|
||||
M_CTR: float(ctr) if ctr is not None else None,
|
||||
M_CONV: float(a["conv"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
|
||||
M_VALUE: int(a["value"].quantize(Decimal(1), rounding=ROUND_HALF_UP)),
|
||||
M_ROAS: float(roas) if roas is not None else None,
|
||||
}
|
||||
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
|
||||
return out
|
||||
@@ -0,0 +1,17 @@
|
||||
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import AdSource
|
||||
from .google_ads import GoogleAdsSource
|
||||
|
||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),)
|
||||
_BY_CODE = {s.code: s for s in _SOURCES}
|
||||
|
||||
|
||||
def all_sources() -> tuple[AdSource, ...]:
|
||||
return _SOURCES
|
||||
|
||||
|
||||
def get_source(code: str) -> AdSource | None:
|
||||
return _BY_CODE.get(code)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||||
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||||
- 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계).
|
||||
- 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만.
|
||||
|
||||
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
||||
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
||||
@@ -341,8 +341,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe
|
||||
return merged, sorted(overlap)
|
||||
|
||||
|
||||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널)
|
||||
DETAIL_CHANNELS = frozenset({"naver"})
|
||||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15)
|
||||
DETAIL_CHANNELS = frozenset({"naver", "google"})
|
||||
|
||||
|
||||
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
@@ -498,6 +498,9 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
||||
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||
if s == "upload" and period.start <= d <= period.end),
|
||||
# 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자)
|
||||
"api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||
if s == "api" and period.start <= d <= period.end),
|
||||
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||||
"migration_needed": migration_needed,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
|
||||
|
||||
- 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다.
|
||||
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
|
||||
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
|
||||
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from datetime import date
|
||||
from typing import Any, Callable
|
||||
|
||||
from .ad_sources.registry import all_sources, get_source
|
||||
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError
|
||||
from .credentials import CredentialService
|
||||
from .db import AdCredentialTable
|
||||
from .security.redact import redact_text
|
||||
|
||||
logger = logging.getLogger("performance.ad_sync")
|
||||
|
||||
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
|
||||
_locks: dict[str, threading.Lock] = {}
|
||||
_locks_guard = threading.Lock()
|
||||
|
||||
|
||||
def _lock(code: str) -> threading.Lock:
|
||||
with _locks_guard:
|
||||
return _locks.setdefault(code, threading.Lock())
|
||||
|
||||
|
||||
class AdSyncBusy(Exception):
|
||||
"""같은 광고 채널 가져오기가 이미 진행 중."""
|
||||
|
||||
|
||||
def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService:
|
||||
"""광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표."""
|
||||
return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS)
|
||||
|
||||
|
||||
class AdSyncService:
|
||||
def __init__(self, store: Any, creds: CredentialService) -> None:
|
||||
self._store = store
|
||||
self._creds = creds
|
||||
|
||||
def configured(self) -> dict[str, bool]:
|
||||
return self._creds.configured_codes(list(all_sources()))
|
||||
|
||||
def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||
cleared: set[str] | None = None) -> AdapterContext:
|
||||
trial = values is not None or bool(cleared)
|
||||
acc = self._creds.accessor(code, overrides=values, persist=not trial, user=user, cleared=cleared)
|
||||
return AdapterContext(code=code, credentials=acc, timeout_sec=30.0)
|
||||
|
||||
@staticmethod
|
||||
def _message(exc: Exception, ctx: AdapterContext) -> str:
|
||||
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
|
||||
return redact_text(str(getattr(exc, "message", "") or exc), known)
|
||||
|
||||
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||
cleared: set[str] | None = None) -> dict[str, Any]:
|
||||
"""values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험, cleared = 화면에서 비운 항목(빈 값으로) —
|
||||
그때는 상태를 기록하지 않는다."""
|
||||
src = get_source(code)
|
||||
if src is None:
|
||||
return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."}
|
||||
ctx = self._ctx(code, values=values, user=user, cleared=cleared)
|
||||
trial = bool(values) or bool(cleared)
|
||||
try:
|
||||
src.require_configured(ctx)
|
||||
msg = src.test_connection(ctx)
|
||||
ok, status = True, "ok"
|
||||
except AdapterError as exc:
|
||||
ok, status, msg = False, exc.status, self._message(exc, ctx)
|
||||
except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게
|
||||
logger.exception("ad test failed: %s", code)
|
||||
ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}"
|
||||
if not trial:
|
||||
self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test")
|
||||
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg,
|
||||
"unsaved": trial}
|
||||
|
||||
def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]:
|
||||
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy."""
|
||||
src = get_source(code)
|
||||
if src is None:
|
||||
raise KeyError(code)
|
||||
lock = _lock(code)
|
||||
if not lock.acquire(blocking=False):
|
||||
raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.")
|
||||
try:
|
||||
ctx = self._ctx(code, user=user)
|
||||
try:
|
||||
src.require_configured(ctx)
|
||||
days = src.fetch_days(ctx, start, end)
|
||||
except AdapterError as exc:
|
||||
msg = self._message(exc, ctx)
|
||||
self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync")
|
||||
return {"ok": False, "code": code, "name": src.name, "status": exc.status,
|
||||
"label": STATUS_LABELS.get(exc.status, exc.status), "message": msg}
|
||||
saved = self._store.replace_ad_api_range(
|
||||
code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API")
|
||||
self._store.record_ad_status(code, status="ok", ok=True, kind="sync")
|
||||
return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days),
|
||||
"from": start.isoformat(), "to": end.isoformat()}
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]:
|
||||
"""설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다."""
|
||||
out = []
|
||||
for code, ok in self.configured().items():
|
||||
if not ok:
|
||||
continue
|
||||
try:
|
||||
out.append(self.sync(code, start, end, user=user))
|
||||
except AdSyncBusy as exc:
|
||||
out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — 다음 채널은 계속
|
||||
logger.exception("ad sync failed: %s", code)
|
||||
out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"})
|
||||
return out
|
||||
@@ -83,6 +83,7 @@ class CredentialField:
|
||||
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
|
||||
|
||||
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
|
||||
multiline=True 면 여러 줄 입력칸(서비스 계정 JSON 키 등).
|
||||
"""
|
||||
|
||||
key: str
|
||||
@@ -92,6 +93,7 @@ class CredentialField:
|
||||
help: str = ""
|
||||
placeholder: str = ""
|
||||
internal: bool = False
|
||||
multiline: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -129,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: ...
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)}"
|
||||
|
||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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]]:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||
|
||||
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
|
||||
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||
@@ -103,9 +104,18 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str,
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
job.finish(error=error, last_update_at=last)
|
||||
# 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15)
|
||||
ads: list[dict[str, Any]] = []
|
||||
try:
|
||||
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
|
||||
|
||||
ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER)
|
||||
except Exception: # noqa: BLE001 — 스레드가 죽지 않게
|
||||
logger.exception("auto ad sync failed")
|
||||
ok = sum(1 for r in results if r.get("ok"))
|
||||
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error}
|
||||
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error,
|
||||
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
|
||||
|
||||
|
||||
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||
|
||||
@@ -16,29 +16,38 @@ from .adapters.base import MarketplaceAdapter
|
||||
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
|
||||
|
||||
|
||||
def aad_for(code: str, key: str) -> str:
|
||||
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터."""
|
||||
return f"perf:{code}:{key}"
|
||||
def aad_for(code: str, key: str, ns: str = "") -> str:
|
||||
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터. ns = 이름 공간(광고 API 인증정보는 "ad:") —
|
||||
쇼핑몰 암호문과 광고 암호문을 서로 바꿔 넣어도 복호화되지 않는다."""
|
||||
return f"perf:{ns}{code}:{key}"
|
||||
|
||||
|
||||
class CredentialAccessor:
|
||||
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
|
||||
|
||||
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
|
||||
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None:
|
||||
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "",
|
||||
aad_ns: str = "", cleared: set[str] | None = None) -> None:
|
||||
self._store = store
|
||||
self._code = code
|
||||
self._ns = aad_ns
|
||||
self._ring_loader = ring_loader
|
||||
self._rows = store.credential_rows(code) if store is not None else {}
|
||||
self._cache: dict[str, str] = {}
|
||||
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
|
||||
# 연결 테스트에서 화면 칸을 비운 항목 — 저장값이 있어도 빈 값으로(저장하지 않음)
|
||||
self._cleared = {k for k in (cleared or set()) if k not in self._overrides}
|
||||
self._persist = persist
|
||||
self._user = user
|
||||
|
||||
def has(self, key: str) -> bool:
|
||||
if key in self._cleared:
|
||||
return False
|
||||
return bool(self._overrides.get(key)) or key in self._rows
|
||||
|
||||
def get(self, key: str) -> str:
|
||||
if key in self._cleared:
|
||||
return ""
|
||||
if key in self._overrides:
|
||||
return self._overrides[key]
|
||||
if key in self._cache:
|
||||
@@ -46,7 +55,7 @@ class CredentialAccessor:
|
||||
row = self._rows.get(key)
|
||||
if not row:
|
||||
return ""
|
||||
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader())
|
||||
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key, self._ns), ring=self._ring_loader())
|
||||
self._cache[key] = value
|
||||
return value
|
||||
|
||||
@@ -57,7 +66,7 @@ class CredentialAccessor:
|
||||
return
|
||||
ring = self._ring_loader()
|
||||
self._store.upsert_credential(
|
||||
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring),
|
||||
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key, self._ns), ring=ring),
|
||||
key_version=ring.current_version, user=self._user or "system",
|
||||
)
|
||||
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
|
||||
@@ -68,14 +77,17 @@ class CredentialAccessor:
|
||||
|
||||
|
||||
class CredentialService:
|
||||
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None:
|
||||
"""store = 인증정보 저장소(쇼핑몰: PerformanceStore, 광고 API: db.AdCredentialTable). aad_ns = 암호문 이름 공간."""
|
||||
|
||||
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing], *, aad_ns: str = "") -> None:
|
||||
self._store = store
|
||||
self._ring_loader = ring_loader
|
||||
self._ns = aad_ns
|
||||
|
||||
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
|
||||
user: str = "") -> CredentialAccessor:
|
||||
user: str = "", cleared: set[str] | None = None) -> CredentialAccessor:
|
||||
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
|
||||
persist=persist, user=user)
|
||||
persist=persist, user=user, aad_ns=self._ns, cleared=cleared)
|
||||
|
||||
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
|
||||
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
|
||||
@@ -87,11 +99,12 @@ class CredentialService:
|
||||
item: dict[str, Any] = {
|
||||
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
|
||||
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
|
||||
"multiline": bool(getattr(f, "multiline", False)),
|
||||
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
|
||||
}
|
||||
if row is not None and not f.secret:
|
||||
try:
|
||||
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key),
|
||||
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key, self._ns),
|
||||
ring=self._ring_loader())
|
||||
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
|
||||
item["value"] = ""
|
||||
@@ -127,23 +140,45 @@ 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), ring=ring),
|
||||
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring),
|
||||
key_version=ring.current_version, user=user,
|
||||
)
|
||||
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]:
|
||||
"""예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수)."""
|
||||
@@ -155,12 +190,12 @@ class CredentialService:
|
||||
continue
|
||||
code, key = row["marketplace_code"], row["credential_key"]
|
||||
try:
|
||||
plain = decrypt(token, aad=aad_for(code, key), ring=ring)
|
||||
plain = decrypt(token, aad=aad_for(code, key, self._ns), ring=ring)
|
||||
except Exception: # noqa: BLE001
|
||||
failed += 1
|
||||
continue
|
||||
self._store.upsert_credential(
|
||||
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring),
|
||||
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key, self._ns), ring=ring),
|
||||
key_version=ring.current_version, user="rekey",
|
||||
)
|
||||
done += 1
|
||||
|
||||
@@ -560,3 +560,167 @@ class PerformanceDBStore:
|
||||
(STALE_RUN_AFTER,),
|
||||
).fetchall()
|
||||
return [r["marketplace_code"] for r in rows]
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 광고 API 연동(마이그레이션 007) — 인증정보(암호문)·연결 상태·가져온 광고비
|
||||
# 읽기는 007 미적용이면 빈 값(설정 화면은 안내만), 쓰기는 AdMigrationNeeded("007").
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def ad_api_ready(self) -> bool:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute("SELECT 1 FROM perf_ad_credentials LIMIT 1").fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
return False
|
||||
return True
|
||||
|
||||
def ad_credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT credential_key, encrypted_value, key_version, updated_at, updated_by "
|
||||
"FROM perf_ad_credentials WHERE channel_code = %s", (code,),
|
||||
).fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
return {}
|
||||
return {r["credential_key"]: r for r in rows}
|
||||
|
||||
def ad_credential_keys_by_code(self) -> dict[str, set[str]]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT channel_code, credential_key FROM perf_ad_credentials").fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
return {}
|
||||
out: dict[str, set[str]] = {}
|
||||
for r in rows:
|
||||
out.setdefault(r["channel_code"], set()).add(r["credential_key"])
|
||||
return out
|
||||
|
||||
def upsert_ad_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO perf_ad_credentials (channel_code, credential_key, encrypted_value, key_version, updated_by)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (channel_code, credential_key) DO UPDATE
|
||||
SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version,
|
||||
updated_by = EXCLUDED.updated_by
|
||||
""",
|
||||
(code, key, encrypted_value, key_version, user),
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded("007") from None
|
||||
|
||||
def delete_ad_credential(self, code: str, key: str) -> None:
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute("DELETE FROM perf_ad_credentials WHERE channel_code = %s AND credential_key = %s", (code, key))
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded("007") from None
|
||||
|
||||
def all_ad_credential_rows(self) -> list[dict[str, Any]]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT channel_code AS marketplace_code, credential_key, encrypted_value, key_version "
|
||||
"FROM perf_ad_credentials"
|
||||
).fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
return []
|
||||
|
||||
def ad_source_statuses(self) -> dict[str, dict[str, Any]]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM perf_ad_source_status").fetchall()
|
||||
except pg_errors.UndefinedTable:
|
||||
return {}
|
||||
return {r["channel_code"]: {k: _iso(v) for k, v in r.items()} for r in rows}
|
||||
|
||||
def record_ad_status(self, code: str, *, status: str, ok: bool, error: str = "", kind: str = "test") -> None:
|
||||
"""연결 테스트(kind=test) 또는 가져오기(kind=sync) 결과. 오류가 없으면 예전 오류 문구는 그대로 둔다."""
|
||||
if kind == "sync":
|
||||
sql = """
|
||||
INSERT INTO perf_ad_source_status (channel_code, status, last_sync_at, last_success_sync_at, last_error, last_error_at)
|
||||
VALUES (%(c)s, %(s)s, now(), CASE WHEN %(ok)s THEN now() END, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
|
||||
ON CONFLICT (channel_code) DO UPDATE
|
||||
SET status = EXCLUDED.status, last_sync_at = now(),
|
||||
last_success_sync_at = CASE WHEN %(ok)s THEN now() ELSE perf_ad_source_status.last_success_sync_at END,
|
||||
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
|
||||
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
|
||||
"""
|
||||
else:
|
||||
sql = """
|
||||
INSERT INTO perf_ad_source_status (channel_code, status, last_test_at, last_test_ok, last_error, last_error_at)
|
||||
VALUES (%(c)s, %(s)s, now(), %(ok)s, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
|
||||
ON CONFLICT (channel_code) DO UPDATE
|
||||
SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = %(ok)s,
|
||||
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
|
||||
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
|
||||
"""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(sql, {"c": code, "s": status, "ok": ok, "e": error})
|
||||
except pg_errors.UndefinedTable:
|
||||
return # 007 미적용 — 상태 기록만 못 함(가져오기 자체는 막지 않음)
|
||||
|
||||
def replace_ad_api_range(self, code: str, start: date, end: date,
|
||||
days: list[tuple[date, int, Any, dict[str, Any] | None]], *, user: str = "") -> int:
|
||||
"""광고 API 로 가져온 기간을 한 트랜잭션으로 반영 — days 의 날은 덮어쓰고(source='api', ROAS·보고서 항목 포함,
|
||||
직접 입력·업로드 값이 있던 날도 API 값으로), 기간 안에서 API 가 돌려주지 않은 날은 **예전 API 값만** 지운다
|
||||
(직접 입력·업로드 값은 그대로). days = [(날짜, 금액, ROAS, 항목)]. 반영한 날 수."""
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
keep = {d for d, _, _, _ in days}
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
old = cur.execute(
|
||||
"SELECT spend_date FROM perf_ad_spend WHERE channel_code = %s AND source = 'api' "
|
||||
"AND spend_date BETWEEN %s AND %s", (code, start, end),
|
||||
).fetchall()
|
||||
gone = [(code, r["spend_date"]) for r in old if r["spend_date"] not in keep]
|
||||
if gone:
|
||||
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s "
|
||||
"AND source = 'api'", gone)
|
||||
rows = [(code, d, int(a), "api", user, r, Jsonb(m) if m is not None else None) for d, a, r, m in days]
|
||||
if rows:
|
||||
cur.executemany(
|
||||
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
|
||||
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
|
||||
rows,
|
||||
)
|
||||
except pg_errors.UndefinedTable:
|
||||
raise AdMigrationNeeded("005") from None
|
||||
except pg_errors.UndefinedColumn:
|
||||
raise AdMigrationNeeded("006") from None
|
||||
return len(days)
|
||||
|
||||
|
||||
class AdCredentialTable:
|
||||
"""광고 API 인증정보 표(perf_ad_credentials)를 쇼핑몰 인증정보 저장소와 같은 이름으로 — credentials.CredentialService 가
|
||||
그대로 쓴다(저장·요약·재암호화). 채널 코드가 쇼핑몰 코드 자리에 들어간다."""
|
||||
|
||||
def __init__(self, store: Any) -> None:
|
||||
self._store = store
|
||||
|
||||
def credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
|
||||
return self._store.ad_credential_rows(code)
|
||||
|
||||
def credential_keys_by_code(self) -> dict[str, set[str]]:
|
||||
return self._store.ad_credential_keys_by_code()
|
||||
|
||||
def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
|
||||
self._store.upsert_ad_credential(code, key, encrypted_value=encrypted_value, key_version=key_version, user=user)
|
||||
|
||||
def delete_credential(self, code: str, key: str) -> None:
|
||||
self._store.delete_ad_credential(code, key)
|
||||
|
||||
def all_credential_rows(self) -> list[dict[str, Any]]:
|
||||
return self._store.all_ad_credential_rows()
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -17,8 +17,11 @@ JSON API — 모듈 권한
|
||||
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
||||
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
|
||||
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
|
||||
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭)
|
||||
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글 머리글 클릭)
|
||||
POST /performance/api/ad-sources/{code}/sync 광고 API(구글 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
|
||||
JSON API — 관리자
|
||||
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
|
||||
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
|
||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||
@@ -34,7 +37,7 @@ JSON API — 관리자
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -59,10 +62,13 @@ AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 0
|
||||
"먼저 적용해야 합니다.")
|
||||
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
|
||||
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
|
||||
AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007"
|
||||
"(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.")
|
||||
|
||||
|
||||
def _ad_migration_help(exc: Exception) -> str:
|
||||
return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP
|
||||
text = str(exc)
|
||||
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
|
||||
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||
"먼저 적용해야 합니다.")
|
||||
|
||||
@@ -155,6 +161,11 @@ def ads_page(
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||
)
|
||||
# [구글 광고 불러오기] — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동만
|
||||
from .ad_sources.registry import get_source # noqa: WPS433
|
||||
|
||||
_, ad_sync = _ad_services(store)
|
||||
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in ad_sync.configured().items() if ok]
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
@@ -171,14 +182,37 @@ def settings_page(request: Request):
|
||||
from .dashboard import build_settings # noqa: WPS433
|
||||
|
||||
creds, _ = common.services(request, store)
|
||||
ad_creds, ad_sync = _ad_services(store)
|
||||
versions = creds.key_versions_in_use()
|
||||
for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키
|
||||
versions[v] = versions.get(v, 0) + n
|
||||
ctx = build_settings(
|
||||
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
||||
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
|
||||
key_versions_in_use=versions, sample_count=store.sample_count(),
|
||||
)
|
||||
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
||||
ctx["ad_api_ready"] = store.ad_api_ready()
|
||||
return render_template(request, "performance/settings.html",
|
||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||
|
||||
|
||||
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
|
||||
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
|
||||
from .ad_sources.registry import all_sources # noqa: WPS433
|
||||
from .adapters.base import STATUS_LABELS # noqa: WPS433
|
||||
|
||||
statuses = store.ad_source_statuses()
|
||||
rows = []
|
||||
for s in all_sources():
|
||||
st = statuses.get(s.code, {})
|
||||
status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured")
|
||||
rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status,
|
||||
"status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"),
|
||||
"last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"),
|
||||
"last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")})
|
||||
return rows
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 모듈 권한
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -510,6 +544,114 @@ def api_ad_spend_upload(
|
||||
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _ad_services(store: Any):
|
||||
"""(광고 인증정보 서비스, 광고 가져오기 서비스)."""
|
||||
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
|
||||
|
||||
creds = ad_credentials(store, common.key_ring)
|
||||
return creds, AdSyncService(store, creds)
|
||||
|
||||
|
||||
def _ad_source_or_404(code: str):
|
||||
from .ad_sources.registry import get_source # noqa: WPS433
|
||||
|
||||
src = get_source(code)
|
||||
if src is None:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.")
|
||||
return src
|
||||
|
||||
|
||||
@router.get("/api/ad-sources/{code}/credentials")
|
||||
def api_ad_source_credentials(request: Request, code: str) -> JSONResponse:
|
||||
"""입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양."""
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
src = _ad_source_or_404(code)
|
||||
creds, _ = _ad_services(store)
|
||||
info = creds.describe(src)
|
||||
if not store.ad_api_ready():
|
||||
info["decrypt_error"] = AD_MIGRATION_HELP_007
|
||||
return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url,
|
||||
"key": common.key_status(), **info})
|
||||
|
||||
|
||||
@router.put("/api/ad-sources/{code}/credentials")
|
||||
def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request, admin=True)
|
||||
src = _ad_source_or_404(code)
|
||||
if not common.key_status()["ok"]:
|
||||
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||
creds, _ = _ad_services(store)
|
||||
values = _clean_values(src, payload)
|
||||
clear = [str(k) for k in (payload.get("clear") or [])]
|
||||
merged = creds.merged_values(src, values)
|
||||
for k in clear:
|
||||
if k in merged and not values.get(k):
|
||||
merged[k] = ""
|
||||
errors = src.validate_credentials(merged)
|
||||
if errors:
|
||||
raise HTTPException(status_code=400, detail=" ".join(errors))
|
||||
try:
|
||||
saved = creds.save(src, values, clear=clear, user=user["email"])
|
||||
except AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
return JSONResponse({"saved": saved, **creds.describe(src)})
|
||||
|
||||
|
||||
@router.post("/api/ad-sources/{code}/test")
|
||||
def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값)."""
|
||||
store, user = common.require_store(request, admin=True)
|
||||
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()}
|
||||
cleared = _cleared_keys(src, payload, values)
|
||||
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
|
||||
|
||||
|
||||
@router.post("/api/ad-sources/{code}/sync")
|
||||
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||
"""광고비 탭 [구글 광고 불러오기] — 기간(from·to, 없으면 최근 N일)을 가져와 저장. 오늘 뒤는 잘라낸다.
|
||||
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||
from .ad_sync import AdSyncBusy # noqa: WPS433
|
||||
from .auto_sync import sync_days # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request)
|
||||
src = _ad_source_or_404(code)
|
||||
today = today_kst()
|
||||
end = _parse_date(payload.get("to"), field="종료일") or today
|
||||
start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1))
|
||||
if end < start:
|
||||
start, end = end, start
|
||||
end = min(end, today)
|
||||
if start > end:
|
||||
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
|
||||
days = (end - start).days + 1
|
||||
if days > MAX_BACKFILL_DAYS:
|
||||
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
||||
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
||||
_, ad_sync = _ad_services(store)
|
||||
if not ad_sync.configured().get(code):
|
||||
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
||||
try:
|
||||
res = ad_sync.sync(code, start, end, user=user["email"])
|
||||
except AdSyncBusy as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from None
|
||||
except AdMigrationNeeded as exc:
|
||||
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||
if not res.get("ok"):
|
||||
return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res})
|
||||
return JSONResponse(res)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -616,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 는 바꾸지 않는다."""
|
||||
@@ -678,4 +828,10 @@ def api_rekey(request: Request) -> JSONResponse:
|
||||
if not common.key_status()["ok"]:
|
||||
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||
creds, _ = common.services(request, store)
|
||||
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
|
||||
ad_creds, _ = _ad_services(store)
|
||||
shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키
|
||||
versions = creds.key_versions_in_use()
|
||||
for v, n in ad_creds.key_versions_in_use().items():
|
||||
versions[v] = versions.get(v, 0) + n
|
||||
return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"],
|
||||
"versions_in_use": versions})
|
||||
|
||||
@@ -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]
|
||||
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -72,17 +72,24 @@
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
|
||||
<div class="perf-ad-actions">
|
||||
{% for s in ad_sync_sources %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-ad-sync-btn" data-ad-sync="{{ s.code }}"
|
||||
title="{{ s.name }} API 로 지금 보는 기간(오늘까지)의 광고비·ROAS 를 가져옵니다 — 같은 날은 덮어씀">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">sync</span>{{ s.name }} 불러오기</button>
|
||||
{% endfor %}
|
||||
{% if upload_channels %}
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
|
||||
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="erp-table-wrap perf-table-wrap">
|
||||
<table class="perf-table perf-main">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = 보고서 ROAS(구매완료 광고수익률)"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -96,9 +103,10 @@
|
||||
{% set v = r.cells[c].gross %}
|
||||
{% if r.kind == 'day' and not r.future and not migration_needed %}
|
||||
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
|
||||
<td class="perf-num is-manual-cell{% if v and not up %} is-manual{% endif %}{% if up %} is-upload{% endif %}"
|
||||
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
|
||||
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}"
|
||||
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
|
||||
title="{% if up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% else %}
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% endif %}
|
||||
@@ -111,9 +119,10 @@
|
||||
</div>
|
||||
{% if period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고,
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.</p>
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고,
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
|
||||
구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -191,9 +200,10 @@
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값).
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함).
|
||||
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값).
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
구글·메타는 지금은 직접 입력합니다.
|
||||
메타는 지금은 직접 입력합니다.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -214,4 +224,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -255,4 +255,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261014b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -103,6 +103,50 @@
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
||||
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
|
||||
<div class="erp-card perf-card" id="perf-ad-sources">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">광고 API 연동</h2>
|
||||
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
||||
설정이 끝나면 광고비 탭 [구글 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
|
||||
</div>
|
||||
{% if not ad_api_ready %}
|
||||
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
|
||||
(scripts/sql/performance_db_007_ad_api.sql)을 적용해야 저장할 수 있습니다.</div>
|
||||
{% endif %}
|
||||
<div class="erp-table-wrap">
|
||||
<table class="perf-table perf-set-table">
|
||||
<thead>
|
||||
<tr><th class="perf-th-label">광고</th><th>API 설정</th><th>연결 상태</th><th>마지막 가져오기</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for a in ad_sources %}
|
||||
<tr data-code="{{ a.code }}" data-name="{{ a.name }}" data-api="ad-sources">
|
||||
<th class="perf-td-label" scope="row">{{ a.name }}</th>
|
||||
<td>{% if a.configured %}<span class="perf-pill is-ok">설정완료</span>{% else %}<span class="perf-pill">미설정</span>{% endif %}</td>
|
||||
<td>
|
||||
<span class="perf-status st-{{ a.status }}"
|
||||
title="마지막 연결 테스트: {{ when(a.last_test_at) }}{% if a.last_error %} 최근 오류({{ when(a.last_error_at) }}): {{ a.last_error }}{% endif %}">
|
||||
<i></i>{{ a.status_label }}</span>
|
||||
{% if a.last_error and a.status not in ('ok',) %}<div class="perf-err">{{ a.last_error }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(a.last_sync_at) }}">{{ when(a.last_success_sync_at) }}</td>
|
||||
<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="test">연결 테스트</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="perf-foot perf-muted">
|
||||
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.
|
||||
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="perf-grid2">
|
||||
<div class="erp-card perf-card">
|
||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||
@@ -120,7 +164,7 @@
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
|
||||
{% endif %}
|
||||
<p class="perf-foot perf-muted">
|
||||
API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
|
||||
API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
|
||||
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
|
||||
</p>
|
||||
</div>
|
||||
@@ -204,4 +248,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261014e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
|
||||
@@ -126,7 +126,8 @@ def test_ad_dashboard_month():
|
||||
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
|
||||
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
||||
assert ctx["detail_channels"] == ["naver"]
|
||||
assert ctx["detail_channels"] == ["google", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15)
|
||||
assert ctx["api_cells"] == []
|
||||
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
|
||||
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
|
||||
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
|
||||
|
||||
@@ -60,7 +60,9 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
|
||||
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""}
|
||||
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
|
||||
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
|
||||
"ads": []}
|
||||
|
||||
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""구글 광고 API 연동(2026-10-15) — 입력 검사·토큰·조회·변환·오류 안내·저장 서비스·라우터. 구글 서버는 가짜(httpx MockTransport)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from app.modules.performance import ad_sync
|
||||
from app.modules.performance.ad_sources import google_ads as ga
|
||||
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured
|
||||
from app.modules.performance.credentials import CredentialService, aad_for
|
||||
from app.modules.performance.security import crypto
|
||||
|
||||
KEY1 = "11" * 32
|
||||
|
||||
|
||||
def _sa_json() -> str:
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()).decode()
|
||||
return json.dumps({"type": "service_account", "client_email": "erp@proj.iam.gserviceaccount.com",
|
||||
"private_key_id": "kid1", "private_key": pem, "token_uri": "https://oauth2.googleapis.com/token"})
|
||||
|
||||
|
||||
SA = _sa_json()
|
||||
|
||||
|
||||
class Creds:
|
||||
def __init__(self, values):
|
||||
self.values = values
|
||||
|
||||
def get(self, key):
|
||||
return self.values.get(key, "")
|
||||
|
||||
def has(self, key):
|
||||
return bool(self.values.get(key))
|
||||
|
||||
def set(self, key, value):
|
||||
self.values[key] = value
|
||||
|
||||
def known_secrets(self):
|
||||
return [v for v in self.values.values() if v]
|
||||
|
||||
|
||||
def _ctx(**over):
|
||||
values = {"customer_id": "123-456-7890", "service_account_json": SA}
|
||||
values.update(over)
|
||||
return AdapterContext(code="google", credentials=Creds(values))
|
||||
|
||||
|
||||
def _install(monkeypatch, handler):
|
||||
"""구글(토큰·광고 API) 가짜 서버 — handler(request) 가 searchStream 응답을 만든다. 보낸 요청을 돌려준다."""
|
||||
ga._token_cache.clear()
|
||||
seen = []
|
||||
|
||||
def route(request: httpx.Request) -> httpx.Response:
|
||||
seen.append(request)
|
||||
if request.url.host == "oauth2.googleapis.com":
|
||||
form = parse_qs(request.content.decode())
|
||||
assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] and form["assertion"][0].count(".") == 2
|
||||
return httpx.Response(200, json={"access_token": "ya29.TOKEN", "expires_in": 3600})
|
||||
return handler(request)
|
||||
|
||||
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
|
||||
return seen
|
||||
|
||||
|
||||
ROWS = [{"results": [
|
||||
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-01"},
|
||||
"metrics": {"costMicros": "123456500000", "impressions": "20000", "clicks": "400", "conversions": 12.5,
|
||||
"conversionsValue": 617282.5}},
|
||||
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-02"},
|
||||
"metrics": {"impressions": "50"}}, # 비용 0(값이 빠진 칸)
|
||||
]}, {"results": [
|
||||
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-03"},
|
||||
"metrics": {"costMicros": "1000000", "clicks": "1", "impressions": "10", "conversionsValue": 3000}},
|
||||
]}]
|
||||
|
||||
|
||||
def test_validate_credentials():
|
||||
src = ga.GoogleAdsSource()
|
||||
ok = {"customer_id": "123-456-7890", "service_account_json": SA}
|
||||
assert src.validate_credentials(ok) == []
|
||||
assert src.validate_credentials({**ok, "service_account_json": "__stored__"}) == []
|
||||
assert "developer_token" not in {f.key for f in src.visible_fields()} # 개발자 토큰 폐지(2026-09-09) — 입력칸 없음
|
||||
errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26",
|
||||
"service_account_json": '{"type": "authorized_user"}'})
|
||||
assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음
|
||||
assert "입력하세요" in " ".join(src.validate_credentials({}))
|
||||
assert "JSON" in " ".join(src.validate_credentials({**ok, "service_account_json": "not json"}))
|
||||
|
||||
|
||||
def test_fetch_days_converts_and_sends_headers(monkeypatch):
|
||||
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=ROWS))
|
||||
days = ga.GoogleAdsSource().fetch_days(_ctx(login_customer_id="999-888-7777", api_version="v27"),
|
||||
date(2026, 10, 1), date(2026, 10, 3))
|
||||
api = seen[-1]
|
||||
assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream"
|
||||
assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and "developer-token" not in api.headers # 폐지된 머리글은 보내지 않음
|
||||
assert api.headers["login-customer-id"] == "9998887777"
|
||||
q = json.loads(api.content)["query"]
|
||||
assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q
|
||||
d1, d2, d3 = days
|
||||
# 광고비 = 부가세 포함(2026-10-15): 123,456.5원 × 1.1 = 135,802.15 → 135,802. ROAS 는 구글 값 그대로(617,282.5 ÷ 123,456.5)
|
||||
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 135802, Decimal("500.00"))
|
||||
assert d1.metrics == {"광고비(부가세 포함)": 135802, "비용(부가세 별도)": 123457, "노출수": 20000, "클릭수": 400,
|
||||
"클릭률(%)": 2.0, "전환수": 12.5, "전환 가치": 617283, "ROAS(%)": 500.0}
|
||||
assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "비용(부가세 별도)"] # 일자별 표 열 순서
|
||||
assert (d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (0, None, 0.0) # 비용 0 → ROAS 없음
|
||||
assert (d3.amount, d3.roas) == (1, Decimal("300000.00"))
|
||||
# 토큰은 한 번만 받아 두고 다시 쓴다
|
||||
ga.GoogleAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert sum(1 for r in seen if r.url.host == "oauth2.googleapis.com") == 1
|
||||
assert "login-customer-id" not in seen[-1].headers and "/v26/" in str(seen[-1].url) # 비우면 MCC 없음·기본 버전
|
||||
|
||||
|
||||
def test_errors_are_explained(monkeypatch):
|
||||
src = ga.GoogleAdsSource()
|
||||
denied = [{"error": {"code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED",
|
||||
"details": [{"errors": [{"errorCode": {"authorizationError": "USER_PERMISSION_DENIED"},
|
||||
"message": "User doesn't have permission to access customer."}]}]}}]
|
||||
_install(monkeypatch, lambda req: httpx.Response(403, json=denied))
|
||||
with pytest.raises(AuthFailed) as e:
|
||||
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert "USER_PERMISSION_DENIED" in e.value.message and "액세스 및 보안" in e.value.message
|
||||
|
||||
# 사용자 화면 오류(2026-10-15): 로그인 고객 ID(MCC) 칸에 권한 없는 번호 → 칸을 비우라는 안내
|
||||
bad_login = [{"error": {"code": 403, "message": "PERMISSION_DENIED", "details": [{"errors": [
|
||||
{"errorCode": {"authorizationError": "INVALID_LOGIN_CUSTOMER_ID"},
|
||||
"message": "The login customer id header 'Optional[9998887777]' could not be validated."}]}]}}]
|
||||
_install(monkeypatch, lambda req: httpx.Response(403, json=bad_login))
|
||||
with pytest.raises(AuthFailed) as e:
|
||||
src.fetch_days(_ctx(login_customer_id="999-888-7777"), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert "INVALID_LOGIN_CUSTOMER_ID" in e.value.message and "칸을 지우고" in e.value.message
|
||||
|
||||
_install(monkeypatch, lambda req: httpx.Response(404, text="Not Found"))
|
||||
with pytest.raises(ApiError) as e:
|
||||
src.fetch_days(_ctx(api_version="v19"), date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert "v19" in e.value.message and "API 버전" in e.value.message
|
||||
|
||||
usd = [{"results": [{"customer": {"currencyCode": "USD"}, "segments": {"date": "2026-10-01"}, "metrics": {}}]}]
|
||||
_install(monkeypatch, lambda req: httpx.Response(200, json=usd))
|
||||
with pytest.raises(ApiError, match="USD"):
|
||||
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||
|
||||
with pytest.raises(NotConfigured):
|
||||
src.fetch_days(_ctx(customer_id=""), date(2026, 10, 1), date(2026, 10, 1))
|
||||
|
||||
ga._token_cache.clear()
|
||||
|
||||
def bad_token(request):
|
||||
return httpx.Response(400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."})
|
||||
|
||||
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(bad_token)))
|
||||
with pytest.raises(AuthFailed, match="invalid_grant"):
|
||||
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||
|
||||
|
||||
def test_connection_message(monkeypatch):
|
||||
body = [{"results": [{"customer": {"id": "1234567890", "descriptiveName": "미라네주방", "currencyCode": "KRW",
|
||||
"timeZone": "Asia/Seoul"}}]}]
|
||||
_install(monkeypatch, lambda req: httpx.Response(200, json=body))
|
||||
assert ga.GoogleAdsSource().test_connection(_ctx()) == "연결됨 — 미라네주방 · 통화 KRW · 시간대 Asia/Seoul"
|
||||
|
||||
|
||||
def test_ad_credentials_use_own_namespace():
|
||||
"""광고 인증정보 암호문은 "perf:ad:{채널}:{항목}" 에 묶인다 — 쇼핑몰 암호문과 바꿔 넣으면 복호화되지 않는다."""
|
||||
ring = crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY1})
|
||||
|
||||
class Table:
|
||||
def __init__(self):
|
||||
self.rows = {}
|
||||
|
||||
def credential_rows(self, code):
|
||||
return {k: {"encrypted_value": v, "key_version": 1} for (c, k), v in self.rows.items() if c == code}
|
||||
|
||||
def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
|
||||
self.rows[(code, key)] = encrypted_value
|
||||
|
||||
t = Table()
|
||||
svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS)
|
||||
svc.save(ga.GoogleAdsSource(), {"service_account_json": SA, "customer_id": "1234567890"}, user="king")
|
||||
assert svc.accessor("google").get("service_account_json") == SA
|
||||
assert aad_for("google", "service_account_json", "ad:") == "perf:ad:google:service_account_json"
|
||||
with pytest.raises(Exception):
|
||||
crypto.decrypt(t.rows[("google", "service_account_json")], aad=aad_for("google", "service_account_json"), ring=ring)
|
||||
# 저장된 일반 항목을 화면에서 비우고 [연결 테스트] → 그 항목은 빈 값으로(저장값 무시), 새 입력값이 있으면 그 값
|
||||
svc.save(ga.GoogleAdsSource(), {"login_customer_id": "999-888-7777"}, user="king")
|
||||
acc = svc.accessor("google", cleared={"login_customer_id"})
|
||||
assert acc.get("login_customer_id") == "" and not acc.has("login_customer_id") and acc.get("customer_id") == "1234567890"
|
||||
assert svc.accessor("google").get("login_customer_id") == "999-888-7777"
|
||||
acc = svc.accessor("google", overrides={"login_customer_id": "111-222-3333"}, cleared={"login_customer_id"})
|
||||
assert acc.get("login_customer_id") == "111-222-3333"
|
||||
# [저장] 때 clear 로 보내면 지워진다(빈 칸 = 유지가 아니라 지움)
|
||||
t.delete_credential = lambda code, key: t.rows.pop((code, key))
|
||||
svc.save(ga.GoogleAdsSource(), {}, clear=["login_customer_id"], user="king")
|
||||
assert ("google", "login_customer_id") not in t.rows
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
self.replaced, self.status = [], []
|
||||
|
||||
def ad_credential_keys_by_code(self):
|
||||
return {"google": {"customer_id", "service_account_json"}}
|
||||
|
||||
def ad_credential_rows(self, code):
|
||||
return {}
|
||||
|
||||
def replace_ad_api_range(self, code, start, end, days, *, user=""):
|
||||
self.replaced.append((code, start, end, days, user))
|
||||
return len(days)
|
||||
|
||||
def record_ad_status(self, code, *, status, ok, error="", kind="test"):
|
||||
self.status.append((code, status, ok, error, kind))
|
||||
|
||||
|
||||
def _service(store, source):
|
||||
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||||
svc.configured = lambda: {"google": True}
|
||||
svc._ctx = lambda code, values=None, user="": _ctx()
|
||||
return svc
|
||||
|
||||
|
||||
def test_sync_service_saves_and_records(monkeypatch):
|
||||
store = FakeStore()
|
||||
from app.modules.performance.ad_sources.base import AdDay
|
||||
|
||||
src = ga.GoogleAdsSource()
|
||||
monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})])
|
||||
monkeypatch.setattr(ad_sync, "get_source", lambda code: src)
|
||||
svc = _service(store, src)
|
||||
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 3), user="king@x")
|
||||
assert res["ok"] and res["days"] == 1 and res["total"] == 1000
|
||||
assert store.replaced == [("google", date(2026, 10, 1), date(2026, 10, 3),
|
||||
[(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})], "king@x")]
|
||||
assert store.status[-1] == ("google", "ok", True, "", "sync")
|
||||
|
||||
# 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림)
|
||||
def boom(ctx, s, e):
|
||||
raise AuthFailed("거부된 값 123-456-7890")
|
||||
|
||||
monkeypatch.setattr(src, "fetch_days", boom)
|
||||
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert not res["ok"] and res["status"] == "auth_failed" and "123-456-7890" not in res["message"] # 꺼낸 인증정보 값은 가림
|
||||
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False)
|
||||
|
||||
# 같은 채널 동시 실행 막기
|
||||
lock = ad_sync._lock("google")
|
||||
lock.acquire()
|
||||
try:
|
||||
with pytest.raises(ad_sync.AdSyncBusy):
|
||||
svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
|
||||
assert svc.sync_all(date(2026, 10, 1), date(2026, 10, 1))[0]["skipped"]
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
|
||||
def test_sync_endpoint(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, admin = [], {"v": False}
|
||||
|
||||
class Svc:
|
||||
def __init__(self):
|
||||
self.result = {"ok": True, "code": "google", "name": "구글 광고", "days": 3, "total": 9000}
|
||||
self.conf = {"google": True}
|
||||
|
||||
def configured(self):
|
||||
return self.conf
|
||||
|
||||
def sync(self, code, start, end, *, user=""):
|
||||
calls.append((code, start, end, user))
|
||||
return {**self.result, "from": start.isoformat(), "to": end.isoformat()}
|
||||
|
||||
svc = Svc()
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"}))
|
||||
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15))
|
||||
monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, svc))
|
||||
import app.store as app_store
|
||||
|
||||
monkeypatch.setattr(app_store, "is_admin", lambda user: admin["v"])
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-10-01", "to": "2026-10-31"})
|
||||
assert r.status_code == 200 and r.json()["to"] == "2026-10-15" # 오늘 뒤는 잘라냄
|
||||
assert calls[-1] == ("google", date(2026, 10, 1), date(2026, 10, 15), "king@x")
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||
assert r.status_code == 200 and calls[-1][1] == date(2026, 10, 6) # 기본 = 최근 10일
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"})
|
||||
assert r.status_code == 403 # 92일 넘으면 관리자만
|
||||
admin["v"] = True
|
||||
assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200
|
||||
assert client.post("/performance/api/ad-sources/meta/sync", json={}).status_code == 404
|
||||
svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"}
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||
assert r.status_code == 502 and "권한 없음" in r.json()["detail"]
|
||||
svc.conf = {"google": False}
|
||||
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||
assert r.status_code == 400 and "설정" in r.json()["detail"]
|
||||
@@ -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(
|
||||
|
||||
@@ -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="<html>maintenance</html>"), # 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"}) # 새 값이 있는 칸·모르는 칸은 빼고
|
||||
+113
-80
@@ -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]:
|
||||
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
|
||||
|
||||
@@ -30,6 +30,9 @@ p{margin:0 0 18px}
|
||||
.video iframe{position:absolute;inset:0;width:100%;height:100%}
|
||||
.yt-link{display:flex;align-items:center;gap:12px;margin-bottom:20px;text-decoration:none;color:#c00;font-size:14px}
|
||||
.yt-link img{width:120px;border-radius:6px}
|
||||
/* 형광펜 — 노랑 음영 */
|
||||
mark{background:#fff35c;color:inherit;padding:1px 2px;border-radius:2px;-webkit-box-decoration-break:clone;box-decoration-break:clone}
|
||||
b{font-weight:700}
|
||||
.photo{display:block;max-width:100%;height:auto;margin:12px 0 8px;border-radius:10px}
|
||||
.link-card{display:block;padding:12px 16px;margin:12px 0 20px;background:#eef2ff;border-radius:8px;color:#1e40af;text-decoration:none;word-break:break-all;font-size:14px}
|
||||
.link-card:hover .news-title{text-decoration:underline}
|
||||
@@ -44,18 +47,18 @@ p{margin:0 0 18px}
|
||||
<header>DBX<button type="button" class="close" onclick="window.close()">닫기</button></header>
|
||||
<nav role="tablist">
|
||||
<button class="tab active" data-i="0" role="tab">DBX 존재이유</button>
|
||||
<button class="tab" data-i="1" role="tab">인생을 결정하는 단 1가지</button>
|
||||
<button class="tab" data-i="2" role="tab">부자/성공</button>
|
||||
<button class="tab" data-i="3" role="tab">일을 잘한다는 것</button>
|
||||
<button class="tab" data-i="4" role="tab">일 못하는 사람 특징</button>
|
||||
<button class="tab" data-i="2" role="tab">부자/성공</button>
|
||||
<button class="tab" data-i="5" role="tab">마케팅?</button>
|
||||
<button class="tab" data-i="1" role="tab">인생을 결정하는 단 1가지</button>
|
||||
</nav>
|
||||
</div>
|
||||
<main>
|
||||
<section class="panel active" id="p0" role="tabpanel">
|
||||
<h2>DBX 존재이유</h2>
|
||||
<p>회사의 존재이유 :<br>구성원의 지속 가능 행복실현 / 일 자체가 재미있는 사람들의 채용 / 선별 1순위<br>what? 우리만의 제품으로<br>how? 강력한 콘텐츠로</p>
|
||||
<p>집착 / 몰입 / 고성과<br>=>커머스 선두주자를 학습하고 기존 성과 난 자사 콘텐츠 학습하며(80%)<br>우리만의 콘텐츠(20%)를 끊임없이 빠른 속도로 테스트합니다.</p>
|
||||
<h2>DBX 존재이유 / 일하는 법</h2>
|
||||
<p>회사의 존재이유 :<br>구성원의 지속 가능 행복실현 / <mark>일 자체가 재미있는 사람들의 채용</mark> / 선별 1순위<br>what? 우리만의 제품으로<br>how? 강력한 콘텐츠로</p>
|
||||
<p>집착 / 몰입 / 고성과<br>=>커머스 선두주자를 학습하고 기존 성과 난 자사 콘텐츠 <mark>학습하며(80%)</mark><br><mark>우리만의 콘텐츠(20%)</mark>를 끊임없이 <mark>빠른 속도로 테스트</mark>합니다.</p>
|
||||
<p>고성과 콘텐츠 인사이트 학습(잘하는 경쟁사)<br>끊임없는 시도 끝 우리만의 mim 탄생<br>必!!!) 잘하고 있는(성장 중인) 회사 브랜드 콘텐츠 참고할 것<br>최근 눈여겨볼 브랜드들 직원들이 업데이트할 수 있게 해야 함</p>
|
||||
</section>
|
||||
<section class="panel" id="p1" role="tabpanel">
|
||||
@@ -91,14 +94,14 @@ p{margin:0 0 18px}
|
||||
</section>
|
||||
<section class="panel" id="p3" role="tabpanel">
|
||||
<h2>일을 잘한다는 것</h2>
|
||||
<p>일을 잘한다 = 문제해결능력이 뛰어나다는 것</p>
|
||||
<p><b>일을 잘한다 = 문제해결능력이 뛰어나다는 것</b></p>
|
||||
<p>문제해결 능력이 뛰어나기 위해선<br>간절한 몰입과 끊임없는 시도를 통한 경험이 축적되어야 합니다.</p>
|
||||
<p>영화 '타짜'에서 고니가 평경장에게 배워 최고의 타짜가 되는 과정,<br>영화 위플래쉬 등.(타짜, 위플래쉬 꼭 보세요)</p>
|
||||
<p>비유하자면 수능에서 4점짜리 킬러문항의 경우,<br>대부분의 경우 어디서부터 어떻게 접근해야 하는지조차 가늠하기 어렵지만,<br>낮은 단계에서부터 실력을 쌓고-바로 정답 보지 말고-몇 시간이고 며칠이고 고민을 하며 문제해결을 했을 때 실력이 쌓이게 됩니다.</p>
|
||||
<p>이러한 문제들은 공식이 3-4개가 순차적으로 밑에서 풀어와야 하는데,<br>어디서부터 접근을 해야 하는지가 중요하기 때문이지요.</p>
|
||||
<p>이렇게 몰입해 해결하다 보면 처음엔 며칠이 걸리지만,<br>결국 수능 시험장에서는 10분 내로 풀 수 있는 경지에 이르게 됩니다.</p>
|
||||
<p>십수 년 있다 보니, 모든 업무에서 일을 잘하는 사람도 같은 패턴입니다.</p>
|
||||
<p>이것이 최선의 방법인지, 옳은 접근인지 습관적으로 의문을 던져야 한다.<br>대부분의 사람은 주어진 방법에 의문을 갖지 않고...<br>주어진 매뉴얼과 시킨 방법으로 최선을 다합니다.<br>"원래 그래"라고 하며 관습적으로 일을 하지요<br>이렇게 해서는 절대 근본적인 문제해결은 불가능합니다.</p>
|
||||
<p><b>이것이 최선의 방법인지, 옳은 접근인지 습관적으로 의문을 던져야 한다.</b><br>대부분의 사람은 주어진 방법에 의문을 갖지 않고...<br>주어진 매뉴얼과 시킨 방법으로 최선을 다합니다.<br>"원래 그래"라고 하며 관습적으로 일을 하지요<br>이렇게 해서는 절대 근본적인 문제해결은 불가능합니다.</p>
|
||||
<h3>2. 몰입의 시간이 필요하다 (축적의 시간)</h3>
|
||||
<p>문제 해결을 위해 몇 시간 며칠 머릿속에서 빼지 않고 계속 생각해야 합니다.<br>그러다 보면 어느 순간 우연히 해결방법을 찾게 됩니다.<br>누군가 이 문제에 대해 해결방법을 알고 있을 수 있고, 간단한 질문으로 해결되는 경우도 있습니다. 몰입하지 않으면 이런 실마리가 나올 리가 없죠<br>성과지표의 혁신은 여기에서 시작됩니다.</p>
|
||||
<h3>3. why를 통해 depth를 몇 단계 내려가야 한다.</h3>
|
||||
@@ -110,7 +113,7 @@ p{margin:0 0 18px}
|
||||
<p>3일 밤을 새워 되는 방법 a, b, c를 뽑아내고 으쌰으쌰 파이팅 넘치는 조직을 만들고<br>즉시 실행했습니다. (안 된다, 부정적인 마인드 가진 직원부터 솎아내야 함)</p>
|
||||
<p>일 잘하는 팀장이 입사하면(나도 그랬다) 조직부터 휘어잡습니다.<br>나이브한 팀원은 내보내고 본인의 파이팅을 서포트할 수 있는 팀원부터 구성하죠<br>기존에 있던 회사에서 데리고 오기도 하고, 타깃 회사에서 부족한 부분의 경력직도 채우는 것부터 시작합니다<br>최적의 상황을 만들고 본격적으로 달립니다. 되도록 구조를 만들고 시작하는 것이 핵심입니다.</p>
|
||||
<p>단순히 열심히 한다고 생산성이 2배 3배 올라가지 않습니다.<br>구조부터 해결해야 합니다. 매우 고난도의 능력이며, 시장에서 그런 능력을 가진 사람은 매우 귀합니다.<br>그리고 그런 사람은 뭘하든 어떤 조직에서는 심장이 되지요.</p>
|
||||
<p>조직에서 당신은 계륵입니까 심장입니까??</p>
|
||||
<p><b><mark>조직에서 당신은 계륵입니까 심장입니까??</mark></b></p>
|
||||
</section>
|
||||
<section class="panel" id="p4" role="tabpanel">
|
||||
<h2>일 못하는 사람 특징</h2>
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -98,6 +98,10 @@
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{# 성공하기 — dbx.html(GET /project/dbx)을 닫기 버튼만 있는 별도 창으로(project.js initDbxButton). 프로젝트 목록 바로 위 #}
|
||||
<button type="button" class="pj-btn pj-side-dbx" id="pj-dbx-open">
|
||||
<span class="material-symbols-outlined">emoji_events</span>성공하기</button>
|
||||
|
||||
<div class="pj-side-block pj-tree-block">
|
||||
<div class="pj-side-head">
|
||||
<span>프로젝트</span>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -298,5 +298,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -342,7 +342,8 @@
|
||||
<ul>
|
||||
<li>서식 도구(왼쪽부터): <span class="pjh-ui"><span class="material-symbols-outlined">format_bold</span></span> 굵게 · <span class="pjh-ui"><span class="material-symbols-outlined">format_italic</span></span> 기울임 · <span class="pjh-ui"><span class="material-symbols-outlined">format_underlined</span></span> 밑줄 · <span class="pjh-ui"><span class="material-symbols-outlined">format_strikethrough</span></span> 취소선(<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>) · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_bulleted</span></span> 글머리 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_numbered</span></span> 번호 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span> 체크박스 · <span class="pjh-ui"><span class="material-symbols-outlined">format_quote</span></span> 인용 · <span class="pjh-ui"><span class="material-symbols-outlined">link</span></span> 링크 · <span class="pjh-ui"><span class="material-symbols-outlined">format_clear</span></span> 서식 지우기 · <span class="pjh-ui"><span class="material-symbols-outlined">image</span></span> 이미지 넣기. 아이콘에 마우스를 올리면 이름이 나옵니다.</li>
|
||||
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
||||
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.</li>
|
||||
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.
|
||||
그림을 누른 채 <kbd>Ctrl</kbd>+<kbd>C</kbd>를 누르면 그림이 복사되어 카카오톡·한글·그림판 등에 그대로 붙습니다. 그림을 더블클릭해 연 창에서는 아래 <span class="pjh-ui">복사</span> 버튼이나 <kbd>Ctrl</kbd>+<kbd>C</kbd>로 복사합니다(마우스 오른쪽 메뉴의 "이미지 복사"는 일부 프로그램에서 빈칸으로 붙을 수 있습니다).</li>
|
||||
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 업무가 쌓입니다.</li>
|
||||
</ul>
|
||||
@@ -496,7 +497,7 @@
|
||||
다른 프로젝트에서 연결돼 와 읽기만 되는 업무의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||
<li>오른쪽 위 <span class="pjh-ui">알림 모두 읽음</span> 아이콘(보라색 버튼)으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||
<li><span class="pjh-ui">PC 알림 프로그램 설치</span> — 브라우저가 뒤에 있어도 PC 화면에 알림을 띄우는 프로그램을 내려받고 연결합니다.</li>
|
||||
<li>제목 옆 <span class="pjh-ui">성공하기</span> — DBX 이야기를 별도 창으로 엽니다(창 위 <span class="pjh-ui">닫기</span>로 닫음).</li>
|
||||
<li>왼쪽 메뉴 프로젝트 목록 위 <span class="pjh-ui">성공하기</span> — DBX 이야기를 별도 창으로 엽니다(어느 Project 화면에서나)(창 위 <span class="pjh-ui">닫기</span>로 닫음).</li>
|
||||
</ul>
|
||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||
<table class="pjh-table">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -18,9 +18,6 @@
|
||||
<div class="pj-section-head">
|
||||
<div class="pj-inbox-titlebar">
|
||||
<h2>수신함</h2>
|
||||
{# 성공하기 — dbx.html(GET /project/dbx)을 닫기 버튼만 있는 별도 창으로 연다 #}
|
||||
<button type="button" class="pj-btn pj-inbox-dbx" id="pj-dbx-open">
|
||||
<span class="material-symbols-outlined">emoji_events</span>성공하기</button>
|
||||
</div>
|
||||
<div class="pj-inbox-actions">
|
||||
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
|
||||
@@ -109,15 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script>
|
||||
// 성공하기 — 닫기 버튼만 있는 별도 창(같은 이름이라 여러 번 눌러도 창 하나).
|
||||
document.getElementById("pj-dbx-open").addEventListener("click", function () {
|
||||
var w = Math.min(960, screen.availWidth - 40), h = Math.min(860, screen.availHeight - 60);
|
||||
var win = window.open("/project/dbx", "pj-dbx",
|
||||
"popup=yes,width=" + w + ",height=" + h +
|
||||
",left=" + Math.max(0, (screen.availWidth - w) / 2) + ",top=" + Math.max(0, (screen.availHeight - h) / 2));
|
||||
if (win) win.focus();
|
||||
});
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -470,5 +470,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261014a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
+27
-4
@@ -304,6 +304,9 @@
|
||||
display: flex;
|
||||
gap: var(--sp-8, 8px);
|
||||
align-items: center;
|
||||
/* 편집기 칸이 좁으면(세로 모니터 2분할 등) 버튼이 다음 줄로 — 줄바꿈이 없으면 [카페24에 적용]이 잘려 보이지 않았다 */
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cf24-check-inline {
|
||||
@@ -317,6 +320,10 @@
|
||||
|
||||
.cf24-memo {
|
||||
width: 260px;
|
||||
max-width: 100%;
|
||||
flex: 0 1 260px;
|
||||
min-width: 140px;
|
||||
box-sizing: border-box;
|
||||
padding: 6px var(--sp-10, 10px);
|
||||
border: 1px solid var(--color-subtle-ash, #e5e5e5);
|
||||
border-radius: var(--r-lg, 10px);
|
||||
@@ -809,12 +816,16 @@
|
||||
왼쪽 목록은 좁게, 가운데 편집기가 남는 폭을, 오른쪽 패널은 고정폭.
|
||||
════════════════════════════════════════════════════════════ */
|
||||
.cf24-split.cf24-split-3 {
|
||||
/* 목록은 320~460px 사이에서 줄어들고, 편집기가 남는 폭을, 패널은 380px 고정.
|
||||
1920px: 460 + 380 → 편집기 약 1000px. 1400px: 320 + 380 → 편집기 약 640px. */
|
||||
grid-template-columns: minmax(320px, 460px) minmax(0, 1fr) 380px;
|
||||
/* 목록은 320~460px 사이에서 **먼저** 줄어들고(편집기 640px 를 남기는 폭), 편집기가 남는 폭을, 패널은 380px 고정.
|
||||
minmax(320px, 460px) 였을 때는 목록이 460px 를 먼저 차지해 1440폭(세로 모니터)에서 편집기가 288px 로 눌렸다(2026-10-15).
|
||||
1920px: 목록 460 → 편집기 약 850px. 1601px: 목록 320 → 편집기 약 610px. 그보다 좁으면 아래 2분할. */
|
||||
grid-template-columns: clamp(320px, calc(100% - 380px - 24px - 640px), 460px) minmax(0, 1fr) 380px;
|
||||
}
|
||||
|
||||
@media (max-width: 1360px) {
|
||||
/* 2분할(정보 패널을 편집기 아래로) 경계 — 가로 화면은 예전대로 1360px 이하, **세로 화면은 1600px 이하**(2026-10-15).
|
||||
세로 모니터(2560×1440 → 폭 1440)는 3분할이면 ERP 왼쪽 메뉴(240px)까지 빠져 편집기가 300px 아래로 눌리고, 높이는 넉넉하다.
|
||||
가로 1366~1600 은 높이가 낮아 아래로 내리면 편집기가 300px 대로 낮아지므로 3분할 그대로(목록이 먼저 줄어듦). */
|
||||
@media (max-width: 1360px), (max-width: 1600px) and (orientation: portrait) {
|
||||
/* 폭이 모자라면 정보 패널을 편집기 아래로 내린다(목록은 그대로 왼쪽).
|
||||
아래 칸은 높이를 제한해 편집기가 너무 눌리지 않게 한다(패널 안에서 스크롤). */
|
||||
.cf24-split.cf24-split-3 {
|
||||
@@ -825,16 +836,28 @@
|
||||
.cf24-split-3 > .cf24-pane-list { grid-area: list; }
|
||||
.cf24-split-3 > .cf24-pane-editor { grid-area: editor; }
|
||||
.cf24-split-3 > .cf24-pane-side { grid-area: side; max-height: 38vh; }
|
||||
/* 편집기 칸 높이 = 화면 − 아래 정보 패널(38vh) − 위아래 머리(약 430px). 고정 56vh 면 세로 모니터(1200×1920 등)에서
|
||||
칸보다 커져 편집기 칸 안에서 다시 스크롤해야 했다(2026-10-15). 낮은 화면은 280px 아래로 줄이지 않는다. */
|
||||
.cf24-split-3 .cf24-code { height: max(280px, calc(62vh - 430px)); }
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
/* 한 줄로 쌓을 때는 화면 높이에 가두지 않는다 — 위 ≤1360 의 행 틀(minmax(0,1fr) auto)이 남아 목록이 24px 로
|
||||
눌리고, 편집기(56vh)가 칸을 넘어 아래 정보 패널과 겹쳤다(세로 모니터 1080폭, 2026-10-15). 칸마다 제 높이로
|
||||
쌓고 페이지(.erp-page)가 스크롤한다. */
|
||||
.erp-page > .cf24-split.cf24-split-3 {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.cf24-split.cf24-split-3 {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-areas: none;
|
||||
grid-template-rows: none;
|
||||
}
|
||||
.cf24-split-3 > .cf24-pane-list,
|
||||
.cf24-split-3 > .cf24-pane-editor,
|
||||
.cf24-split-3 > .cf24-pane-side { grid-area: auto; max-height: none; }
|
||||
.cf24-split-3 > .cf24-pane-list { max-height: 45vh; }
|
||||
.cf24-split-3 .cf24-code { height: 56vh; }
|
||||
}
|
||||
|
||||
.cf24-pane-side {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 @@
|
||||
'<div class="erp-notice-card" role="alertdialog" aria-modal="true" aria-labelledby="erp-notice-title">' +
|
||||
'<div class="erp-notice-head"><span class="erp-notice-badge">긴급 공지</span><span class="erp-notice-count" hidden></span></div>' +
|
||||
'<h2 class="erp-notice-title" id="erp-notice-title"></h2>' +
|
||||
'<p class="erp-notice-updated" role="status" hidden>공지 내용이 수정되었습니다. 바뀐 내용을 확인한 뒤 [확인]을 눌러 주세요.</p>' +
|
||||
'<div class="erp-notice-body"></div>' +
|
||||
'<p class="erp-notice-error" role="alert" hidden></p>' +
|
||||
'<div class="erp-notice-foot"><span class="erp-notice-meta"></span>' +
|
||||
@@ -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();
|
||||
|
||||
@@ -58,6 +58,13 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ads .perf-chart .bar { fill: var(--perf-ad); }
|
||||
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
|
||||
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
|
||||
.perf-ads td.is-api .v-gross { color: #1e8e3e; }
|
||||
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.perf-ad-sync-btn { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.perf-ad-sync-btn .material-symbols-outlined { font-size: 16px; color: #1e8e3e; }
|
||||
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
|
||||
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
|
||||
/* "광고비(ROAS%)" — ROAS 는 작게 옅게 붙인다. 입력 중엔 숫자처럼 자리만 남기고 숨김 */
|
||||
.perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); }
|
||||
.perf-row-total .perf-roas { color: #bbb; }
|
||||
|
||||
+52
-18
@@ -383,7 +383,27 @@
|
||||
});
|
||||
});
|
||||
|
||||
// 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||||
// [구글 광고 불러오기] — 광고 API 로 지금 보는 기간(오늘까지)을 가져와 저장(같은 날 덮어씀) → 새로고침.
|
||||
root.addEventListener("click", async function (e) {
|
||||
const btn = e.target.closest("[data-ad-sync]");
|
||||
if (!btn || btn.disabled) return;
|
||||
const label = btn.textContent;
|
||||
btn.disabled = true;
|
||||
btn.textContent = "불러오는 중…";
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/ad-sources/" + encodeURIComponent(btn.dataset.adSync) + "/sync",
|
||||
{ from: data.period_start, to: data.period_end });
|
||||
await alertMsg(res.name + " — " + res.from + " ~ " + res.to + "\n" + (res.days ? res.days + "일, 광고비 ₩" + fmt(res.total) + " 반영" : "이 기간 광고비가 없습니다."),
|
||||
{ tone: "ok" });
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
alertMsg(err.message);
|
||||
btn.disabled = false;
|
||||
btn.textContent = label;
|
||||
}
|
||||
});
|
||||
|
||||
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||||
root.addEventListener("click", async function (e) {
|
||||
const btn = e.target.closest("[data-detail-channel]");
|
||||
if (!btn) return;
|
||||
@@ -394,7 +414,7 @@
|
||||
try {
|
||||
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
|
||||
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
|
||||
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간에 올린 보고서 자료가 없습니다.</p>'; return; }
|
||||
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; }
|
||||
const cols = res.columns || [];
|
||||
const cell = function (v) {
|
||||
if (v == null || v === "") return '<span class="perf-zero">–</span>';
|
||||
@@ -413,7 +433,7 @@
|
||||
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
|
||||
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") +
|
||||
"</tr></tfoot></table></div>" +
|
||||
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.</p>';
|
||||
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
|
||||
} catch (err) {
|
||||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
}
|
||||
@@ -717,9 +737,11 @@
|
||||
if (!btn) return;
|
||||
const tr = btn.closest("tr");
|
||||
const code = tr.dataset.code, name = tr.dataset.name;
|
||||
// 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰
|
||||
const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/";
|
||||
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
|
||||
else if (btn.dataset.act === "creds") openCreds(code, name);
|
||||
else if (btn.dataset.act === "test") runTest(code, name, btn);
|
||||
else if (btn.dataset.act === "creds") openCreds(code, name, base);
|
||||
else if (btn.dataset.act === "test") runTest(code, name, btn, base);
|
||||
});
|
||||
|
||||
function today() {
|
||||
@@ -790,11 +812,12 @@
|
||||
}
|
||||
|
||||
// ── API 인증정보 ──
|
||||
async function openCreds(code, name) {
|
||||
async function openCreds(code, name, base) {
|
||||
base = base || "/performance/api/marketplaces/";
|
||||
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
|
||||
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
|
||||
let info;
|
||||
try { info = await api("GET", "/performance/api/marketplaces/" + code + "/credentials"); }
|
||||
try { info = await api("GET", base + code + "/credentials"); }
|
||||
catch (err) { m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; return; }
|
||||
|
||||
const result = el("span", { class: "perf-test-result" });
|
||||
@@ -818,15 +841,23 @@
|
||||
? '<span class="perf-secret-state">현재 값: •••••••• (저장됨' + (f.updated_at ? ", " + esc(f.updated_at.slice(0, 16).replace("T", " ")) : "") + ")</span>"
|
||||
: '<span class="perf-secret-state is-empty">저장된 값 없음</span>';
|
||||
}
|
||||
// 저장된 일반(비밀 아님) 선택 항목 — 칸을 비우면 저장된 값을 지운다(data-had, cleared())
|
||||
const had = !f.secret && f.has_value && !f.required ? ' data-had="1"' : "";
|
||||
// 여러 줄 항목(서비스 계정 JSON 키 등)은 textarea — 비밀값이면 저장 후 내용은 다시 보이지 않는다
|
||||
const field = f.multiline
|
||||
? '<textarea class="erp-input perf-cred-multi" id="' + id + '" data-key="' + esc(f.key) + '"' + had + ' rows="6" spellcheck="false" ' +
|
||||
'autocomplete="off" placeholder="' + (f.secret && f.has_value ? "변경할 때만 새 값 붙여넣기" : esc(f.placeholder || "붙여넣기")) + '">' +
|
||||
(f.secret ? "" : esc(f.value || "")) + "</textarea>"
|
||||
: '<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '"' + had + " " +
|
||||
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
|
||||
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />";
|
||||
return '<div class="perf-form-row"><label for="' + id + '">' + esc(f.label) + (f.required ? " *" : "") + "</label>" + state +
|
||||
'<input class="erp-input" id="' + id + '" data-key="' + esc(f.key) + '" ' +
|
||||
(f.secret ? 'type="password" autocomplete="new-password" placeholder="' + (f.has_value ? "변경할 때만 새 값 입력" : "입력") + '"'
|
||||
: 'type="text" value="' + esc(f.value || "") + '" placeholder="' + esc(f.placeholder || "") + '"') + " />" +
|
||||
field +
|
||||
(f.help ? '<div class="perf-form-help">' + esc(f.help) + "</div>" : "") +
|
||||
(f.secret && f.has_value && !f.required ? '<label class="perf-check"><input type="checkbox" data-clear="' + esc(f.key) + '" /> 저장된 값 지우기</label>' : "") +
|
||||
"</div>";
|
||||
}).join("") + "</form>" +
|
||||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 칸은 저장된 값 사용). ' +
|
||||
'<p class="perf-foot perf-muted">[연결 테스트]는 입력한 새 값으로 시험하며 저장하지 않습니다(빈 비밀 칸은 저장된 값 사용, 값이 보이던 칸을 비우면 빈 값으로 시험). ' +
|
||||
"[저장]은 연결 테스트 결과와 관계없이 저장합니다 — 쇼핑몰의 일시 장애로 테스트가 실패할 수 있기 때문입니다. " +
|
||||
"저장 후 자동으로 한 번 더 연결 테스트를 합니다.</p>";
|
||||
m.body.innerHTML = html;
|
||||
@@ -835,9 +866,9 @@
|
||||
saveBtn.addEventListener("click", async function () {
|
||||
saveBtn.disabled = true;
|
||||
try {
|
||||
await api("PUT", "/performance/api/marketplaces/" + code + "/credentials", { values: typed(), clear: cleared() });
|
||||
await api("PUT", base + code + "/credentials", { values: typed(), clear: cleared() });
|
||||
m.changed = true;
|
||||
m.body.querySelectorAll("input[type=password]").forEach(function (i) { i.value = ""; });
|
||||
m.body.querySelectorAll("input[type=password], textarea.perf-cred-multi").forEach(function (i) { i.value = ""; });
|
||||
result.className = "perf-test-result";
|
||||
result.textContent = "저장했습니다. 연결 확인 중…";
|
||||
await test(false);
|
||||
@@ -850,19 +881,22 @@
|
||||
|
||||
function typed() {
|
||||
const out = {};
|
||||
m.body.querySelectorAll("input[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); });
|
||||
m.body.querySelectorAll("input[data-key], textarea[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); });
|
||||
return out;
|
||||
}
|
||||
function cleared() {
|
||||
return Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; })
|
||||
const out = Array.prototype.filter.call(m.body.querySelectorAll("input[data-clear]"), function (c) { return c.checked; })
|
||||
.map(function (c) { return c.dataset.clear; });
|
||||
// 저장값이 보이던 일반 칸을 비웠으면 지우기(예: 구글 광고 로그인 고객 ID)
|
||||
m.body.querySelectorAll("[data-had]").forEach(function (i) { if (!i.value.trim() && out.indexOf(i.dataset.key) < 0) out.push(i.dataset.key); });
|
||||
return out;
|
||||
}
|
||||
async function test(withTyped) {
|
||||
testBtn.disabled = true;
|
||||
result.className = "perf-test-result";
|
||||
result.textContent = "연결 확인 중…";
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", withTyped ? { values: typed() } : {});
|
||||
const res = await api("POST", base + code + "/test", withTyped ? { values: typed(), clear: cleared() } : {});
|
||||
result.className = "perf-test-result " + (res.ok ? "is-ok" : "is-bad");
|
||||
result.textContent = (res.ok ? "● " : "● " + res.label + " — ") + res.message + (res.unsaved ? " (저장 안 한 값으로 시험)" : "");
|
||||
if (!res.unsaved) m.changed = true;
|
||||
@@ -874,12 +908,12 @@
|
||||
testBtn.addEventListener("click", function () { test(true); });
|
||||
}
|
||||
|
||||
async function runTest(code, name, btn) {
|
||||
async function runTest(code, name, btn, base) {
|
||||
btn.disabled = true;
|
||||
const label = btn.textContent;
|
||||
btn.textContent = "확인 중…";
|
||||
try {
|
||||
const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {});
|
||||
const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {});
|
||||
await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
|
||||
+15
-7
@@ -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; }
|
||||
@@ -3175,14 +3183,14 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p
|
||||
.pj-notifier-back:hover { color: var(--pj-accent-dark); text-decoration: underline; }
|
||||
.pj-inbox-notifier { display: inline-flex; align-items: center; gap: 4px; text-decoration: none; }
|
||||
.pj-inbox-notifier .material-symbols-outlined { font-size: 18px; }
|
||||
/* 수신함 머리 — 제목은 줄 가운데(굵게), 그 오른쪽에 [성공하기], 맨 오른쪽 버튼들.
|
||||
1fr | 제목 | 1fr 격자라 [성공하기]가 있어도 제목 자체가 정가운데. 모두 확인/읽음은 아이콘만(말풍선 = title) */
|
||||
.pj-inbox-view .pj-main > .pj-section-head { display: grid; grid-template-columns: 1fr auto 1fr; }
|
||||
.pj-inbox-titlebar { grid-column: 2; position: relative; display: flex; align-items: center; }
|
||||
/* 수신함 머리 — 제목 줄 가운데(굵게) | 버튼들 맨 오른쪽.
|
||||
1fr | 제목 | 1fr 격자라 오른쪽 버튼 폭과 상관없이 제목이 정가운데. 모두 확인/읽음은 아이콘만(말풍선 = title) */
|
||||
.pj-inbox-view .pj-main > .pj-section-head { display: grid; grid-template-columns: 1fr auto 1fr; gap: 12px; }
|
||||
/* 성공하기 — 왼쪽 사이드바 프로젝트 목록 바로 위(모든 Project 화면 공용), 아이콘은 버튼 글자보다 크게(18px 의 120%) */
|
||||
.pj-side-dbx { align-self: flex-start; display: inline-flex; align-items: center; gap: 5px; margin: 10px 0 6px 8px; white-space: nowrap; }
|
||||
.pj-side-dbx .material-symbols-outlined { font-size: 21.6px; color: #e8a33d; }
|
||||
.pj-inbox-titlebar { grid-column: 2; display: flex; align-items: center; }
|
||||
.pj-inbox-actions { grid-column: 3; justify-self: end; display: flex; gap: 8px; }
|
||||
.pj-inbox-dbx { position: absolute; left: calc(100% + 12px); top: 50%; transform: translateY(-50%); white-space: nowrap;
|
||||
display: inline-flex; align-items: center; gap: 4px; }
|
||||
.pj-inbox-dbx .material-symbols-outlined { font-size: 18px; color: #e8a33d; }
|
||||
.pj-inbox-iconbtn { display: inline-flex; align-items: center; justify-content: center; padding-left: 10px; padding-right: 10px; }
|
||||
.pj-inbox-iconbtn .material-symbols-outlined { font-size: 20px; }
|
||||
|
||||
|
||||
+141
-18
@@ -2305,6 +2305,47 @@
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── 성공하기(왼쪽 사이드바 프로젝트 목록 위, _side.html) — dbx.html(GET /project/dbx)을 닫기 버튼만 있는 별도 창으로.
|
||||
// 같은 창 이름이라 여러 번 눌러도 창 하나. 사이드바는 화면마다 include 라 문서 단위로 한 번만 건다.
|
||||
document.addEventListener("click", function (e) {
|
||||
if (!e.target.closest || !e.target.closest("#pj-dbx-open")) return;
|
||||
const sw = (window.screen && screen.availWidth) || 1600, sh = (window.screen && screen.availHeight) || 900;
|
||||
const w = Math.min(960, sw - 40), h = Math.min(860, sh - 60);
|
||||
const win = window.open("/project/dbx", "pj-dbx",
|
||||
"popup=yes,width=" + w + ",height=" + h + ",left=" + Math.max(0, Math.round((sw - w) / 2)) + ",top=" + Math.max(0, Math.round((sh - h) / 2)));
|
||||
if (!win) { showToast("팝업이 막혀 있습니다. 브라우저 주소창 오른쪽에서 이 사이트의 팝업을 허용해 주세요.", "error"); return; }
|
||||
try { win.focus(); } catch (_) {}
|
||||
});
|
||||
|
||||
// ── 이미지 → 클립보드(PNG 그림만, 2026-10-15) — 브라우저 기본 복사는 `<img src=첨부 주소>` HTML 을 같이(또는 그것만) 넣는데,
|
||||
// 첨부 주소는 로그인해야 받을 수 있어서 카카오톡·한글·워드처럼 HTML 을 먼저 쓰는 프로그램에선 빈칸이 된다.
|
||||
// 그래서 화면의 이미지를 캔버스로 PNG 로 만들어 그림만 넣는다(같은 서버 이미지라 캔버스가 오염되지 않음).
|
||||
// ClipboardItem 에 Promise 를 넘겨야 변환을 기다리는 동안에도 키·클릭 직후 권한이 유지된다.
|
||||
function imagePngBlob(img) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
function draw() {
|
||||
try {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = img.naturalWidth; c.height = img.naturalHeight;
|
||||
c.getContext("2d").drawImage(img, 0, 0);
|
||||
c.toBlob(function (b) { if (b) resolve(b); else reject(new Error("변환 실패")); }, "image/png");
|
||||
} catch (e) { reject(e); }
|
||||
}
|
||||
if (img.complete && img.naturalWidth) { draw(); return; }
|
||||
img.addEventListener("load", draw, { once: true });
|
||||
img.addEventListener("error", function () { reject(new Error("이미지를 불러오지 못했습니다.")); }, { once: true });
|
||||
});
|
||||
}
|
||||
function copyImageToClipboard(img) {
|
||||
if (!navigator.clipboard || !navigator.clipboard.write || !window.ClipboardItem) {
|
||||
showToast("이 브라우저는 이미지 복사를 지원하지 않습니다. 이미지를 더블클릭해 연 창에서 복사해 주세요.", "error");
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
return navigator.clipboard.write([new ClipboardItem({ "image/png": imagePngBlob(img) })])
|
||||
.then(function () { showToast("이미지를 복사했습니다."); return true; })
|
||||
.catch(function (e) { showToast("이미지 복사 실패: " + ((e && e.message) || e), "error"); return false; });
|
||||
}
|
||||
|
||||
// ── 이미지 보기 창 — 설명란 이미지를 더블클릭하면 별도 브라우저 창(팝업 창, 페이지 안 팝업 아님)으로 연다.
|
||||
// 창 크기 = 이미지 원본 크기(+ 여백·도구 막대), 화면보다 크면 화면 95% 까지. 처음엔 원본(100%), 창보다 크면 창에 맞춤.
|
||||
// 창 안: 휠 = 마우스 위치 기준 확대·축소, 끌기 = 이동, 아래 막대 − / % / + · 1:1(원본) · 맞춤,
|
||||
@@ -2337,12 +2378,19 @@
|
||||
'#pct{min-width:56px;text-align:center;font-size:13px;font-variant-numeric:tabular-nums}' +
|
||||
'.sep{width:1px;height:18px;background:rgba(255,255,255,.18);margin:0 4px}' +
|
||||
'#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;color:#cfd3da;font-size:14px}' +
|
||||
'#msg{position:fixed;left:50%;top:14px;transform:translate(-50%,-8px);padding:7px 14px;border-radius:8px;background:rgba(40,42,47,.95);' +
|
||||
'border:1px solid rgba(255,255,255,.1);font-size:13px;opacity:0;pointer-events:none;transition:opacity .18s,transform .18s;z-index:3}' +
|
||||
'#msg.show{opacity:1;transform:translate(-50%,0)}#msg.bad{color:#ffb4a8}' +
|
||||
'</style></head><body><div id="stage"><img id="img" alt="" draggable="false"></div><div id="err">이미지를 불러오지 못했습니다.</div>' +
|
||||
'<div id="msg" role="status" aria-live="polite"></div>' +
|
||||
'<div id="bar">' +
|
||||
'<button id="out" title="축소 (−)" aria-label="축소">' + ICON('<path d="M5 10h10"/>') + "</button>" +
|
||||
'<span id="pct">100%</span>' +
|
||||
'<button id="in" title="확대 (+)" aria-label="확대">' + ICON('<path d="M5 10h10M10 5v10"/>') + "</button>" +
|
||||
'<span class="sep"></span><button id="one" title="원본 크기 (1)">1:1</button><button id="fit" title="창에 맞춤 (0)">맞춤</button></div>' +
|
||||
'<span class="sep"></span><button id="one" title="원본 크기 (1)">1:1</button><button id="fit" title="창에 맞춤 (0)">맞춤</button>' +
|
||||
'<span class="sep"></span><button id="copy" title="이미지 복사 (Ctrl+C) — 카카오톡·한글·그림판 등에 그림으로 붙여넣기" aria-label="이미지 복사">' +
|
||||
ICON('<rect x="7" y="7" width="10" height="10" rx="1.6"/><path d="M13 7V4.6A1.6 1.6 0 0 0 11.4 3H4.6A1.6 1.6 0 0 0 3 4.6v6.8A1.6 1.6 0 0 0 4.6 13H7"/>') +
|
||||
' 복사</button></div>' +
|
||||
"<script>(function(){" +
|
||||
"var SRC=" + JSON.stringify(src) + ",TITLE=" + JSON.stringify(title) + ";document.title=TITLE;" +
|
||||
"var img=document.getElementById('img'),stage=document.getElementById('stage'),pct=document.getElementById('pct');" +
|
||||
@@ -2363,7 +2411,18 @@
|
||||
"document.getElementById('out').onclick=function(){var m=mid();zoomAt(s/1.25,m[0],m[1]);};" +
|
||||
"document.getElementById('one').onclick=function(){centerAt(1);};" +
|
||||
"document.getElementById('fit').onclick=function(){centerAt(fitScale());};" +
|
||||
"addEventListener('keydown',function(e){var m=mid();if(e.key==='+'||e.key==='='){zoomAt(s*1.25,m[0],m[1]);}else if(e.key==='-'||e.key==='_'){zoomAt(s/1.25,m[0],m[1]);}" +
|
||||
// 복사 = PNG 그림만(copyImageToClipboard 와 같은 이유 — 브라우저 기본 "이미지 복사"의 첨부 주소 HTML 은 로그인 없인 안 열림)
|
||||
"var msg=document.getElementById('msg'),mt=0;" +
|
||||
"function note(t,bad){msg.textContent=t;msg.className=bad?'show bad':'show';clearTimeout(mt);mt=setTimeout(function(){msg.className=bad?'bad':'';},1800);}" +
|
||||
"function pngBlob(){return new Promise(function(ok,no){try{var c=document.createElement('canvas');c.width=img.naturalWidth;c.height=img.naturalHeight;" +
|
||||
"c.getContext('2d').drawImage(img,0,0);c.toBlob(function(b){if(b)ok(b);else no(new Error('변환 실패'));},'image/png');}catch(e){no(e);}});}" +
|
||||
"function copyImg(){if(!img.naturalWidth)return;" +
|
||||
"if(!navigator.clipboard||!navigator.clipboard.write||!window.ClipboardItem){note('이 브라우저는 이미지 복사를 지원하지 않습니다.',1);return;}" +
|
||||
"navigator.clipboard.write([new ClipboardItem({'image/png':pngBlob()})]).then(function(){note('이미지를 복사했습니다.');}," +
|
||||
"function(e){note('복사 실패: '+((e&&e.message)||e),1);});}" +
|
||||
"document.getElementById('copy').onclick=copyImg;" +
|
||||
"addEventListener('keydown',function(e){if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&(e.code==='KeyC'||e.key==='c'||e.key==='C')){e.preventDefault();copyImg();return;}" +
|
||||
"var m=mid();if(e.key==='+'||e.key==='='){zoomAt(s*1.25,m[0],m[1]);}else if(e.key==='-'||e.key==='_'){zoomAt(s/1.25,m[0],m[1]);}" +
|
||||
"else if(e.key==='0'){centerAt(fitScale());}else if(e.key==='1'){centerAt(1);}else if(e.key==='Escape'){window.close();}});" +
|
||||
"})();<\/script></body></html>";
|
||||
win.document.open();
|
||||
@@ -8451,9 +8510,19 @@
|
||||
document.addEventListener("mouseup", function () { dragging = false; });
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (!selectedImg) return;
|
||||
if (e.key !== "Delete" && e.key !== "Backspace") return;
|
||||
const active = document.activeElement;
|
||||
if (active && ["INPUT", "TEXTAREA", "SELECT"].indexOf(active.tagName) >= 0) return;
|
||||
// 고른 이미지 Ctrl+C = PNG 그림으로 복사(copyImageToClipboard). 이미지 선택은 브라우저 선택이 아니라
|
||||
// 이 편집기의 표시라 기본 Ctrl+C 로는 아무것도 복사되지 않았다. 글자를 드래그해 둔 상태면 글자 복사 그대로.
|
||||
// e.code — 한글 입력 상태에선 e.key 가 "ㅊ" 로 온다.
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey && (e.code === "KeyC" || e.key === "c" || e.key === "C")) {
|
||||
const sel = window.getSelection && window.getSelection();
|
||||
if (sel && !sel.isCollapsed && String(sel).trim()) return;
|
||||
e.preventDefault();
|
||||
copyImageToClipboard(selectedImg);
|
||||
return;
|
||||
}
|
||||
if (e.key !== "Delete" && e.key !== "Backspace") return;
|
||||
e.preventDefault();
|
||||
deleteSelectedImage();
|
||||
});
|
||||
@@ -11338,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 = "";
|
||||
@@ -11387,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, {
|
||||
@@ -11397,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 '<button type="button" class="pj-meet-pick-cell' + (text ? "" : " is-empty") + '" data-pick="' + kind + '"' +
|
||||
@@ -11433,7 +11535,10 @@
|
||||
} else if (locked) {
|
||||
acts = "";
|
||||
} else {
|
||||
acts = '<button type="button" class="pj-meet-quick-apply" data-quick="apply">적용</button>' +
|
||||
acts = (r.err && r.unsaved.size
|
||||
? '<button type="button" class="pj-meet-quick-retry" data-quick="retry" title="' + escapeHtml("저장 실패: " + r.err + " — 눌러 다시 저장") +
|
||||
'" aria-label="저장 실패 — 다시 저장"><span class="material-symbols-outlined">sync_problem</span></button>' : "") +
|
||||
'<button type="button" class="pj-meet-quick-apply" data-quick="apply">적용</button>' +
|
||||
'<button type="button" class="pj-meet-quick-del" data-quick="remove" title="이 줄 지우기(아직 등록 전)">' +
|
||||
'<span class="material-symbols-outlined">close</span></button>';
|
||||
}
|
||||
@@ -11448,7 +11553,7 @@
|
||||
const taskCell = r.parentTaskId
|
||||
? cell("task", "↳ " + (r.parentTaskTitle || "업무"), "", ro, "이 업무의 세부 업무로 등록")
|
||||
: cell("task", "", r.registered ? "—" : "새 업무", ro || !r.projectId, r.projectId ? "고르면 그 업무의 세부 업무로 등록(비우면 섹션에 새 업무)" : "프로젝트를 먼저 고르세요");
|
||||
return '<tr data-i="' + i + '"' + (r.registered ? ' class="is-done"' : "") + ">" +
|
||||
return '<tr data-i="' + i + '"' + (r.registered ? ' class="is-done"' : (r.err && r.unsaved.size ? ' class="is-unsaved"' : "")) + ">" +
|
||||
'<td class="pj-meet-quick-title">' + titleCell + "</td>" +
|
||||
"<td>" + (r.assignee
|
||||
? '<button type="button" class="pj-meet-pick-cell is-person" data-pick="assignee"' + (ro ? " disabled" : "") + ">" +
|
||||
@@ -11567,9 +11672,14 @@
|
||||
if (!r.projectId) { showToast("프로젝트를 고르세요."); return; }
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await r.chain;
|
||||
if (!r.id) await persist(r, {});
|
||||
if (!r.id) throw new Error("줄을 저장하지 못했습니다");
|
||||
await saveRow(r);
|
||||
} catch (e) {
|
||||
btn.disabled = false;
|
||||
showToast("입력한 내용이 저장되지 않아 [적용]하지 않았습니다(" + e.message + "). 다시 저장한 뒤 [적용]하세요.", "error");
|
||||
render();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await api("POST", rowUrl(r.id) + "/apply", {});
|
||||
const sub = !!r.parentTaskId;
|
||||
Object.assign(r, fromServer(res.task));
|
||||
@@ -11668,7 +11778,7 @@
|
||||
const t = titleTimers.get(r);
|
||||
if (!t) return;
|
||||
clearTimeout(t); titleTimers.delete(r);
|
||||
persist(r, { title: r.title });
|
||||
return persist(r, { title: r.title });
|
||||
}
|
||||
const rowOf = function (node) { const tr = node.closest("tr"); return tr && tr.dataset.i != null ? rows[+tr.dataset.i] : null; };
|
||||
tbody.addEventListener("input", function (e) {
|
||||
@@ -11699,6 +11809,10 @@
|
||||
if (del) { if (del.dataset.quick === "delete") removeTask(r, del); else dropRow(r); return; }
|
||||
if (e.target.closest('[data-quick="open"]')) { if (modal) closeBig(); requestPanel(r.taskId); return; }
|
||||
if (r.registered || locked) return;
|
||||
if (e.target.closest('[data-quick="retry"]')) {
|
||||
saveRow(r).then(function () { showToast("저장했습니다."); render(); }, function () {});
|
||||
return;
|
||||
}
|
||||
const fail = function (err) { showToast("목록을 읽지 못했습니다: " + err.message, "error"); };
|
||||
if (pick) {
|
||||
e.stopPropagation();
|
||||
@@ -11750,14 +11864,19 @@
|
||||
|
||||
// ── 읽기 — 처음·30초마다·창을 다시 볼 때. 입력 중(제목 칸 포커스·저장 대기)이면 건너뛴다 ──
|
||||
function busy() {
|
||||
return titleTimers.size > 0 || pendingSaves > 0 || (document.activeElement && tbody.contains(document.activeElement));
|
||||
return hasUnsaved() || (document.activeElement && tbody.contains(document.activeElement));
|
||||
}
|
||||
async function load(force) {
|
||||
if (!force && busy()) return;
|
||||
try {
|
||||
const res = await api("GET", listUrl);
|
||||
const blanks = rows.filter(function (r) { return !r.id && !r.title && !r.projectId && !r.assignee; }).length;
|
||||
rows = (res.tasks || []).map(fromServer);
|
||||
// 저장 안 된 초안은 새로 읽어도 지우지 않는다(서버에서 이미 [적용]된 줄은 서버 값)
|
||||
const drafts = {};
|
||||
rows.forEach(function (r) { if (r.id && r.unsaved && r.unsaved.size) drafts[r.id] = r; });
|
||||
const unsent = rows.filter(function (r) { return !r.id && r.unsaved && r.unsaved.size; });
|
||||
rows = (res.tasks || []).map(function (t) { return drafts[t.id] && !t.registered ? drafts[t.id] : fromServer(t); });
|
||||
rows = rows.concat(unsent);
|
||||
for (let i = 0; i < blanks; i++) rows.push(blank());
|
||||
padBlank();
|
||||
unavailable = "";
|
||||
@@ -11798,10 +11917,14 @@
|
||||
await load(true);
|
||||
if (!unavailable && !locked) { await migrateLocal(); await load(true); }
|
||||
})();
|
||||
// 저장 안 된(저장 중·실패한) 입력이 있으면 페이지를 떠나기 전에 묻는다
|
||||
window.addEventListener("beforeunload", function (e) {
|
||||
if (!locked && hasUnsaved()) { e.preventDefault(); e.returnValue = ""; }
|
||||
});
|
||||
setInterval(function () { if (!document.hidden && ready && !panelOpen()) load(false); }, 30000);
|
||||
document.addEventListener("visibilitychange", function () { if (!document.hidden && ready && !panelOpen()) load(false); });
|
||||
if (window.__PJ_TEST__) window.__pjMeetQuick = { load: load, rows: function () { return rows; }, openBig: openBig, closeBig: closeBig,
|
||||
settling: function () { return switching || Promise.resolve(); } };
|
||||
settling: function () { return switching || Promise.resolve(); }, hasUnsaved: hasUnsaved };
|
||||
}
|
||||
|
||||
function initGoalMeeting() {
|
||||
|
||||
@@ -341,8 +341,8 @@
|
||||
});
|
||||
</script>
|
||||
{# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #}
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<script src="/static/erp-notice.js?v=20261012a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261015a" />
|
||||
<script src="/static/erp-notice.js?v=20261015a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
<script src="/static/erp-overdue.js?v=20261014b" defer></script>
|
||||
</body>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<link rel="stylesheet" href="/static/erp-shell.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-attach-viewer.css" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
</head>
|
||||
@@ -192,7 +192,7 @@
|
||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||
<script src="/static/erp-attach-viewer.js" defer></script>
|
||||
{# 긴급 공지 — 로그인한 모든 화면 가운데(받는 사람이 [확인] 전까지). app/modules/notice #}
|
||||
{% if user %}<script src="/static/erp-notice.js?v=20261012a" defer></script>{% endif %}
|
||||
{% if user %}<script src="/static/erp-notice.js?v=20261015a" defer></script>{% endif %}
|
||||
{# 마감 지난 내 업무 — 로그인한 모든 화면 위쪽(닫으면 1시간 뒤 다시). Project 권한이 없으면 조용히 멈춘다. #}
|
||||
{% if user %}<script src="/static/erp-overdue.js?v=20261014b" defer></script>{% endif %}
|
||||
{% block scripts %}{% endblock %}
|
||||
|
||||
@@ -168,8 +168,8 @@
|
||||
setInterval(refreshHealth, 30000);
|
||||
</script>
|
||||
{# 긴급 공지 — erp_base 를 쓰지 않는 화면도 같이(app/modules/notice) #}
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261012c" />
|
||||
<script src="/static/erp-notice.js?v=20261012a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261015a" />
|
||||
<script src="/static/erp-notice.js?v=20261015a" defer></script>
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
<script src="/static/erp-overdue.js?v=20261014b" defer></script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# Main-app 독립 코드 검토 — 2026-10-15
|
||||
|
||||
검토 대상: `edd5a97` 현재 소스. 최근 변경 비교 기준은 `061f18d`(2026-10-08 마지막 커밋), 10월 10일 이후 비병합 커밋 62건이다. 비교 구간에는 132개 파일, 14,619줄 추가·1,389줄 삭제가 있다. 변경이 집중된 프로젝트/회의록, 실적/광고비, 신규 긴급 공지를 중점적으로 읽었고 공통 인증·사용자 저장소, 쿠팡 밀크런 무게 표시, 카페24 관련 코드와 테스트도 확인했다.
|
||||
|
||||
이 검토는 로컬 소스·가짜 API/저장소를 이용한 실패 주입·일부 실제 Edge 브라우저 테스트에 근거한다. 운영 서버·운영 DB·실제 쇼핑몰에는 접속하지 않았다. 실제 PostgreSQL 동시성 및 운영 화면 전체의 시각 검증은 수행하지 않았다. 아래의 “재현”은 따로 표시하지 않는 한 로컬 대역 환경에서의 재현이다.
|
||||
|
||||
## 판단
|
||||
|
||||
모듈 경계, 쇼핑몰별 어댑터, 인증정보 암호화, 프로젝트 접근 판단의 공통화, 카페24 쓰기 안전장치는 갖춰져 있다. 기능 추가 과정에서 문제가 쌓인 부분은 **실패를 다음 단계로 전달하는 방식, 여러 저장 작업의 원자성, 비슷한 화면과 API 사이의 규칙 일치**다. 이를 우선 고치는 편이 효과적이다.
|
||||
|
||||
P1 2건과 P2 7건의 기능 문제, 별도의 테스트 유지보수 문제를 확인했다. 운영에서 이미 발생했다는 의미는 아니다. 정상 성공 경로의 기존 테스트는 대부분 통과하지만 아래 실패 경로는 놓치고 있다.
|
||||
|
||||
작성 도구: 최근 확인한 커밋 `5a4ceea`, `5eaeee2`, `4eda10d`, `66a99e2`, `e7b1e17` 본문에 `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`가 있다. Claude를 사용해 개발했다는 기록은 확인된다. 개별 코드의 작성 주체나 검증 수준을 이 표기만으로 단정할 수는 없다.
|
||||
|
||||
## 확인한 기능 문제
|
||||
|
||||
### F01 · P1 · 잘못된 쿠팡 응답을 정상 0건으로 받아 기존 매출을 비울 수 있음
|
||||
|
||||
- 위치: `app/modules/performance/adapters/coupang.py:298`, `:324`; `app/modules/performance/sync.py:134`; `app/modules/performance/db.py:239`.
|
||||
- HTTP 200 응답이 JSON이 아니면 `_get()`이 오류 대신 `{}`를 만든다. `_pages()`는 이를 주문 0건으로 처리한다. 수집 서비스는 성공으로 판단하고 `replace_events(..., [])`를 호출한다. 실제 저장소는 해당 기간 기존 실데이터를 삭제하고 새 행이 없으면 그대로 커밋한다.
|
||||
- 재현: 모든 쿠팡 요청에 `200 / <html>maintenance</html>`을 주입했다. 결과는 `sync_ok=True`, 교체할 사건 목록 `[]`였다. 운영 데이터 삭제는 실행하지 않았다.
|
||||
- 영향: 프록시·점검 응답이나 응답 규격 이상이 매출 0원으로 반영될 수 있다. 자동 수집에도 같은 경로가 사용된다.
|
||||
- 권장: JSON 파싱 실패와 필수 응답 구조 누락은 `ApiError`로 중단한다. 정상적인 빈 목록임을 확인한 경우에만 기간 교체를 허용한다. HTTP 200이라는 사실만으로 수집 성공을 판단하지 않는다.
|
||||
|
||||
### F02 · P1 · 회의록 [적용]에서 업무 생성과 회의록 연결이 별도 트랜잭션임
|
||||
|
||||
- 위치: `app/modules/project/db.py:3738`, 특히 `:3759`; `app/modules/project/router.py:4015`; `app/modules/project/db.py:664`.
|
||||
- `apply_meeting_task()`는 회의록 줄을 잠근 트랜잭션 안에서 `create()` 콜백을 부른다. 콜백은 `_create_task_for()` → `create_task()`로 들어가 **다른 DB 연결에서 업무를 생성하고 커밋**한다. 이후 원래 연결에서 회의록 줄에 `task_id`를 기록한다.
|
||||
- 재현: 실제 저장소 메서드에 트랜잭션 동작을 모사하는 연결 대역을 넣고, 업무 생성 후 `UPDATE goal_meeting_tasks`에서 실패하도록 했다. 바깥 트랜잭션이 롤백돼도 업무는 남았다. 재시도하면 같은 회의록 줄에서 업무가 하나 더 생겼다.
|
||||
- 영향: 생성됐지만 회의록과 연결되지 않은 업무, 재시도 시 중복 업무. 같은 줄 잠금이 정상 동시 클릭은 막아도 이 실패 구간은 막지 못한다.
|
||||
- 권장: 하나의 DB 연결·트랜잭션에서 업무 생성과 줄 연결을 끝낸다. 알림은 커밋 뒤 처리한다. 회의록 줄 ID를 이용한 생성 중복 방지도 함께 두는 것이 좋다.
|
||||
- 추가 구조 위험: 연결 하나를 잡은 상태에서 같은 풀의 다른 연결을 요구한다. 기본 최대 연결 수가 5라 동시 [적용]이 몰릴 때 풀 대기 문제도 검증해야 한다. 이 동시성 현상은 실제 PostgreSQL에서 재현하지 않았다.
|
||||
|
||||
### F03 · P2 · 회의록 제목 저장 실패 후에도 [적용]이 진행됨
|
||||
|
||||
- 위치: `app/static/project.js:11460`, `:11473`, `:11633`.
|
||||
- `persist()`가 실패를 토스트로 알린 뒤 예외를 삼켜 Promise를 성공 상태로 끝낸다. `apply()`는 `await r.chain`이 끝나면 저장 성공 여부를 확인하지 않고 [적용] API를 부른다.
|
||||
- 재현: 저장된 제목 `OLD SAVED TITLE`을 `NEW UNSAVED TITLE`로 바꾸고 제목 PUT만 500으로 응답하게 했다. [적용]을 누르자 서버에는 이전 제목으로 업무가 생성됐다. 같은 실패 상태에서 페이지 이탈 경고도 없었다.
|
||||
- 영향: 사용자가 방금 입력한 내용과 실제 생성된 업무가 달라진다. 이후 목록 재조회로 실패한 초안이 사라질 수도 있다.
|
||||
- 권장: 실패를 호출자에게 전달하고 미저장 상태를 유지한다. 저장이 성공할 때까지 [적용]을 중단하며 재시도·이탈 경고를 제공한다. 기존 업무 상세 창의 저장 대기·실패 처리 방식을 재사용할 수 있다.
|
||||
|
||||
### F04 · P2 · API 계정 정보를 바꿔도 이전 계정의 토큰을 계속 사용함
|
||||
|
||||
- 위치: `app/modules/performance/credentials.py:138`; `app/modules/performance/adapters/naver.py:228`; 토스도 같은 토큰 재사용 구조.
|
||||
- 인증정보 저장은 전달한 항목만 갱신한다. `client_id`·`client_secret`·`account_id` 등이 바뀌어도 내부의 `access_token`·만료 시각을 무효화하지 않는다. 수집기는 만료까지 남은 시간이 충분하면 이전 토큰을 그대로 쓴다.
|
||||
- 재현: 이전 네이버 계정 토큰을 저장하고 새 client ID·secret·판매자 ID를 저장했다. 다음 `_token()` 결과는 `OLD_ACCOUNT_TOKEN`이었다.
|
||||
- 영향: 계정 변경 후에도 예전 계정의 매출을 수집할 수 있다. 연결 테스트가 새 입력값으로 성공해도 실제 수집과 다른 계정을 사용할 여지가 있다.
|
||||
- 권장: 토큰의 기반이 되는 인증정보가 바뀌면 종속 토큰과 캐시를 무효화한다. 갱신을 한 트랜잭션으로 처리하고, 수집 대상 판매자 식별자도 확인한다.
|
||||
|
||||
### F05 · P2 · 페이지 수 상한에 도달해도 불완전한 수집을 성공으로 반환함
|
||||
|
||||
- 위치: `app/modules/performance/adapters/coupang.py:62`, `:324`; 유사 반복 제한이 있는 다른 어댑터도 같은 기준으로 점검 필요.
|
||||
- `_pages()`는 `MAX_PAGES=400`을 모두 소진해도 다음 커서가 남았는지 확인하지 않고 `out`을 반환한다. 커서가 반복되는 경우도 정상 종료처럼 처리한다.
|
||||
- 재현: 상한을 2로 낮추고 두 번째 응답에도 다음 커서를 넣었다. 예외 없이 두 페이지 결과가 반환됐다. 실제 2만 건을 호출한 것은 아니다.
|
||||
- 영향: 큰 조회 구간의 일부 주문만 수집해 기간 전체를 교체할 수 있다. 부분 수집을 전체 성공으로 표시한다.
|
||||
- 권장: 마지막 페이지임을 확인하지 못하면 교체를 중단한다. 조회 기간을 더 나누거나 명확한 수집 불완전 오류를 반환한다. 페이지 반복 방지와 수집 완료 판정은 구분해야 한다.
|
||||
|
||||
### F06 · P2 · 수집 중 [중지]를 받아들인 뒤에도 저장할 수 있음
|
||||
|
||||
- 위치: `app/modules/performance/jobs.py:47`, `:92`; `app/modules/performance/sync.py:120`.
|
||||
- 중지 검사는 주로 다음 API 호출 전과 진행 단계 갱신 때 이뤄진다. `collect()` 반환 직후에는 중지 상태를 확인하지 않고 `saving()`으로 전환한다. 마지막 API 요청 중 들어온 중지나 마지막 정규화 중의 중지를 놓칠 수 있다.
|
||||
- 재현: `collect()`가 끝나기 직전에 `ShopProgress.stop()`을 호출했다. 중지 요청은 `True`로 수락됐지만, 교체 저장이 실행되고 최종 상태도 `done`이었다.
|
||||
- 영향: 사용자는 “저장하지 않고 중지”를 기대했지만 데이터가 바뀔 수 있다.
|
||||
- 권장: 중지 확인과 `running → saving` 전환을 동일 잠금에서 처리한다. 저장을 시작한 뒤 들어온 요청에는 중지 불가를 명확히 반환한다.
|
||||
|
||||
### F07 · P2 · 열린 긴급 공지의 내용이 바뀌어도 화면은 이전 내용을 유지함
|
||||
|
||||
- 위치: `app/static/erp-notice.js:39`.
|
||||
- 재조회 시 표시 중인 공지 ID가 여전히 존재하면 본문을 갱신하지 않고 개수만 다시 그린다.
|
||||
- 재현: 같은 ID의 본문을 `VERSION ONE`에서 `VERSION TWO`로 바꿔 다음 조회에 반환했다. 화면 본문은 계속 `VERSION ONE`이었다.
|
||||
- 영향: 관리자가 정정한 내용을 읽지 못한 채 [확인]을 누를 수 있다. `reshow=true`로 같은 공지를 다시 띄우는 경우도 현재 열린 창에는 정정 본문이 즉시 반영되지 않는다.
|
||||
- 권장: `updated_at`이나 공지 버전을 수신 응답에 포함하고 버전 변경 시 다시 그린다. 확인 요청에도 읽은 버전을 보내도록 하면 수정 전 내용을 읽은 확인 기록을 구분할 수 있다.
|
||||
|
||||
### F08 · P2 · 아직 표시되지 않은 예약 공지도 [확인] 처리 가능함
|
||||
|
||||
- 위치: `app/modules/notice/router.py:103`; `app/modules/notice/db.py:175` 부근 `ack()`.
|
||||
- 라우터는 공지 존재 여부와 수신 대상 여부만 확인한다. 주석과 달리 `show_at`과 `cancelled_at`을 검사하지 않고, 저장소도 추가 검사를 하지 않는다.
|
||||
- 재현: 2099년 표시 예정인 공지와 취소된 공지에 각각 확인 요청을 보냈다. 둘 다 HTTP 200으로 확인 저장 경로가 호출됐다.
|
||||
- 영향: 공지 ID를 아는 수신자가 예약 공지를 미리 확인 처리할 수 있고, 해당 공지는 실제 표시 시각에 pending 목록에서 제외된다. ID만으로 비수신자가 본문을 읽는 문제를 확인한 것은 아니다.
|
||||
- 권장: 표시 시각·취소 여부·수신 대상을 확인 INSERT와 동일한 DB 문장 또는 트랜잭션에서 검증한다.
|
||||
|
||||
### F09 · P2 · 공통 API 설정 창의 “칸 비우고 연결 테스트”가 쇼핑몰에서는 적용되지 않음
|
||||
|
||||
- 위치: `app/static/performance.js:887`, `:899`; `app/modules/performance/router.py:761`; 광고용 경로 `:605`와 비교.
|
||||
- 공통 화면은 선택 입력칸을 비우면 `clear`를 전송하고 빈 값으로 연결을 시험한다고 안내한다. 광고 테스트 API는 이를 처리하지만 쇼핑몰 테스트 API는 `clear`를 버린다.
|
||||
- 재현: 저장된 네이버 `account_id`가 있는 상태에서 `clear:["account_id"]`를 보냈다. 테스트는 저장된 계정 값을 읽었고, `unsaved=False`로 결과를 반환했다.
|
||||
- 영향: 지운 판매자 ID나 선택 항목이 그대로 사용돼 잘못된 연결 테스트 결과를 볼 수 있다. 저장하지 않은 테스트인데 기존 연결 상태를 변경할 수도 있다.
|
||||
- 권장: 쇼핑몰 테스트에도 광고 테스트와 같은 `cleared` 전달·임시 테스트 판정을 적용한다. 공통 화면을 쓰는 API들의 계약을 통일한다.
|
||||
|
||||
## 테스트 체계에서 확인한 문제
|
||||
|
||||
### F10 · P2 · 일괄 테스트가 신뢰할 수 있는 기본 상태로 유지되지 않음
|
||||
|
||||
검증 환경은 Python 3.12 계열 별도 가상환경에 `requirements.txt`와 pytest를 설치했다. `.env` 자동 로딩을 비활성화하고 데이터 경로는 저장소 밖 임시 폴더로 지정했다. 운영 인증정보를 사용하지 않았다.
|
||||
|
||||
전체 실행:
|
||||
|
||||
```text
|
||||
pytest -q tests app/modules/performance/tests app/modules/cafe24/tests app/modules/dispatch/tests
|
||||
426 passed, 56 failed, 2 skipped, 29 subtests passed
|
||||
```
|
||||
|
||||
- 실패 54개: `tests/test_cafe24_db.py`, `tests/test_project_module.py`는 DB 설정이 없을 때 import 준비만 생략하고 pytest의 테스트 수집은 막지 않는다. `ST`, `ADMIN`, `RUN` 등이 없어 `NameError`로 실패했다. 파일을 직접 실행하는 자체 러너의 skip 처리만 있다. 이 54개를 운영 기능 결함으로 해석하면 안 된다.
|
||||
- 실패 2개: `tests/test_malaysia_stock.py:176`, `:187`은 랙 36칸·A/B만 기대하지만 현재 구현에는 Ground 6칸이 추가돼 42칸이다. 현재 구조에 맞춘 기대값 갱신이 필요하다.
|
||||
- 위 세 파일을 제외한 확인 실행: `407 passed, 2 skipped, 29 subtests passed`. 실제 DB 통합 테스트는 수행하지 못했다.
|
||||
- jsdom UI 테스트 6개 파일 실행: 프로젝트·회의록·목표 탐색·마감 알림·공지 5개 파일 통과. 실적 수동 입력 파일은 3개 검증 실패. 새 구글 광고 데이터·상세 보기·광고 설정 행 추가를 기대값에 반영하지 않은 경우다. 이 세 검증도 최신 요구와 맞춰 정리해야 한다.
|
||||
- 실제 Edge 테스트: `inbox_panel.browser.test.js`, `perf_manual.browser.test.js`, `image_copy.browser.test.js` 통과. 저장 실패 시 수신함 패널 유지·전환 대기, 900/1400px 수동 입력 칸 크기 유지, 이미지 원본 크기 복사를 확인했다. API 응답은 테스트 대역이다.
|
||||
- `app/modules/cafe24/tests/test_cafe24.py:29`에서 import 시 `products.time.sleep`을 직접 대체한다. `time`은 공유 모듈이므로 다른 테스트의 `time.sleep`까지 바뀐다. fixture/patch 범위 안으로 옮겨 테스트 간 간섭을 없애야 한다.
|
||||
|
||||
권장: pytest 공통 진입점과 개발 의존성 명세를 두고, DB 없는 검증은 명시적으로 skip한다. 별도 PostgreSQL 통합 검증과 브라우저 검증을 CI에서 분리해 실행한다. 테스트 수보다 실패·재시도·부분 수집·트랜잭션 경계가 실제로 검증되는지가 중요하다.
|
||||
|
||||
## 중복·비대화·유지보수
|
||||
|
||||
### 1. 프로젝트 화면 스크립트의 책임을 나눌 시점
|
||||
|
||||
`app/static/project.js`는 약 1만 2천 줄로 프로젝트 보드, 업무 상세, 설명 편집기, 댓글/첨부, 수신함, 목표, 회의록, 공통 부품을 함께 담고 있다. 최근 비교 구간에서 이 파일에만 1,775줄이 추가되고 403줄이 삭제됐다. 프로젝트 저장소와 라우터도 각각 수천 줄이다.
|
||||
|
||||
`PJLib` 부품을 쓰기 위해 공지 관리 화면도 이 큰 파일을 불러온다. `PJ_LIB_ONLY`로 초기화를 막는 안전장치는 있지만, 편집기·날짜 선택·멤버 선택·토스트를 작은 공통 모듈로 빼면 의존 관계와 테스트 범위가 줄어든다. 이후 업무 상세, 보드, 수신함, 목표, 회의록 순으로 책임을 나누는 편이 좋다. 파일 수만 늘리는 기계적인 분할은 피한다.
|
||||
|
||||
### 2. 인증·페이지 가드가 여러 모듈에 반복됨
|
||||
|
||||
`_require_user`가 vacation/malaysia/cupang/dispatch/expense/project에 반복되고 설정 필요 화면과 `_guard`도 비슷하게 복제돼 있다. 모듈별 접근 정책은 유지하되 “현재 사용자 조회 → 모듈 권한 → 저장소 준비”라는 반복 절차는 공통 의존성으로 합칠 수 있다.
|
||||
|
||||
기존 `project/access.py`처럼 정책을 한 곳에 모은 부분은 유지할 가치가 있다. 프로젝트 멤버십 정책까지 범용 가드에 섞으면 권한 판단이 흐려질 수 있다.
|
||||
|
||||
### 3. 공통 화면과 서버 구현이 서로 다른 규칙으로 발전함
|
||||
|
||||
F09가 실제 사례다. 같은 입력창을 쓰지만 광고와 쇼핑몰 테스트 API의 `clear` 처리가 다르다. F03도 일반 업무 상세 창에 있는 저장 실패 방어가 회의록 업무 등록 표에 빠진 사례다. 공통 요청·저장 상태 처리를 먼저 정리하고 모듈별 동작을 얹는 방향이 유효하다.
|
||||
|
||||
업무 생성·수정·프로젝트 이동의 완료 상태/담당자 처리도 여러 경로에 분산돼 있어 비교 검증이 필요하다. 예를 들어 프로젝트 이동은 완료 섹션 진입은 처리하지만, 완료 업무를 미완료 섹션으로 이동할 때는 기존 완료 시각을 유지한다(`project/db.py:986`). 같은 프로젝트 안의 섹션 이동은 완료를 해제하는 경로가 있다. 의도한 정책을 정한 뒤 일치시킬 필요가 있다. 이 항목은 확정 버그 수에 포함하지 않았다.
|
||||
|
||||
### 4. 안 쓰는 import보다 규칙 중복을 먼저 정리
|
||||
|
||||
Ruff의 `F821,F811,F401` 검사에서 12건이 나왔고 전부 미사용 import 분류였다. 이 검사에서는 미정의 이름과 함수 재정의가 검출되지 않았다. 12건에는 `asset/__init__.py`의 router 재노출처럼 유지해야 할 항목도 포함된다. 자동 삭제하면 안 된다.
|
||||
|
||||
명백한 정리 후보는 cupang 라우터의 `json`·`SHIP_METHODS`, project 라우터의 `Depends`, 일부 DB 파일의 `timezone` 등이다. 운영 오류 예방 효과는 F01~F09와 저장 계약 정리 쪽이 훨씬 크다. 현재 소스를 근거 없이 “불필요한 코드가 대부분”이라고 평가할 정도는 아니다.
|
||||
|
||||
### 5. 문서·의존성 관리
|
||||
|
||||
- 필독 문서에 휴가 “준비중/미개발”, 관리자 자동 전체 권한 등 현재 구현과 어긋나는 설명이 남아 있다. `project/__init__.py`의 권한 요약도 현재 4등급·멤버십 기준과 다르다.
|
||||
- `SERVER_ARCHITECTURE.md`는 main-app 배포 경로를 여러 후보로 안내하지만 상위 지침은 `/opt/www/main`으로 확정한다. 다른 서비스 경로와 구분하는 설명으로 정리해야 한다.
|
||||
- `requirements.txt`는 대부분 하한만 있어 같은 커밋을 나중에 빌드하면 다른 라이브러리 조합이 설치된다. 검증한 버전 조합을 잠그고 계획적으로 갱신하는 편이 재현에 유리하다. 이번 설치 환경에서도 Starlette의 테스트 클라이언트 관련 deprecation 경고가 나왔다. 이 경고를 현재 운영 장애로 해석하지는 않는다.
|
||||
|
||||
## UI/UX 개선 제안 — 결함과 구분
|
||||
|
||||
1. 자동 저장 상태를 화면 전체에 일관되게 제공한다. 회의록 업무 등록 표에도 “저장 중/실패/재시도”가 지속적으로 보여야 한다. 토스트만으로 실패를 알리면 나중에 어떤 줄이 미저장인지 알기 어렵다.
|
||||
2. 광고비 직접 입력과 자동 수집의 우선순위를 설명한다. 현재 `replace_ad_api_range()`는 API가 반환한 날짜의 수동·업로드 금액도 덮어쓰도록 명시적으로 구현돼 있다. 자동 수집을 켠 채 보정 입력한 사용자에게는 값이 되돌아가는 경험이 된다. 버그로 단정하지 않고 정책 개선 대상으로 본다. 원본 값과 수동 보정 값을 분리하거나 입력 시 덮어쓰기 예정임을 알리는 방안이 있다.
|
||||
3. 긴급 공지의 키보드 탐색을 개선한다. Tab을 무조건 [확인] 버튼으로 돌리기 때문에 본문 링크에 키보드로 접근할 수 없다(`erp-notice.js`의 keydown 처리). 본문의 접근 가능한 요소를 포함해 포커스를 순환시키고 닫힐 때 이전 위치로 복귀하는 편이 좋다.
|
||||
4. 큰 화면 표의 키보드 조작·포커스·모달 닫힘을 공통화한다. `performance.js`의 자체 모달과 프로젝트의 모달은 동작 규칙이 다르다. 같은 사용자가 모듈을 옮겨 다닐 때 조작 방식이 일치하도록 정리할 수 있다.
|
||||
5. 마이그레이션 누락·DB 장애 안내는 일반 사용자용 문구와 관리자 진단을 구분한다. 현재 일부 화면은 SQL 파일명과 환경변수를 바로 보여 준다. 사용자는 “사용 준비 중/관리자에게 문의”를 보고 관리자는 구체적인 진단을 확인하게 하면 된다.
|
||||
|
||||
## 문제로 판정하지 않은 부분
|
||||
|
||||
- Google Ads 개발자 토큰 제거와 기본 버전 v26은 기억에 의존하지 않고 공식 문서를 확인했다. v26은 2026-10-14 릴리스로 확인되고, 개발자 토큰 정책도 변경 안내가 있다. 이를 잘못된 구현으로 지적하지 않았다. [Google Ads 릴리스 노트](https://developers.google.com/google-ads/api/docs/release-notes), [개발자 토큰 정책](https://developers.google.com/google-ads/api/docs/api-policy/developer-token?hl=en).
|
||||
- 카페24는 원격 반영 여부 불명과 로컬 기록 실패를 구분하고 lease·쓰기 잠금·백업·기록 복구 경로를 마련했다. 검토 중 이런 보호 장치를 확인했다. 실제 쇼핑몰과의 운영 검증까지 통과했다고 주장하는 것은 아니다.
|
||||
- 수신함 패널의 저장 완료 대기와 이미지 복사, 실적 수동 입력 시 열 너비 유지는 이번 브라우저 검증을 통과했다.
|
||||
|
||||
## 권장 진행 순서
|
||||
|
||||
1. F01·F02: 수집 검증과 트랜잭션 경계를 먼저 고친다.
|
||||
2. F03·F04·F05·F06: 저장 실패 전파, 계정 변경 시 토큰 무효화, 수집 완료 판정, 중지-저장 전환을 보강한다.
|
||||
3. F07·F08·F09: 공지 버전/확인 조건과 공통 설정창 API 계약을 맞춘다.
|
||||
4. F10: 테스트 진입점·기대값·전역 대체를 정리하고, 위 실패 상황을 회귀 검증에 넣는다.
|
||||
5. 이 검증을 유지하면서 공통 부품과 프로젝트 스크립트를 단계적으로 나눈다.
|
||||
|
||||
이번 작업에서는 애플리케이션 소스와 기존 테스트를 수정하지 않았다. 이 보고서만 저장소에 추가했다. 원래 있던 미추적 `api doc/` 폴더도 변경하지 않았다.
|
||||
@@ -0,0 +1,71 @@
|
||||
# 2026-10-15 코드 검토 — 조치 결과
|
||||
|
||||
원 보고서: `docs/CODE_REVIEW_2026-10-15.md`(edd5a97 기준, 수정하지 않음). 이 문서는 F01~F10 조치와 검증, 남은 위험, 후속 과제를 정리한다.
|
||||
|
||||
검증 환경: 로컬 PC, Python 3.12 가상환경 + `requirements.txt` + pytest 9.1.1, **로컬 PostgreSQL 16**(휴대용, localhost:55432 —
|
||||
`scripts/sql` 의 init·마이그레이션을 그대로 적용, 단 008 의 `pg_trgm` 인덱스 줄만 제외), jsdom 24, 실제 Edge(Playwright).
|
||||
운영 서버·운영 DB·실제 쇼핑몰·SMTP 에는 접속하지 않았다. 각 결함은 **원래 코드(edd5a97, 별도 git worktree)에서 같은 테스트로 먼저 재현**하고
|
||||
수정 후 통과를 확인했다.
|
||||
|
||||
## 항목별
|
||||
|
||||
| | 원인(확인) | 조치 | 주요 위치 | 원래 코드 재현 → 수정 후 |
|
||||
|---|---|---|---|---|
|
||||
| F01 | 쿠팡 `_get()` 이 HTTP 200 비JSON 을 `{}` 로, `_pages()` 가 `data` 없음을 0건으로 → 기간 교체로 매출 삭제 | 2xx 비JSON·`data` 목록 없음 = `ApiError`. 정상 빈 목록(`data: []`, 성공 표시 + `null`)만 0건 | `adapters/coupang.py` `_get`·`_page_rows` | HTML 200 → `ok: True`(교체) → 실패·기존 매출 유지 |
|
||||
| F02 | `apply_meeting_task` 가 줄을 잠근 연결 A 를 쥔 채 `create_task` 가 연결 B 에서 업무 커밋 | 확인은 잠그기 전, 업무 INSERT(`_insert_task`)·줄 연결을 **같은 연결·트랜잭션**, 줄이 바뀌었으면 409, 알림·메일은 커밋 뒤 | `project/db.py` `_insert_task`·`apply_meeting_task`, `project/router.py` `_task_create_checks/_fields/_created_effects`·`api_apply_quick_task` | 실제 PG + 연결 실패 트리거: 2회 시도에 고아 업무 2건 → 0건, 재시도 1건 |
|
||||
| F03 | `persist()` 가 실패를 삼켜 `apply()` 가 이전 제목으로 [적용] | 칸별 미저장 추적, `persist()` 실패 전파, `saveRow()` 성공 전 [적용] 중단, 초안 유지·[다시 저장]·이탈 경고, 새로고침도 초안 보존 | `static/project.js` `initMeetQuickTasks` | `OLD SAVED TITLE` 로 [적용] → 요청 없음, 다시 저장 뒤 새 제목으로 |
|
||||
| F04 | 인증정보 저장이 내부 토큰·만료를 그대로 둠, 토큰은 만료만 확인 | 저장 시 값이 실제로 바뀌면 내부 값 삭제(같은 값은 유지) + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음(시험 입력값 포함), GS샵 방식 캐시도 키 지문 기준 | `credentials.py` `save`, `adapters/base.py` `credential_fingerprint`, `naver.py`·`toss.py`·`gsshop.py` | 키 변경 후 `OLD_ACCOUNT_TOKEN` → 새 토큰 |
|
||||
| F05 | `_pages()` 가 상한 소진·커서 반복을 정상 종료로 | 쿠팡 `TooManyPages` → 구간 반으로(하루까지), 하루도 넘치면 실패. 네이버·카카오·토스(3곳)·GS샵도 상한 소진·커서 반복 = 실패 | `coupang.py` `_pages`·`_seller_orders`·`_rg_orders`, 각 어댑터 쪽 넘김 | 부분 목록 반환 → 실패 / 하루씩 끝까지 |
|
||||
| F06 | `collect()` 반환 뒤 중지 확인 없이 `saving()` | `ShopProgress.begin_saving()` — 중지 확인과 전환을 `stop()` 과 같은 잠금에서, 저장 시작 뒤 중지는 거부 | `jobs.py`, `sync.py` | 중지 수락 후 저장·`done` → 저장 안 함·"중지됨" |
|
||||
| F07 | 같은 ID 공지는 재조회해도 본문을 다시 그리지 않음, 확인에 읽은 내용 정보 없음 | 공지 `version`(updated_at μs), 버전이 바뀌면 다시 그리고 "수정됨" 안내, [확인]에 version → 다르면 409(기록 없음) | `notice/db.py`·`router.py`, `static/erp-notice.js`·`.css` | `VERSION ONE` 유지 → `VERSION TWO` 로 갱신 |
|
||||
| F08 | `api_ack` 가 존재·수신자만 확인, `ack()` 는 무조건 INSERT | `ack()` 한 트랜잭션: 공지 행 `FOR SHARE` 잠금 + 수신자·표시 시각·취소 확인 후 기록(acked/already/stale/denied) | `notice/db.py` `ack`, `router.py` `api_ack` | 예약 공지 확인 기록 → 404·기록 없음, 동시 취소는 잠금 대기 후 거부 |
|
||||
| F09 | 쇼핑몰 테스트 API 가 `clear` 를 버리고 시험도 상태 기록 | `clear` 를 빈 값으로(접근자 `cleared`), values·clear 가 있으면 저장 안 한 시험 — 상태·토큰 저장 안 함. 광고 테스트와 같은 `_cleared_keys` | `sync.py` `test_connection`, `router.py`, `credentials.py` | 저장된 `OLD-SELLER` 로 시험·상태 덮어씀 → 빈 값·상태 유지 |
|
||||
| F10 | DB 테스트 파일이 import 때 가짜 `app.main` 을 바꿔 끼워 서로 덮어씀(DB 있어도 28건 실패), DB 없으면 NameError, 오래된 기대값, import 때 전역 `time.sleep` 대체 | DB 없으면 `pytestmark` skip, 가짜 `app.main`·`time.sleep` 은 파일 범위 fixture(직접 실행도 유지), 말레이시아 Ground 42칸·광고 API 기대값 갱신(검증 추가), `pytest.ini`·`requirements-dev.txt`·`tests/js/package.json`·`docs/TESTING.md` | `tests/test_project_module.py`·`test_cafe24_db.py`, `app/modules/cafe24/tests/test_cafe24.py`, `tests/test_malaysia_stock.py`, `tests/js/perf_manual.test.js` | 아래 실행 결과 |
|
||||
|
||||
## 실행한 테스트(이번 작업, 모두 실제 실행)
|
||||
|
||||
| 구분 | 명령 | 결과 |
|
||||
|---|---|---|
|
||||
| Python, DB 없음 | `python -m pytest -q` | **440 passed, 63 skipped**(DB 통합), 실패 0 — 작업 전 426 passed / 56 failed |
|
||||
| Python, 로컬 PG | `PROJECT_TEST_DB_URL=… CAFE24_TEST_DB_URL=… python -m pytest -q` | **503 passed**, 실패 0 |
|
||||
| 직접 실행 | `python tests/test_project_module.py` · `tests/test_cafe24_db.py` · `-m app.modules.cafe24.tests.test_cafe24` | 35 · 23 · 127 통과, DB 없으면 SKIP |
|
||||
| jsdom | project_ui · goals_meeting_ui · goal_nav_ui · overdue_ui · notice_ui · perf_manual · help_ui | 전부 ALL PASS(178·244·—·12·12·51·—) |
|
||||
| 실제 Edge | asset · goal_nav · help · image_copy · inbox_panel · perf_manual `.browser.test.js` | ALL PASS |
|
||||
| 실제 Edge | `goals_autofit.browser.test.js` | 앞 7항목 통과 후 회의록 측정에서 `TypeError`(요소 없음) — **원래 코드에서도 같은 위치에서 실패**(이번 변경과 무관, 미조치) |
|
||||
|
||||
새 회귀 테스트: `app/modules/performance/tests/test_review_2026_10_15.py`(F01·F04·F05·F06·F09, 15건 — 원래 코드에서 14건 실패),
|
||||
`tests/test_project_module.py::test_review_meeting_apply_is_one_transaction`(F02, 실제 PG), `tests/test_notice_db.py` 3건·`tests/test_notice.py`(F07·F08),
|
||||
`tests/js/goals_meeting_ui.test.js` [2g9](F03), `tests/js/notice_ui.test.js` F07.
|
||||
|
||||
## 미검증·남은 위험
|
||||
|
||||
- **실제 쇼핑몰 응답**: F01 의 "성공 표시 + `data: null` = 빈 목록" 허용은 문서·기존 테스트 응답 기준 추정. 쿠팡이 빈 기간에 다른 모양을 주면
|
||||
그 기간 수집이 실패로 나온다(데이터는 지워지지 않음 — 오류 문구로 드러남).
|
||||
- **F05 다른 어댑터**: 상한·커서 반복을 실패로 바꿨을 뿐 기간 분할 재시도는 쿠팡만. 한 구간이 상한을 넘는 날(예: 네이버 하루 2만 건 초과)은
|
||||
자동 복구 없이 실패로 알린다.
|
||||
- **F04**: 배포 직후 네이버·토스는 지문 없는 기존 토큰 때문에 한 번 새 토큰을 받는다(토스는 문서상 잦은 재발급 제한 안내가 있으나 1회).
|
||||
- **동시성**: F02·F08 은 로컬 단일 PostgreSQL 에서 트리거·잠금으로 검증. 운영 부하·연결 수 조건은 재현하지 않았다.
|
||||
- **F06**: 전체 [업데이트 취소](job 단위)는 쇼핑몰 잠금과 다른 잠금이라, 저장 시작과 거의 동시에 들어온 전체 취소는 그 쇼핑몰 저장을 막지 못할 수
|
||||
있다(기존 문서의 "저장 중이면 그 저장은 끝낸다"와 같은 동작). 쇼핑몰별 [중지]는 막힌다.
|
||||
- **F07**: version 없는 예전 화면(브라우저 캐시)의 [확인]은 내용 확인을 건너뛴다 — 스크립트 버전을 올려 새로고침 때 바뀐다.
|
||||
|
||||
## 운영 적용 전 확인
|
||||
|
||||
- **마이그레이션 없음, 새 환경변수 없음.** 스키마 변경 없이 코드만.
|
||||
- 웹만 다시 띄우면 된다(카페24 worker 코드는 바뀌지 않음 — 카페24 테스트 파일만 수정):
|
||||
`cd /opt/www/main && git pull && docker compose up --build -d web`
|
||||
- 배포 후 확인: 실적 [매출 업데이트] 정상 완료(쿠팡·네이버·토스 — 토스·네이버는 토큰 한 번 재발급), 회의록 업무 등록 표 [적용],
|
||||
긴급 공지 띄움·[확인], 실적 설정 연결 테스트(칸 비우기 포함).
|
||||
|
||||
## 후속 개선안(이번 범위 밖 — 결함 수정과 분리)
|
||||
|
||||
1. **프로젝트 화면 스크립트 분리**: `project.js`(약 1.2만 줄)를 공통 부품(편집기·날짜·멤버 선택·토스트, 공지 관리 화면도 씀) → 업무 상세 → 보드
|
||||
→ 수신함 → 목표 → 회의록 순으로 책임별 분리. 회의록 업무 등록 표의 저장 상태 처리(F03)를 다른 칸 저장(`createFieldSaver`)과 공통화.
|
||||
2. **공통 가드 정리**: 모듈마다 반복되는 "사용자 조회 → 모듈 권한 → 저장소 준비"를 공통 의존성으로. 프로젝트 멤버십 정책(`access.py`)은 섞지 않는다.
|
||||
3. **광고비 수동 보정 정책**: `replace_ad_api_range()` 는 API 가 준 날의 직접 입력·업로드 값을 덮어쓴다. 원본(API) 값과 보정 값을 나눠 저장하거나,
|
||||
입력 때 "다음 불러오기에서 덮어씀"을 알리는 방안 중 결정 필요.
|
||||
4. **모달·키보드 UX 공통화**: 긴급 공지 Tab 이 [확인]으로만 가서 본문 링크에 키보드로 못 감(포커스 순환·닫힌 뒤 복귀), 실적 자체 모달과
|
||||
프로젝트 모달의 Esc·바깥 클릭·포커스 규칙 통일.
|
||||
5. **기타 보고서 항목**: 업무 이동 시 완료 상태 정책 통일(`project/db.py` 프로젝트 이동 vs 섹션 이동), 미사용 import 정리(자동 삭제 금지 —
|
||||
재노출 import 있음), `requirements.txt` 버전 고정, 마이그레이션 누락 안내를 일반 사용자/관리자용으로 나누기,
|
||||
`goals_autofit.browser.test.js` 회의록 측정 실패(원래부터) 원인 확인.
|
||||
@@ -211,6 +211,22 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend"
|
||||
|
||||
되돌리기(보고서 ROAS·상세만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas;"`
|
||||
|
||||
## 실적 광고 API 연동 마이그레이션 (performance_db 007)
|
||||
|
||||
007은 광고 API(구글 광고) 인증정보 표 `perf_ad_credentials`·연결 상태 표 `perf_ad_source_status` 두 개만 만든다(기존 표·데이터 그대로,
|
||||
다시 실행 가능). 005·006 다음에 적용한다. 미적용이면 실적 설정 → 광고 API 연동 카드에 안내가 나오고 저장이 503, 광고비 탭은 그대로.
|
||||
새 환경변수 없음 — 인증정보는 설정 화면에서 입력하고 기존 `APP_ENCRYPTION_KEY` 로 암호화된다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_007_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_007_ad_api.sql
|
||||
docker exec postgres-db psql -U postgres -d performance_db -c "\dt perf_ad_*"
|
||||
```
|
||||
|
||||
되돌리기(광고 API 인증정보·상태만 사라짐, 가져온 광고비는 perf_ad_spend 에 남음):
|
||||
`docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_source_status, perf_ad_credentials;"`
|
||||
|
||||
## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026)
|
||||
|
||||
026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내.
|
||||
|
||||
+12
-2
@@ -50,8 +50,18 @@
|
||||
|
||||
아직 긴급 공지를 띄우지 않는다(웹만). 붙이려면 `desktop/notifier` 에 공지 창(가운데)·[확인] 호출을 추가하고 exe 를 다시 빌드해야 한다.
|
||||
|
||||
## 내용 버전 · 확인 조건 (2026-10-15 검토 F07·F08)
|
||||
|
||||
- 공지마다 `version`(= `updated_at` 마이크로초, 고치기·취소 때마다 바뀜)을 받는 사람 화면(`/notice/api/pending`)에 보낸다.
|
||||
열린 공지의 버전이 바뀌면 다음 확인(30초) 때 바뀐 내용으로 다시 그리고 "수정되었습니다" 안내. reshow 는 확인 기록을 지워 다시 띄운다.
|
||||
- [확인] `POST /notice/api/{id}/ack {version}` — 저장소가 **한 트랜잭션**에서 공지 행을 `FOR SHARE` 로 잠그고 받는 사람·띄울 시각 지남·
|
||||
취소 안 됨을 본 뒤 기록(`ack()` → acked·already·stale·denied). 예약·취소·받는 사람 아님 = 404(기록 없음), 이미 확인 = 200(한 번만),
|
||||
읽은 version 이 지금과 다르면 409(기록 없음 — 화면이 바뀐 내용을 다시 보여 줌). 동시에 취소가 들어오면 그 쪽이 끝난 뒤 다시 판정한다.
|
||||
version 이 없는 요청(예전 화면 캐시)은 내용 확인만 건너뛴다.
|
||||
|
||||
## 테스트
|
||||
|
||||
- `tests/test_notice.py` — 본문 정리·이미지 형식·시각(한국시간)·받는 사람 검증, API 권한(수퍼관리자만 관리·받는 사람만 확인/이미지·503). DB 없음.
|
||||
- `tests/test_notice_db.py` — 실제 PostgreSQL(로컬 테스트 DB): 예약 시각·고른 사람·확인 한 번·취소/되돌리기·고치기·다시 띄우기·남의 이미지 안 묶임.
|
||||
- `tests/js/notice_ui.test.js` — jsdom: 가운데 창·차례대로·Esc/바깥 클릭 무시·확인 실패 유지·다른 곳 확인 반영·503 멈춤.
|
||||
- `tests/test_notice_db.py` — 실제 PostgreSQL(로컬 테스트 DB): 예약 시각·고른 사람·확인 한 번·취소/되돌리기·고치기·다시 띄우기·남의 이미지 안 묶임,
|
||||
예약·취소·비수신자 확인 거부, 고치기 전 버전 확인 stale, 동시 취소(행 잠금 대기 후 거부).
|
||||
- `tests/js/notice_ui.test.js` — jsdom: 가운데 창·차례대로·Esc/바깥 클릭 무시·확인 실패 유지·다른 곳 확인 반영·503 멈춤, 고친 공지 다시 그리기·확인에 버전·409.
|
||||
|
||||
@@ -336,6 +336,19 @@
|
||||
- 쇼핑몰 하나 실패 → 그 쇼핑몰만 상태 오류(`perf_connection_status`), 나머지 계속. 대시보드는 저장된 데이터로 계속 표시하고
|
||||
상단에 오류 쇼핑몰만 표시.
|
||||
- 중복 방지: `UNIQUE(marketplace_code, event_type, external_event_id)` + `ON CONFLICT DO UPDATE`.
|
||||
- **실패를 성공으로 만들지 않는다(2026-10-15 검토 F01·F05·F06, `docs/CODE_REVIEW_2026-10-15.md`)** — 기간을 통째로 교체(`replace_range`)하는
|
||||
쇼핑몰은 일부만 받은 목록으로 교체하면 매출이 지워진다:
|
||||
- 쿠팡: HTTP 200 이어도 JSON 이 아니거나 `data` 목록이 없으면 `ApiError`(정상 빈 목록 `data: []`·성공 표시가 있는 `data: null` 만 0건).
|
||||
- 쪽 넘김: 마지막 쪽을 확인하지 못하면(쪽 수 상한 소진·같은 커서 반복) 실패. 쿠팡은 `TooManyPages` → 조회 구간을 반으로(하루까지),
|
||||
하루도 넘치면 실패. 네이버·카카오·토스(주문·정산·클레임)·GS샵도 상한 소진·커서 반복이면 `ApiError`.
|
||||
- [중지]: `ShopProgress.begin_saving()` 이 중지 확인과 running → saving 전환을 한 잠금에서 — `collect()` 끝 무렵 받아들인 중지는
|
||||
저장하지 않고 "중지됨", 저장을 시작한 뒤의 중지는 409(중지 불가).
|
||||
- **인증정보가 바뀌면 이전 토큰을 쓰지 않는다(F04)**: 저장 때 화면 항목 값이 실제로 바뀌면 그 쇼핑몰의 내부 값(토큰·만료)을 지운다
|
||||
(같은 값 다시 저장은 그대로). 네이버·토스 토큰은 발급한 인증정보 지문(`access_token_for` = SHA-256, 원문 아님)과 지금 인증정보가
|
||||
같을 때만 다시 쓴다 — 저장하지 않은 연결 테스트 값에도 같은 기준. GS샵 토큰 방식 캐시도 (협력사코드, 운영 KEY 지문) 기준.
|
||||
배포 직후 지문이 없는 예전 토큰은 한 번 새로 받는다.
|
||||
- **연결 테스트 `clear`(F09)**: 쇼핑몰·광고 테스트 API 공통 — 요청 `{values, clear}`, 비운 칸(clear)은 저장값 대신 빈 값으로 시험,
|
||||
values·clear 중 하나라도 있으면 저장하지 않은 시험(`unsaved: true`) — 연결 상태·토큰을 저장하지 않는다(`router._cleared_keys`).
|
||||
|
||||
## 7. 화면
|
||||
|
||||
@@ -365,14 +378,38 @@
|
||||
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
|
||||
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
|
||||
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
|
||||
- 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력.
|
||||
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력.
|
||||
- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양,
|
||||
돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단).
|
||||
- **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로
|
||||
`perf_ad_credentials`(쇼핑몰 표는 `perf_marketplaces` 에 FK 로 묶여 있음), 암호문 AAD 이름 공간 `perf:ad:{채널}:{항목}`
|
||||
(`credentials.aad_for(…, ns)` — 쇼핑몰 암호문과 바꿔 넣어도 복호화 안 됨). 비밀 원문은 화면으로 다시 보내지 않음.
|
||||
[현재 키로 다시 암호화]·저장된 항목 수에 광고 인증정보도 포함. 연결 상태·마지막 가져오기는 `perf_ad_source_status`.
|
||||
- **구글 광고**(`ad_sources/google_ads.py`): 입력 = 고객 ID(광고 계정 10자리) ·
|
||||
로그인 고객 ID(MCC 를 거칠 때만) · 서비스 계정 키 JSON(비밀, 여러 줄) · API 버전(기본 `v26`, 구글이 종료 알리면 설정에서 올림).
|
||||
서비스 계정 이메일을 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다(도메인 위임 불필요, 2024-11~).
|
||||
**개발자 토큰은 2026-09-09 폐지**(구글) — 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙고
|
||||
Cloud Console → Google Ads API Overview 에서 신청. `developer-token` 머리글은 무시되며 다음 큰 버전부터 거부라 보내지 않는다(입력칸 없음).
|
||||
승인 없는 프로젝트 = `CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION`(안내 문구 붙음).
|
||||
토큰 = 서비스 계정 JWT(google-auth 서명) → `oauth2.googleapis.com/token`(httpx), 프로세스 안 캐시(만료 2분 전까지).
|
||||
조회 = REST `googleAds:searchStream` GAQL `FROM customer` + `segments.date BETWEEN`(계정 시간대), 요청 1번.
|
||||
금액 = `cost_micros ÷ 10⁶ × 1.1` 원 반올림 — **부가세 포함**(2026-10-15 사용자 요청, 쿠팡 청구금액과 같은 기준. 구글 비용 자체는 부가세 별도),
|
||||
ROAS = 전환 가치 ÷ 비용(부가세 별도) × 100(소수 둘째, 구글 화면 값 그대로), 항목에 광고비(부가세 포함)·비용(부가세 별도) 둘 다,
|
||||
항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
|
||||
통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내.
|
||||
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
|
||||
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
|
||||
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
|
||||
`POST /api/ad-sources/{code}/sync`) + **매출 자동 업데이트 회차**(같은 최근 N일, 매출 다음에, 실패해도 매출과 무관 — `auto_sync.run_once`).
|
||||
- API: `GET|PUT /api/ad-sources/{code}/credentials`·`POST /api/ad-sources/{code}/test`(관리자), `POST /api/ad-sources/{code}/sync`(모듈 권한).
|
||||
- 007 미적용: 설정 카드에 안내, 저장은 503(안내 문구), 광고비 탭은 그대로(불러오기 버튼만 안 보임).
|
||||
- **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…`
|
||||
기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행),
|
||||
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
|
||||
월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
|
||||
- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
|
||||
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), 마스터 키 상태·재암호화,
|
||||
테스트 데이터 생성/삭제(`is_sample`).
|
||||
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 —
|
||||
설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`).
|
||||
|
||||
## 8. 테스트
|
||||
|
||||
@@ -382,3 +419,5 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest
|
||||
|
||||
암호화(왕복·AAD·변조·키 교체), 가리기, 수수료 반올림·요율 이력, 기간/주 계산, 표·누적 합계, 인증정보 비노출·재암호화,
|
||||
동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
|
||||
`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키),
|
||||
광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증.
|
||||
|
||||
+23
-2
@@ -441,6 +441,10 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
**설명란 이미지 더블클릭 → 별도 브라우저 창**(`openImageWindow`, 페이지 안 팝업 아님) — 창 크기 = 원본 크기(화면보다 크면 95%),
|
||||
처음 원본 100%(창보다 크면 맞춤), 휠 = 커서 기준 확대·축소, 끌기 = 이동, 아래 막대 − / % / + · 1:1 · 맞춤, 더블클릭 = 원본↔맞춤,
|
||||
키 + − 0 1 Esc. 팝업이 막히면 허용 안내 토스트.
|
||||
**이미지 복사(2026-10-15)** — 설명란에서 고른 이미지 Ctrl+C, 보기 창 [복사]·Ctrl+C = 캔버스로 만든 **PNG 그림만** 클립보드에
|
||||
(`copyImageToClipboard`, `navigator.clipboard.write` + `ClipboardItem` 에 Promise). 브라우저 기본 복사는 `<img src=첨부 주소>` HTML 을
|
||||
넣는데 첨부 주소는 로그인해야 열려서 카카오톡·한글처럼 HTML 을 먼저 쓰는 프로그램엔 빈칸으로 붙었다(설명란 이미지 "선택"은 편집기 표시라
|
||||
기본 Ctrl+C 는 아무것도 복사하지 않았음). 글자를 드래그해 둔 Ctrl+C 는 그대로 글자 복사. 검증 `tests/js/image_copy.browser.test.js`.
|
||||
그 아래 메타(담당자·섹션·우선순위·마감일 한 줄 — 마감일은 캘린더 아이콘 버튼, 좁으면 2×2 | 협업자), 다시 그 아래 **설명란**과
|
||||
**하위 작업**가 각각 팝업 너비 전체를 쓰는 별도 행(`.pj-desc-block` / `.pj-subtask-full`,
|
||||
그리드 `1 / -1`). 하위 작업은 제목 왼쪽 체크박스로 완료를 토글하고, 완료된 줄은
|
||||
@@ -1341,13 +1345,30 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame
|
||||
|
||||
## 6-21. 수신함 머리 — 성공하기 창 · 아이콘 버튼 (2026-10-15, 마이그레이션 없음)
|
||||
|
||||
- **[성공하기]** — 수신함 제목 오른쪽 버튼. 모듈 폴더의 `app/modules/project/dbx.html` 을 `GET /project/dbx`(`dbx_page`,
|
||||
- **[성공하기]** — 왼쪽 사이드바 프로젝트 목록 위 버튼(처음엔 수신함 머리에 있었음). 모듈 폴더의 `app/modules/project/dbx.html` 을 `GET /project/dbx`(`dbx_page`,
|
||||
로그인·`project` 권한 = `_page_user`, DB 없이 파일 그대로)로 내주고, 화면은 `window.open(..., "pj-dbx", "popup=yes,…")` 별도 창으로 연다
|
||||
(같은 창 이름이라 여러 번 눌러도 창 하나). 창 안에는 맨 위 [닫기](`window.close()`) 버튼만 — 내용은 dbx.html 을 고치면 바로 반영(`no-cache`).
|
||||
- **[태그 모두 확인]·[알림 모두 읽음]** 은 글자 없이 아이콘만(`done_all`·`mark_email_read`, 말풍선 = `title`), [PC 알림] → **[PC 알림 프로그램 설치]**.
|
||||
- 수신함 제목은 머리 줄 **가로 정가운데·굵게**(`1fr | 제목 | 1fr` 격자, [성공하기]는 제목 오른쪽에 절대 배치라 제목 위치에 영향 없음).
|
||||
- 수신함 머리 줄 = **제목 가로 정가운데·굵게 | 버튼들 맨 오른쪽**(`1fr | 제목 | 1fr` 격자).
|
||||
- **[성공하기]는 왼쪽 사이드바 프로젝트 목록 바로 위**(`_side.html` `#pj-dbx-open`, 아이콘 21.6px = 120%) — 모든 Project 화면 공용, 창 여는 코드는 project.js(문서 단위 클릭 위임).
|
||||
- dbx.html: 첫 탭 제목 "DBX 존재이유 / 일하는 법", 탭 순서 = 존재이유·일을 잘한다는 것·일 못하는 사람 특징·부자/성공·마케팅?·인생을 결정하는 단 1가지(패널 id 는 그대로, 버튼 순서만), 강조는 `<b>`·형광 `<mark>`.
|
||||
- dbx.html 탭은 Project 뷰 탭처럼 고른 탭 뒤 옅은 보라 사각형(`.tab-hl`)이 미끄러져 옮겨 간다(두 줄로 접혀도 위아래까지).
|
||||
|
||||
## 6-22. 회의록 [적용] 한 트랜잭션 · 업무 등록 표 저장 실패 처리 (2026-10-15 검토 F02·F03, 마이그레이션 없음)
|
||||
|
||||
- **[적용](`POST /api/goals/meeting-quick-tasks/{id}/apply`)** — ① 잠그기 전에 줄을 읽어 작업 창과 같은 확인(`_task_create_checks`:
|
||||
멤버·담당자·협업자) ② `db.apply_meeting_task(task_fields, expect)` **한 연결·한 트랜잭션**: 줄 `FOR UPDATE` → 이미 업무가 있으면 그대로(200)
|
||||
→ 확인에 쓴 줄 값(`MT_APPLY_KEYS`)이 그사이 바뀌었으면 409 → 상위 업무가 같은 프로젝트에 있는지 → `_insert_task(conn)`(업무 INSERT·이력,
|
||||
`create_task` 와 같은 본문) → 줄에 `task_id`. 연결 기록이 실패하면 업무도 롤백(고아·재시도 중복 없음), 동시 클릭에도 업무 하나,
|
||||
트랜잭션 안에서 같은 풀의 다른 연결을 빌리지 않는다(풀 1개로도 동작) ③ **커밋 뒤에만** 협업자·배정/완료 알림·관리자 메일(`_task_created_effects`).
|
||||
예전엔 줄을 잠근 연결을 쥔 채 `create_task` 가 다른 연결에서 업무를 만들어 커밋했다.
|
||||
- **업무 등록 표 저장**(`initMeetQuickTasks`) — 줄마다 저장 안 된 칸(`r.unsaved`)을 기억. `persist()` 는 실패하면 거부되는 약속을 돌려주고
|
||||
(예전엔 실패를 삼켜 [적용]이 이전 제목으로 업무를 만들었다), [적용]은 `saveRow()`(치던 제목 보내기 → 앞선 저장 기다림 → 실패한 칸 다시
|
||||
저장)가 끝까지 성공해야 보낸다. 실패한 초안은 그대로 두고 줄 빨간 테두리 + [다시 저장](`data-quick="retry"`), 자동·강제 새로고침도 초안을
|
||||
지우지 않으며(이미 [적용]된 줄·409 만 서버 값), 저장 안 된 입력이 있으면 페이지 이탈 경고(`beforeunload`).
|
||||
- 검증: `tests/test_project_module.py::test_review_meeting_apply_is_one_transaction`(실제 PostgreSQL — 테스트 전용 트리거로 연결 실패 주입,
|
||||
풀 1개, 줄 바뀜 409), 기존 `test_review_meeting_quick_tasks_shared`(동시 4건), `tests/js/goals_meeting_ui.test.js` [2g9].
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# 테스트 실행 방법
|
||||
|
||||
운영 서버·운영 DB·실제 쇼핑몰은 쓰지 않는다. DB 통합 테스트는 **localhost 의 테스트용 PostgreSQL** 일 때만 돈다
|
||||
(`*_TEST_DB_URL` 호스트가 localhost/127.0.0.1 이 아니면 건너뜀). 메일·쇼핑몰 API 는 가짜다.
|
||||
|
||||
## 1. Python (pytest)
|
||||
|
||||
```bash
|
||||
python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||
python -m pytest -q # pytest.ini 의 testpaths 전부
|
||||
```
|
||||
|
||||
- DB 가 없으면 `tests/test_project_module.py`·`tests/test_cafe24_db.py`·`tests/test_notice_db.py` 는 **skip** 으로 나온다
|
||||
(실패가 아니다 — 2026-10-15 검토 F10 전에는 NameError 로 실패했다).
|
||||
- 파일별 직접 실행도 그대로 된다: `python tests/test_project_module.py`, `python -m app.modules.cafe24.tests.test_cafe24`.
|
||||
- `.env` 는 테스트에 필요 없다. `DATA_DIR` 을 저장소 밖 임시 폴더로 주면 사용자 JSON 등이 저장소에 생기지 않는다.
|
||||
|
||||
## 2. DB 통합 테스트(로컬 PostgreSQL)
|
||||
|
||||
저장소의 SQL 그대로 로컬 테스트 DB 를 만든다(운영 명령 아님).
|
||||
|
||||
```bash
|
||||
# 예: 로컬 PostgreSQL 16 이 localhost:55432 에 postgres 사용자(trust)로 떠 있을 때
|
||||
export PGCLIENTENCODING=UTF8
|
||||
for db in project cafe24; do
|
||||
psql -h localhost -p 55432 -U postgres -d postgres -v app_password=localtest -f scripts/sql/${db}_db_init.sql
|
||||
for f in $(ls scripts/sql | grep "^${db}_db_0" | sort); do
|
||||
psql -h localhost -p 55432 -U postgres -d ${db}_db -v ON_ERROR_STOP=1 -f scripts/sql/$f
|
||||
done
|
||||
done
|
||||
PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \
|
||||
CAFE24_TEST_DB_URL=postgresql://postgres@localhost:55432/cafe24_db \
|
||||
python -m pytest -q tests/test_project_module.py tests/test_cafe24_db.py tests/test_notice_db.py
|
||||
```
|
||||
|
||||
- project_db 008 은 `pg_trgm`(contrib 확장)이 필요하다. 확장이 없는 휴대용 PostgreSQL 이면 008 의 trgm 확장·인덱스 줄만 빼고
|
||||
적용해도 테스트 동작은 같다(검색 속도용 인덱스뿐 — 앱 쿼리는 ILIKE).
|
||||
- 같은 DB 로 여러 번 돌려도 된다(테스트마다 새 이름·번호). 깨끗하게 하려면 위 스크립트로 DB 를 다시 만든다.
|
||||
- 여기서 실제로 검증하는 것: 트랜잭션 롤백(회의록 [적용] 연결 실패 시 업무도 롤백 — 테스트 전용 트리거), 동시 [적용] 4건,
|
||||
풀 연결 1개로 [적용], 공지 확인과 동시 취소(행 잠금 대기), 카페24 lease·쓰기 잠금 등.
|
||||
|
||||
## 3. 화면(jsdom) 테스트
|
||||
|
||||
```bash
|
||||
cd tests/js && npm install && cd ../.. # jsdom·playwright-core(package.json 고정 버전)
|
||||
python tests/js/render_project.py # 템플릿 → tests/js/.out/*.html
|
||||
python tests/js/render_goals.py
|
||||
python tests/js/render_performance.py
|
||||
python tests/js/render_help.py
|
||||
for t in project_ui goals_meeting_ui goal_nav_ui overdue_ui notice_ui perf_manual help_ui; do node tests/js/$t.test.js; done
|
||||
```
|
||||
|
||||
마지막 줄 `ALL PASS` 면 통과. 서버 응답은 테스트 안의 가짜 fetch 다.
|
||||
|
||||
## 4. 실제 브라우저 테스트(Playwright)
|
||||
|
||||
```bash
|
||||
PJ_TEST_BROWSER="C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" node tests/js/image_copy.browser.test.js
|
||||
```
|
||||
|
||||
`*.browser.test.js` — 설치된 Chrome/Edge 경로를 `PJ_TEST_BROWSER` 로 준다(playwright-core 는 브라우저를 내려받지 않음).
|
||||
렌더된 `.out` 페이지와 테스트 안의 가짜 서버를 쓴다.
|
||||
|
||||
## 5. 남은 한계
|
||||
|
||||
- 실제 쇼핑몰·Google Ads·SMTP 와의 통신은 테스트하지 않는다(가짜 응답). 응답 형식 가정이 바뀌면 운영에서 확인이 필요하다.
|
||||
- 운영 PostgreSQL 과 같은 설정(확장·권한·부하)에서의 동시성은 로컬 단일 인스턴스 결과로 대신한다.
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
; 저장소 전체 pytest 진입점(2026-10-15 검토 F10) — 실행 방법은 docs/TESTING.md.
|
||||
; python -m pytest → 아래 경로 전부. DB 통합 테스트(tests/test_project_module.py·test_cafe24_db.py·test_notice_db.py)는
|
||||
; *_TEST_DB_URL(localhost)이 없으면 명시적으로 skip 된다(운영 DB 보호).
|
||||
[pytest]
|
||||
testpaths =
|
||||
tests
|
||||
app/modules/performance/tests
|
||||
app/modules/cafe24/tests
|
||||
app/modules/dispatch/tests
|
||||
cache_dir = .pytest_cache
|
||||
@@ -0,0 +1,4 @@
|
||||
# 테스트 전용 의존성(운영 이미지에는 넣지 않음) — docs/TESTING.md
|
||||
# python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||
# 2026-10-15 검증 조합: Python 3.12 + pytest 9.1.1
|
||||
pytest==9.1.1
|
||||
@@ -0,0 +1,53 @@
|
||||
-- =====================================================================
|
||||
-- performance_db 마이그레이션 007 — 광고 API 연동(구글 광고) 인증정보·연결 상태
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 새 표 두 개만 만든다(기존 표·데이터 그대로). 005·006 다음에 적용.
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \
|
||||
-- < scripts/sql/performance_db_007_ad_api.sql
|
||||
--
|
||||
-- 왜(2026-10-15 사용자 요청): 광고비 탭에 구글 광고비·ROAS 를 Google Ads API 로 가져온다.
|
||||
-- 인증정보(개발자 토큰·서비스 계정 키 등)는 실적 설정 화면에서 입력 → 쇼핑몰 인증정보와 같은 마스터 키
|
||||
-- (APP_ENCRYPTION_KEY, AES-256-GCM)로 암호화해 저장한다. 쇼핑몰 인증정보 표(perf_credentials)는
|
||||
-- 쇼핑몰 목록(perf_marketplaces)에 묶여 있어 광고 채널용 표를 따로 둔다.
|
||||
-- 가져온 광고비·ROAS 는 기존 perf_ad_spend 에 source='api' 로 들어간다(005 에 이미 허용된 값).
|
||||
-- 되돌리기: DROP TABLE perf_ad_source_status, perf_ad_credentials; (광고 API 인증정보·상태만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS perf_ad_credentials (
|
||||
channel_code TEXT NOT NULL,
|
||||
credential_key TEXT NOT NULL,
|
||||
encrypted_value TEXT NOT NULL,
|
||||
key_version INTEGER NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (channel_code, credential_key)
|
||||
);
|
||||
COMMENT ON TABLE perf_ad_credentials IS '광고 API 인증정보(암호문만) — 채널(google 등) × 항목. 원문은 서버 안에서만 복호화';
|
||||
DROP TRIGGER IF EXISTS trg_perf_ad_credentials_updated ON perf_ad_credentials;
|
||||
CREATE TRIGGER trg_perf_ad_credentials_updated
|
||||
BEFORE UPDATE ON perf_ad_credentials
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
CREATE TABLE IF NOT EXISTS perf_ad_source_status (
|
||||
channel_code TEXT PRIMARY KEY,
|
||||
status TEXT NOT NULL DEFAULT 'unknown',
|
||||
last_test_at TIMESTAMPTZ,
|
||||
last_test_ok BOOLEAN,
|
||||
last_sync_at TIMESTAMPTZ,
|
||||
last_success_sync_at TIMESTAMPTZ,
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
last_error_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE perf_ad_source_status IS '광고 API 연결 상태 — 마지막 연결 테스트·가져오기·오류(비밀값 가린 문구)';
|
||||
DROP TRIGGER IF EXISTS trg_perf_ad_source_status_updated ON perf_ad_source_status;
|
||||
CREATE TRIGGER trg_perf_ad_source_status_updated
|
||||
BEFORE UPDATE ON perf_ad_source_status
|
||||
FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_credentials, perf_ad_source_status TO performance_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'performance_db 007 ad api ready' AS status;
|
||||
@@ -81,3 +81,13 @@ node tests/js/project_ui.test.js # jsdom
|
||||
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉트 뒤 embed·저장 실패 확인창·A→B→A·iframe 안 Esc·읽음 실패
|
||||
```
|
||||
|
||||
# 설명란 이미지 복사 (Playwright, 2026-10-15)
|
||||
|
||||
설명란 이미지 Ctrl+C · 이미지 보기 창 [복사]·Ctrl+C 가 클립보드에 **PNG 그림만**(첨부 주소 HTML 없이, 원본 크기) 넣는지,
|
||||
글자를 골라 둔 Ctrl+C 는 그대로 글자 복사인지 실제 Chromium/Edge 로 확인한다. 가짜 서버, 운영 DB 연결 없음.
|
||||
|
||||
```bash
|
||||
python tests/js/render_project.py # → tests/js/.out/project_render.html
|
||||
NODE_PATH=<playwright 또는 playwright-core 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/image_copy.browser.test.js
|
||||
```
|
||||
|
||||
@@ -667,6 +667,46 @@ function meetServer(env, st) {
|
||||
check("[2g2] 직원(User)에겐 '새 프로젝트' 없음(새 프로젝트는 Pro user 이상)", labels.indexOf("새 프로젝트") < 0 && labels.indexOf("브랜드") >= 0, labels);
|
||||
});
|
||||
|
||||
// ════════════════════ [2g9] 2026-10-15 검토 F03 — 제목 저장이 실패하면 [적용]을 멈춘다(이전 제목으로 업무가 생기지 않게) ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
const q = quickServer(env, { rows: [{ id: 41, title: "OLD SAVED TITLE", project_id: 7, project_name: "브랜드", stage_id: 71, stage_name: "할 일" }] });
|
||||
let failPut = true;
|
||||
env.route("PUT", /\/meeting-quick-tasks\/(\d+)$/, function (u, b) {
|
||||
if (failPut) return { status: 500, body: { detail: "서버 오류" } };
|
||||
const r = q.rows[+/(\d+)$/.exec(u)[1]];
|
||||
Object.assign(r, b);
|
||||
return { body: { task: { id: r.id, title: r.title, project_id: r.project_id, stage_id: r.stage_id, task_id: null, registered: false } } };
|
||||
});
|
||||
await boot(env); await settle(); await wait(5); await settle();
|
||||
const d = env.d;
|
||||
const tr = function () { return Array.from(d.querySelectorAll("#pj-meet-quick tbody tr")).find(function (x) {
|
||||
const i = x.querySelector('input[data-field="title"]'); return i && /TITLE/.test(i.value); }); };
|
||||
const inp = tr().querySelector('input[data-field="title"]');
|
||||
inp.value = "NEW UNSAVED TITLE"; inp.dispatchEvent(new env.w.Event("input", { bubbles: true }));
|
||||
tr().querySelector('[data-quick="apply"]').click(); // 치자마자 [적용] — 제목 저장(PUT)이 500
|
||||
await settle(); await wait(5); await settle();
|
||||
check("[2g9] 제목 저장 실패 → [적용] 요청을 보내지 않음(이전 제목으로 업무 안 생김)", q.applied.length === 0, q.applied);
|
||||
check("[2g9] 실패한 초안은 그대로(입력칸 NEW UNSAVED TITLE) + 저장 실패 표시·다시 저장 버튼",
|
||||
!!tr() && tr().querySelector('input[data-field="title"]').value === "NEW UNSAVED TITLE" &&
|
||||
tr().classList.contains("is-unsaved") && !!tr().querySelector('[data-quick="retry"]'), tr() && tr().outerHTML.slice(0, 300));
|
||||
check("[2g9] 저장 안 된 입력이 있으면 페이지 이탈 경고", (function () {
|
||||
const ev = new env.w.Event("beforeunload", { cancelable: true });
|
||||
env.w.dispatchEvent(ev);
|
||||
return ev.defaultPrevented;
|
||||
})());
|
||||
await env.w.__pjMeetQuick.load(true); await settle();
|
||||
check("[2g9] 새로 읽어도(강제) 초안을 지우지 않음", !!tr() && tr().querySelector('input[data-field="title"]').value === "NEW UNSAVED TITLE");
|
||||
// 서버가 돌아오면 [다시 저장] → 저장, 그 뒤 [적용]은 새 제목으로
|
||||
failPut = false;
|
||||
tr().querySelector('[data-quick="retry"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g9] [다시 저장] → 서버 줄이 새 제목", q.rows[41].title === "NEW UNSAVED TITLE" && !tr().classList.contains("is-unsaved"), q.rows[41]);
|
||||
check("[2g9] 저장되면 이탈 경고 없음", !env.w.__pjMeetQuick.hasUnsaved());
|
||||
tr().querySelector('[data-quick="apply"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g9] 저장 뒤 [적용] → 새 제목으로 한 번", q.applied.length === 1 && q.applied[0].title === "NEW UNSAVED TITLE", q.applied);
|
||||
});
|
||||
|
||||
// ════════════════════ [2g3] 작업 등록 = 주차별 서버 표 · 다른 사람 줄도 보임 · 제목 "N주차 작업 등록" · 브라우저 예전 표는 서버로 ════════════════════
|
||||
await section(async function () {
|
||||
// 제목 — 입력칸(등록 전) 또는 등록된 줄의 제목 버튼·글자
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// 실제 브라우저 — 설명란 이미지 복사(2026-10-15). 클립보드에 PNG 그림만(첨부 주소 HTML 없이) 들어가는지:
|
||||
// ① 설명란 이미지를 눌러 고른 뒤 Ctrl+C ② 더블클릭 이미지 보기 창의 [복사] 버튼 ③ 그 창에서 Ctrl+C.
|
||||
// 원본이 JPEG 여도 PNG 로 바뀌고 크기는 원본 그대로인지도 본다. 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome/Edge 경로> node tests/js/image_copy.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
let chromium;
|
||||
try { ({ chromium } = require("playwright")); } catch (_) { ({ chromium } = require("playwright-core")); }
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
const IMG = path.join(STATIC, "dbx/inline.jpg"); // JPEG 777×832 — PNG 로 바뀌어야 한다
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
|
||||
if (url.pathname === "/project/api/attachments/7/inline") { res.setHeader("Content-Type", "image/jpeg"); res.end(fs.readFileSync(IMG)); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") {
|
||||
return json(200, { task: { id: +task[1], title: "이미지 작업", project_id: 1, stage_id: 11, priority: "normal", assignee_email: "",
|
||||
description: '<p>글자</p><p><img src="/project/api/attachments/7/inline" alt="외벽" width="300"></p>',
|
||||
subtasks: [], links: [], followers: [], access: "full", completed_at: null } });
|
||||
}
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
// 클립보드 내용 — 형식 목록과 PNG 크기(그림으로 다시 읽어 본다)
|
||||
async function readClipboard(page) {
|
||||
return page.evaluate(async () => {
|
||||
const items = await navigator.clipboard.read();
|
||||
const types = items.flatMap(i => i.types);
|
||||
let w = 0, h = 0;
|
||||
if (types.includes("image/png")) {
|
||||
const bmp = await createImageBitmap(await items[0].getType("image/png"));
|
||||
w = bmp.width; h = bmp.height;
|
||||
}
|
||||
return { types, w, h };
|
||||
});
|
||||
}
|
||||
// 복사는 비동기(PNG 변환) — 클립보드에 그림이 들어올 때까지 기다린다(최대 5초)
|
||||
async function waitClipPng(page) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if ((await readClipboard(page)).types.includes("image/png")) return;
|
||||
await page.waitForTimeout(100);
|
||||
}
|
||||
}
|
||||
async function clearClipboard(page) {
|
||||
await page.evaluate(() => navigator.clipboard.writeText("비움"));
|
||||
}
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const context = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: base });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", e => errors.push(String(e)));
|
||||
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); console.log("PASS " + name); };
|
||||
try {
|
||||
await page.goto(base + "/project/p/1?task=1");
|
||||
await page.waitForFunction(() => { const i = document.querySelector("#pj-t-desc img"); return i && i.complete && i.naturalWidth > 0; });
|
||||
const img = page.locator("#pj-t-desc img");
|
||||
|
||||
// ① 설명란: 이미지 고르기 → Ctrl+C
|
||||
await clearClipboard(page);
|
||||
await img.click();
|
||||
ok("이미지를 누르면 고른 표시", await img.evaluate(n => n.classList.contains("pj-img-selected")));
|
||||
await page.keyboard.press("Control+c");
|
||||
await waitClipPng(page);
|
||||
let clip = await readClipboard(page);
|
||||
ok("설명란 Ctrl+C = PNG 그림만(첨부 주소 HTML 없음)", clip.types.length === 1 && clip.types[0] === "image/png", clip);
|
||||
ok("원본 크기 그대로(화면 표시 폭 300 이 아니라 777×832)", clip.w === 777 && clip.h === 832, clip);
|
||||
ok("복사 알림", /이미지를 복사했습니다/.test(await page.locator(".erp-toast").textContent()));
|
||||
|
||||
// 글자를 드래그해 둔 상태면 글자 복사 그대로(이미지로 가로채지 않음)
|
||||
await clearClipboard(page);
|
||||
await page.evaluate(() => {
|
||||
const p = document.querySelector("#pj-t-desc p"), r = document.createRange();
|
||||
r.selectNodeContents(p); const s = getSelection(); s.removeAllRanges(); s.addRange(r);
|
||||
});
|
||||
await page.keyboard.press("Control+c");
|
||||
await page.waitForTimeout(300);
|
||||
clip = await readClipboard(page);
|
||||
ok("글자를 골라 둔 Ctrl+C 는 브라우저 기본 복사(이미지 아님)", !clip.types.includes("image/png"), clip);
|
||||
|
||||
// ② 이미지 보기 창 [복사] ③ 그 창 Ctrl+C
|
||||
await page.evaluate(() => getSelection().removeAllRanges());
|
||||
const [popup] = await Promise.all([page.waitForEvent("popup"), img.dblclick()]);
|
||||
await popup.waitForFunction(() => { const i = document.getElementById("img"); return i && i.naturalWidth > 0; });
|
||||
await clearClipboard(page);
|
||||
await popup.click("#copy");
|
||||
await popup.waitForFunction(() => document.getElementById("msg").classList.contains("show"));
|
||||
clip = await readClipboard(page);
|
||||
ok("보기 창 [복사] = PNG 그림만, 원본 크기", clip.types.join() === "image/png" && clip.w === 777 && clip.h === 832, clip);
|
||||
ok("보기 창 복사 알림", /이미지를 복사했습니다/.test(await popup.locator("#msg").textContent()));
|
||||
|
||||
await clearClipboard(page);
|
||||
await popup.keyboard.press("Control+c");
|
||||
await waitClipPng(page);
|
||||
clip = await readClipboard(page);
|
||||
ok("보기 창 Ctrl+C = PNG 그림만", clip.types.join() === "image/png", clip);
|
||||
|
||||
ok("페이지 스크립트 오류 없음", errors.length === 0, errors);
|
||||
console.log("ALL PASS");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch(e => { console.error("FAIL " + e.message); process.exit(1); });
|
||||
@@ -24,7 +24,13 @@ function env(opts) {
|
||||
}
|
||||
const m = /^\/notice\/api\/(\d+)\/ack$/.exec(url);
|
||||
if (m) {
|
||||
const sent = (o && o.body) ? JSON.parse(o.body) : {};
|
||||
(e.ackBodies = e.ackBodies || []).push(sent);
|
||||
if (e.ackStatus >= 400) return { ok: false, status: e.ackStatus, json: async function () { return {}; } };
|
||||
const now = e.pending.find(function (n) { return String(n.id) === m[1]; });
|
||||
if (now && sent.version && now.version && sent.version !== now.version) { // 서버 계약: 읽은 내용이 지금과 다르면 409
|
||||
return { ok: false, status: 409, json: async function () { return { detail: "공지 내용이 수정되었습니다." }; } };
|
||||
}
|
||||
e.pending = e.pending.filter(function (n) { return String(n.id) !== m[1]; });
|
||||
return { ok: true, status: 200, json: async function () { return { ok: true }; } };
|
||||
}
|
||||
@@ -63,6 +69,27 @@ function env(opts) {
|
||||
await e.w.__erpNotice.poll(); await settle();
|
||||
check("[공지] 다른 곳에서 확인·취소되면 닫힘", box.hidden);
|
||||
}
|
||||
{
|
||||
// 2026-10-15 검토 F07 — 띄운 공지가 고쳐지면 다시 그리고, [확인]은 읽은 버전으로. 고치기 전 내용으로 누르면(409) 기록 안 함
|
||||
const V = function (version, body) { return Object.assign(N(5, "정정 공지", body), { version: version }); };
|
||||
const e = env({ pending: [V("v1", "<p>VERSION ONE</p>")] });
|
||||
await settle();
|
||||
const box = e.d.querySelector(".erp-notice-backdrop");
|
||||
check("[공지 F07] 처음 내용", /VERSION ONE/.test(box.querySelector(".erp-notice-body").textContent) &&
|
||||
box.querySelector(".erp-notice-updated").hidden);
|
||||
e.pending = [V("v2", "<p>VERSION TWO</p>")];
|
||||
await e.w.__erpNotice.poll(); await settle();
|
||||
check("[공지 F07] 같은 공지가 고쳐지면 열린 창을 바뀐 내용으로 + 수정됨 안내",
|
||||
/VERSION TWO/.test(box.querySelector(".erp-notice-body").textContent) && !box.querySelector(".erp-notice-updated").hidden);
|
||||
// 창이 VERSION TWO 를 보여 주는 동안 서버가 다시 고침(v3) — 읽은 v2 로 누르면 409, 기록 안 하고 v3 를 다시 보여 줌
|
||||
e.pending = [V("v3", "<p>VERSION THREE</p>")];
|
||||
box.querySelector(".erp-notice-ok").click(); await settle(); await settle();
|
||||
check("[공지 F07] [확인]에 읽은 버전(v2)을 보냄 → 409 면 닫지 않고 바뀐 내용(v3)·안내",
|
||||
e.ackBodies[0].version === "v2" && !box.hidden && /VERSION THREE/.test(box.querySelector(".erp-notice-body").textContent) &&
|
||||
!box.querySelector(".erp-notice-updated").hidden && e.pending.length === 1, e.ackBodies);
|
||||
box.querySelector(".erp-notice-ok").click(); await settle();
|
||||
check("[공지 F07] 바뀐 내용을 읽고 누르면 기록·닫힘", e.ackBodies[1].version === "v3" && box.hidden && e.pending.length === 0, e.ackBodies);
|
||||
}
|
||||
{
|
||||
const e = env({ pending: [], status: 503 });
|
||||
await settle();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "main-app-ui-tests",
|
||||
"private": true,
|
||||
"description": "UI 테스트 전용(jsdom·실제 브라우저) — 운영 앱과 무관. 실행 방법은 docs/TESTING.md",
|
||||
"devDependencies": {
|
||||
"jsdom": "24.1.3",
|
||||
"playwright-core": "1.48.2"
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,11 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
!up.classList.contains("is-manual") && man.classList.contains("is-manual") && gross(up) === "220,000");
|
||||
check("[광고비] 앞으로의 날은 입력 칸 아님", !cell(e, "google", "2026-10-08") && !!cell(e, "google", "2026-10-07"));
|
||||
const kpi = Array.from(e.d.querySelectorAll(".perf-kpi-value")).map(function (n) { return n.textContent.trim(); });
|
||||
check("[광고비] KPI — 이번달 광고비 599,000(네이버 300,000 포함) · 매출 대비 비율", kpi[0] === "₩599,000" && /%$/.test(kpi[1]), kpi);
|
||||
// 렌더 데이터(render_performance.py)에 구글 광고 API 값 10/04 123,457 이 더해졌다(2026-10-15 구글 광고 API 연동)
|
||||
check("[광고비] KPI — 이번달 광고비 722,457(네이버 300,000·구글 API 123,457 포함) · 매출 대비 비율", kpi[0] === "₩722,457" && /%$/.test(kpi[1]), kpi);
|
||||
const api = cell(e, "google", "2026-10-04");
|
||||
check("[광고비] 광고 API 값 = 초록(is-api) — 직접 입력·업로드 표시와 구분, 구글 ROAS(500%)", api.classList.contains("is-api") &&
|
||||
!api.classList.contains("is-manual") && !api.classList.contains("is-upload") && api.textContent.trim() === "123,457(500%)", api.className + " " + api.textContent);
|
||||
wing.click();
|
||||
const wi = wing.querySelector(".perf-manual-input");
|
||||
wi.value = "30000";
|
||||
@@ -219,7 +223,9 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
const nv = cell(e, "naver", "2026-10-03");
|
||||
check("[네이버] 칸 = 광고비(보고서 ROAS 반올림)", nv.textContent.trim() === "300,000(251%)", nv.textContent);
|
||||
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
|
||||
check("[네이버] 머리글 = 상세 보기 버튼(다른 채널은 아님)", !!hb && e.d.querySelectorAll(".perf-main thead [data-detail-channel]").length === 1);
|
||||
const detailChans = Array.from(e.d.querySelectorAll(".perf-main thead [data-detail-channel]")).map(function (b) { return b.dataset.detailChannel; });
|
||||
// 구글도 광고 API 로 가져온 보고서 항목이 있어 상세 보기(2026-10-15) — 그 밖의 채널은 아님
|
||||
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글만)", !!hb && detailChans.sort().join(",") === "google,naver", detailChans);
|
||||
hb.click(); await settle();
|
||||
const call = e.calls.find(function (c) { return /\/details/.test(c.url); });
|
||||
check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);
|
||||
@@ -233,10 +239,14 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
// ── 설정: 수동 입력 토글 ──
|
||||
{
|
||||
const e = await env("perf_settings.html");
|
||||
const heads = Array.from(e.d.querySelectorAll(".perf-set-table thead th")).map(function (th) { return th.textContent.trim(); });
|
||||
// 쇼핑몰 표만(아래 "광고 API 연동" 표도 같은 표 모양 — 2026-10-15)
|
||||
const SHOP = ".perf-card:not(#perf-ad-sources) .perf-set-table";
|
||||
const heads = Array.from(e.d.querySelectorAll(SHOP + " thead th")).map(function (th) { return th.textContent.trim(); });
|
||||
check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads);
|
||||
const rows = Array.from(e.d.querySelectorAll(".perf-set-table tbody tr")).map(function (tr) { return tr.dataset.code; });
|
||||
const rows = Array.from(e.d.querySelectorAll(SHOP + " tbody tr")).map(function (tr) { return tr.dataset.code; });
|
||||
check("[설정] 쇼핑몰 순서 = 어댑터 등록 순서(003 열 순서)", rows.join(",") === "cafe24,naver,coupang,ohouse,gmarket,kakao,gsshop,elevenst,lotteon,toss", rows);
|
||||
const adRows = Array.from(e.d.querySelectorAll("#perf-ad-sources tbody tr")).map(function (tr) { return tr.dataset.code + ":" + tr.dataset.api; });
|
||||
check("[설정] 광고 API 연동 표는 따로(구글 광고, /api/ad-sources/)", adRows.join(",") === "google:ad-sources", adRows);
|
||||
const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]');
|
||||
check("[설정] 켜진 쇼핑몰은 체크", box && box.checked && !e.d.querySelector('tr[data-code="cafe24"] input[data-field="manual_input"]').checked);
|
||||
box.checked = false;
|
||||
|
||||
@@ -59,12 +59,13 @@ class FakeStore:
|
||||
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual"),
|
||||
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")}
|
||||
(date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload"),
|
||||
(date(2026, 10, 4), "google"): (123457, "api")} # 구글 광고 API 값(초록 숫자)
|
||||
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
|
||||
|
||||
def ad_roas(self, start, end):
|
||||
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5")}
|
||||
rows = {(date(2026, 10, 3), "naver"): Decimal("250.5"), (date(2026, 10, 4), "google"): Decimal("500")}
|
||||
return {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
|
||||
|
||||
@@ -86,10 +87,15 @@ def main() -> None:
|
||||
f.write(html)
|
||||
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
sales_codes=["cafe24", "coupang"])
|
||||
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
|
||||
html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx)
|
||||
with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0)
|
||||
sctx["ad_api_ready"] = True # 광고 API 연동 표(마이그레이션 007)
|
||||
sctx["ad_sources"] = [{"code": "google", "name": "구글 광고", "configured": True, "status": "ok", "status_label": "정상 연결",
|
||||
"last_test_at": "2026-10-15T10:00:00+09:00", "last_error": "", "last_error_at": None,
|
||||
"last_sync_at": "2026-10-15T10:30:02+09:00", "last_success_sync_at": "2026-10-15T10:30:02+09:00"}]
|
||||
html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
|
||||
+34
-1
@@ -71,7 +71,9 @@ if ENABLED:
|
||||
from app.modules.cafe24.tests import fakes # noqa: E402
|
||||
from app.timezone import now_kst # noqa: E402
|
||||
|
||||
products.time.sleep = lambda *_a, **_k: None
|
||||
# 카페24 쓰기 직후 읽기 지연 재시도의 실제 sleep 을 건너뛴다 — time 은 공유 모듈이라 import 때 바꾸지 않고
|
||||
# 이 파일 테스트 동안만(pytest fixture / 직접 실행은 _run_all) 바꾼다(검토 F10).
|
||||
_NO_SLEEP = lambda *_a, **_k: None # noqa: E731
|
||||
ST = Cafe24Store(DSN)
|
||||
ST2 = Cafe24Store(DSN) # 두 번째 "프로세스"(별도 연결 풀)
|
||||
|
||||
@@ -107,6 +109,36 @@ if ENABLED:
|
||||
APP.state.cafe24_store = ST
|
||||
CLIENT = TestClient(APP)
|
||||
|
||||
# ── pytest 실행 범위(2026-10-15 검토 F10) ─────────────────────────────────
|
||||
# DB 가 없으면 이 파일 전체를 명시적으로 skip(예전엔 import 준비만 건너뛰어 ST·ADMIN 등이 없어 NameError).
|
||||
# 가짜 app.main 은 이 파일 테스트 동안만 sys.modules 에 둔다 — pytest 는 모든 파일을 먼저 import 하므로 import 때 바꿔 끼우면
|
||||
# 다른 DB 테스트 파일(test_cafe24_db ↔ test_project_module)의 가짜가 서로 덮어써 사용자 조회가 틀렸다.
|
||||
# 직접 실행(python tests/…)은 위 import 때 설치한 가짜를 그대로 쓴다.
|
||||
try:
|
||||
import pytest
|
||||
except ImportError: # 직접 실행은 pytest 없이도 돈다
|
||||
pytest = None
|
||||
|
||||
if pytest is not None:
|
||||
pytestmark = pytest.mark.skipif(not ENABLED, reason="CAFE24_TEST_DB_URL(localhost) 미설정 — 실제 PostgreSQL 통합 테스트는 건너뜀")
|
||||
|
||||
@pytest.fixture(autouse=True, scope="module")
|
||||
def _own_app_main_and_sleep():
|
||||
if not ENABLED:
|
||||
yield
|
||||
return
|
||||
prev, prev_sleep = sys.modules.get("app.main"), products.time.sleep
|
||||
sys.modules["app.main"] = fake_main
|
||||
products.time.sleep = _NO_SLEEP
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
products.time.sleep = prev_sleep
|
||||
if prev is None:
|
||||
sys.modules.pop("app.main", None)
|
||||
else:
|
||||
sys.modules["app.main"] = prev
|
||||
|
||||
_BASE = random.randint(100_000, 900_000) * 10
|
||||
|
||||
|
||||
@@ -610,6 +642,7 @@ def _run_all() -> None:
|
||||
if not ENABLED:
|
||||
print("SKIP — CAFE24_TEST_DB_URL(localhost) 이 없어 건너뜁니다.")
|
||||
return
|
||||
products.time.sleep = _NO_SLEEP # 직접 실행 = 이 프로세스는 이 파일 테스트만
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
|
||||
@@ -175,24 +175,29 @@ def test_missing_bom_sets():
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def test_rack_cell_codes_count_and_format():
|
||||
codes = store.rack_cell_codes()
|
||||
# A/B 2면 × 3행 × 3열 × 2분할 = 36칸
|
||||
assert len(codes) == 36
|
||||
assert len(set(codes)) == 36
|
||||
# A/B 2면 × 3행 × 3열 × 2분할 = 36칸 + Side B 아래 바닥(Ground) 파렛트 6칸(G1~G6) = 42칸
|
||||
# (Ground 추가 후 기대값 갱신 — 2026-10-15 검토 F10)
|
||||
assert len(codes) == 42
|
||||
assert len(set(codes)) == 42
|
||||
assert "A3-1-1" in codes
|
||||
assert "B1-3-2" in codes
|
||||
# 그림과 동일: 첫 칸은 A면 3행 1열 1분할
|
||||
# 그림과 동일: 첫 칸은 A면 3행 1열 1분할, 랙 36칸 뒤에 바닥 G1~G6
|
||||
assert codes[0] == "A3-1-1"
|
||||
assert codes[36:] == ["G1", "G2", "G3", "G4", "G5", "G6"]
|
||||
|
||||
|
||||
def test_rack_layout_structure():
|
||||
layout = store.rack_layout()
|
||||
assert [s["side"] for s in layout] == ["A", "B"]
|
||||
assert [s["side"] for s in layout] == ["A", "B", "Ground"]
|
||||
side_a = layout[0]
|
||||
assert [r["row"] for r in side_a["rows"]] == [3, 2, 1]
|
||||
# 각 행 3열, 각 열 2분할
|
||||
first_row = side_a["rows"][0]
|
||||
assert len(first_row["cols"]) == 3
|
||||
assert first_row["cols"][0] == ["A3-1-1", "A3-1-2"]
|
||||
# 바닥(Ground) — 한 줄에 분할 없는 파렛트 6칸
|
||||
ground = layout[2]
|
||||
assert len(ground["rows"]) == 1 and ground["rows"][0]["cols"] == [["G1"], ["G2"], ["G3"], ["G4"], ["G5"], ["G6"]]
|
||||
|
||||
|
||||
def test_aggregate_rack_sums_units_times_boxes():
|
||||
|
||||
+18
-3
@@ -86,9 +86,16 @@ class FakeStore:
|
||||
def is_recipient(self, notice, email):
|
||||
return notice["to_all"] or email in notice["targets"]
|
||||
|
||||
def ack(self, notice_id, email):
|
||||
def ack(self, notice_id, email, version=None):
|
||||
"""저장소 계약(검토 F07·F08) — 받는 사람·표시 시각·취소·내용 버전은 저장소가 판단(실제 판단은 test_notice_db)."""
|
||||
n = self.notices.get(notice_id)
|
||||
if n is None or n["cancelled_at"] or not self.is_recipient(notice=n, email=email) \
|
||||
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST):
|
||||
return "denied"
|
||||
if version and version != n.get("version", ""):
|
||||
return "stale"
|
||||
self.acked.append((notice_id, email))
|
||||
return True
|
||||
return "acked"
|
||||
|
||||
def list_notices(self):
|
||||
return [{**n, "acks": {}} for n in self.notices.values()]
|
||||
@@ -138,10 +145,18 @@ class NoticeApiTests(unittest.TestCase):
|
||||
with self.as_(BOB):
|
||||
out = self.client.get("/notice/api/pending").json()["notices"]
|
||||
self.assertEqual(sorted(n["id"] for n in out), [1, 3]) # 시각 판단은 저장소(실제 DB 테스트)
|
||||
self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by"}) # 받는 사람 목록·확인 현황 없음
|
||||
# 받는 사람 목록·확인 현황 없음, 내용 버전(version)은 보낸다(고친 공지를 다시 그리게, 검토 F07)
|
||||
self.assertEqual(set(out[0]), {"id", "title", "body_html", "show_at", "created_by", "version"})
|
||||
self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 200)
|
||||
self.assertEqual(self.client.post("/notice/api/2/ack").status_code, 404) # 받는 사람 아님
|
||||
self.assertEqual(self.client.post("/notice/api/3/ack").status_code, 404) # 띄울 시각 전(예약) — 검토 F08
|
||||
self.assertEqual(self.client.post("/notice/api/99/ack").status_code, 404)
|
||||
self.st.notices[1]["version"] = "v2"
|
||||
r = self.client.post("/notice/api/1/ack", json={"version": "v1"}) # 고치기 전 내용을 읽고 누름
|
||||
self.assertEqual(r.status_code, 409)
|
||||
self.assertIn("수정", r.json()["detail"])
|
||||
self.st.notices[1]["cancelled_at"] = "2026-10-15T10:00+09:00"
|
||||
self.assertEqual(self.client.post("/notice/api/1/ack").status_code, 404) # 취소된 공지
|
||||
self.assertEqual(self.st.acked, [(1, "bob@test.local")])
|
||||
|
||||
def test_image_access(self):
|
||||
|
||||
+59
-2
@@ -49,8 +49,8 @@ class NoticeDbTests(unittest.TestCase):
|
||||
self.assertNotIn(some["id"], self.ids(b)) # 고른 사람만
|
||||
self.assertNotIn(later["id"], self.ids(a)) # 띄울 시각 전
|
||||
self.assertIn(later["id"], self.ids(a, now=now + timedelta(hours=3)))
|
||||
self.assertTrue(self.st.ack(notice_id=allp["id"], email=a))
|
||||
self.assertFalse(self.st.ack(notice_id=allp["id"], email=a)) # 두 번 눌러도 한 번
|
||||
self.assertEqual(self.st.ack(notice_id=allp["id"], email=a), "acked")
|
||||
self.assertEqual(self.st.ack(notice_id=allp["id"], email=a), "already") # 두 번 눌러도 한 번
|
||||
self.assertNotIn(allp["id"], self.ids(a))
|
||||
self.assertIn(allp["id"], self.ids(b))
|
||||
self.st.cancel_notice(notice_id=allp["id"], by=boss)
|
||||
@@ -70,6 +70,63 @@ class NoticeDbTests(unittest.TestCase):
|
||||
with self.assertRaises(KeyError):
|
||||
self.st.update_notice(notice_id=10 ** 12, title="x", body="", show_at="", to_all=True, targets=[], by=boss)
|
||||
|
||||
def test_ack_only_shown_uncancelled_for_recipients(self):
|
||||
"""2026-10-15 검토 F08 — 예약(띄울 시각 전)·취소·받는 사람 아님은 확인 기록을 남기지 않는다(같은 트랜잭션에서 판단)."""
|
||||
boss, a, b = self.em("boss"), self.em("a8"), self.em("b8")
|
||||
now = datetime.now(KST)
|
||||
later = self.st.create_notice(title="예약", body="", show_at=(now + timedelta(hours=2)).isoformat(),
|
||||
to_all=True, targets=[], by=boss)
|
||||
only_a = self.st.create_notice(title="a 만", body="", show_at="", to_all=False, targets=[a], by=boss)
|
||||
gone = self.st.create_notice(title="취소", body="", show_at="", to_all=True, targets=[], by=boss)
|
||||
self.st.cancel_notice(notice_id=gone["id"], by=boss)
|
||||
self.assertEqual(self.st.ack(notice_id=later["id"], email=a), "denied") # 미래 공지
|
||||
self.assertEqual(self.st.ack(notice_id=gone["id"], email=a), "denied") # 취소 공지
|
||||
self.assertEqual(self.st.ack(notice_id=only_a["id"], email=b), "denied") # 받는 사람 아님
|
||||
self.assertEqual(self.st.ack(notice_id=10 ** 12, email=a), "denied")
|
||||
acks = {n["id"]: n["acks"] for n in self.st.list_notices()}
|
||||
self.assertEqual((acks[later["id"]], acks[gone["id"]], acks[only_a["id"]]), ({}, {}, {}))
|
||||
# 표시 시각이 되면 확인 가능, 미리 확인해 두는 일은 없으니 그 시각에 pending 에 그대로 뜬다
|
||||
self.assertIn(later["id"], self.ids(a, now=now + timedelta(hours=3)))
|
||||
self.assertEqual(self.st.ack(notice_id=later["id"], email=a, now=now + timedelta(hours=3)), "acked")
|
||||
self.assertEqual(self.st.ack(notice_id=only_a["id"], email=a), "acked")
|
||||
|
||||
def test_ack_version_and_reshow(self):
|
||||
"""F07 — 읽은 내용(version)이 지금과 다르면 stale(기록 안 함), 같으면 기록. reshow 는 다시 띄운다."""
|
||||
boss, a = self.em("boss"), self.em("a7")
|
||||
n = self.st.create_notice(title="VERSION ONE", body="<p>1</p>", show_at="", to_all=True, targets=[], by=boss)
|
||||
v1 = next(x["version"] for x in self.st.pending_for(email=a) if x["id"] == n["id"])
|
||||
self.st.update_notice(notice_id=n["id"], title="VERSION TWO", body="<p>2</p>", show_at="", to_all=True, targets=[], by=boss)
|
||||
cur = next(x for x in self.st.pending_for(email=a) if x["id"] == n["id"])
|
||||
self.assertNotEqual(cur["version"], v1)
|
||||
self.assertEqual(cur["title"], "VERSION TWO")
|
||||
self.assertEqual(self.st.ack(notice_id=n["id"], email=a, version=v1), "stale") # 고치기 전 내용을 읽고 누름
|
||||
self.assertIn(n["id"], self.ids(a))
|
||||
self.assertEqual(self.st.ack(notice_id=n["id"], email=a, version=cur["version"]), "acked")
|
||||
self.assertNotIn(n["id"], self.ids(a))
|
||||
self.st.update_notice(notice_id=n["id"], title="VERSION THREE", body="", show_at="", to_all=True, targets=[], by=boss,
|
||||
reshow=True)
|
||||
self.assertIn(n["id"], self.ids(a)) # reshow — 확인한 사람에게도 다시
|
||||
|
||||
def test_ack_waits_for_concurrent_cancel(self):
|
||||
"""F08 — 다른 연결이 공지를 취소하는 중(커밋 전)이면 확인은 기다렸다가 취소된 행으로 다시 판단해 기록하지 않는다."""
|
||||
import threading
|
||||
|
||||
boss, a = self.em("boss"), self.em("ac")
|
||||
n = self.st.create_notice(title="곧 취소", body="", show_at="", to_all=True, targets=[], by=boss)
|
||||
out = {}
|
||||
with self.ps.pool.connection() as conn:
|
||||
conn.execute("BEGIN")
|
||||
conn.execute("UPDATE urgent_notices SET cancelled_at = now() WHERE id = %s", (n["id"],)) # 잠금 + 커밋 전
|
||||
th = threading.Thread(target=lambda: out.setdefault("r", self.st.ack(notice_id=n["id"], email=a)))
|
||||
th.start()
|
||||
th.join(1.0)
|
||||
self.assertTrue(th.is_alive()) # 행 잠금 때문에 기다린다
|
||||
conn.execute("COMMIT")
|
||||
th.join(10)
|
||||
self.assertEqual(out.get("r"), "denied")
|
||||
acks = next(x["acks"] for x in self.st.list_notices() if x["id"] == n["id"])
|
||||
self.assertEqual(acks, {})
|
||||
|
||||
def test_images_link_only_own_uploads(self):
|
||||
boss, other = self.em("boss"), self.em("other")
|
||||
mine = self.st.add_image(data=PNG, filename="a.png", by=boss)
|
||||
|
||||
@@ -98,6 +98,35 @@ if ENABLED:
|
||||
EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음
|
||||
|
||||
|
||||
# ── pytest 실행 범위(2026-10-15 검토 F10) ─────────────────────────────────
|
||||
# DB 가 없으면 이 파일 전체를 명시적으로 skip(예전엔 import 준비만 건너뛰어 ST·ADMIN 등이 없어 NameError).
|
||||
# 가짜 app.main 은 이 파일 테스트 동안만 sys.modules 에 둔다 — pytest 는 모든 파일을 먼저 import 하므로 import 때 바꿔 끼우면
|
||||
# 다른 DB 테스트 파일(test_cafe24_db ↔ test_project_module)의 가짜가 서로 덮어써 사용자 조회가 틀렸다.
|
||||
# 직접 실행(python tests/…)은 위 import 때 설치한 가짜를 그대로 쓴다.
|
||||
try:
|
||||
import pytest
|
||||
except ImportError: # 직접 실행은 pytest 없이도 돈다
|
||||
pytest = None
|
||||
|
||||
if pytest is not None:
|
||||
pytestmark = pytest.mark.skipif(not ENABLED, reason="PROJECT_TEST_DB_URL(localhost) 미설정 — 실제 PostgreSQL 통합 테스트는 건너뜀")
|
||||
|
||||
@pytest.fixture(autouse=True, scope="module")
|
||||
def _own_app_main():
|
||||
if not ENABLED:
|
||||
yield
|
||||
return
|
||||
prev = sys.modules.get("app.main")
|
||||
sys.modules["app.main"] = fake_main
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if prev is None:
|
||||
sys.modules.pop("app.main", None)
|
||||
else:
|
||||
sys.modules["app.main"] = prev
|
||||
|
||||
|
||||
def req(method: str, url: str, who: str, **kw):
|
||||
return CLIENT.request(method, url, headers={"x-test-user": who}, **kw)
|
||||
|
||||
@@ -1357,6 +1386,77 @@ def test_review_meeting_quick_parent_task_column():
|
||||
req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB)
|
||||
|
||||
|
||||
def test_review_meeting_apply_is_one_transaction():
|
||||
"""2026-10-15 검토 F02 — [적용]: 업무 INSERT 와 줄 연결(task_id)이 한 트랜잭션.
|
||||
줄 연결이 DB 에서 실패하면 만든 업무도 롤백(고아·재시도 중복 없음), 알림은 커밋 뒤에만,
|
||||
풀 연결 1개로도 동작(잠근 연결을 쥔 채 같은 풀의 두 번째 연결을 기다리지 않음)."""
|
||||
import time as _time
|
||||
|
||||
from app.modules.project import store
|
||||
|
||||
w = store.month_weeks(2032, 2)[1][0]
|
||||
_clear_quick(w)
|
||||
p = _project("P-apply-tx", ADMIN, (BOB, CAROL))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
url = f"/project/api/goals/meetings/{w}/quick-tasks"
|
||||
title = f"연결실패-{RUN}"
|
||||
row = req("POST", url, BOB, json={"title": title, "project_id": p["id"], "stage_id": s["id"],
|
||||
"assignee_email": CAROL}).json()["task"]
|
||||
apply = f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply"
|
||||
inbox = lambda: _count("SELECT COUNT(*) AS n FROM project_notifications WHERE title = %s", f"업무 배정: {title}") # noqa: E731
|
||||
# ① 줄 연결(UPDATE … SET task_id)을 DB 에서 실패시킨다 — 테스트 전용 트리거(로컬 테스트 DB 에서만)
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
conn.execute("CREATE OR REPLACE FUNCTION pj_test_fail_link() RETURNS trigger AS $$ BEGIN "
|
||||
"IF NEW.task_id IS NOT NULL AND NEW.title LIKE '연결실패-%' THEN RAISE EXCEPTION 'link failed (test)'; "
|
||||
"END IF; RETURN NEW; END $$ LANGUAGE plpgsql")
|
||||
conn.execute("DROP TRIGGER IF EXISTS pj_test_fail_link ON goal_meeting_tasks")
|
||||
conn.execute("CREATE TRIGGER pj_test_fail_link BEFORE UPDATE ON goal_meeting_tasks "
|
||||
"FOR EACH ROW EXECUTE FUNCTION pj_test_fail_link()")
|
||||
try:
|
||||
for _ in range(2): # 재시도해도 고아 업무가 쌓이지 않는다
|
||||
try:
|
||||
r = req("POST", apply, BOB)
|
||||
assert r.status_code >= 500, r.text
|
||||
except Exception as exc: # noqa: BLE001 — TestClient 가 서버 예외를 그대로 올림
|
||||
assert "link failed" in str(exc), exc
|
||||
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 0 # 업무도 롤백
|
||||
assert ST.get_meeting_task(item_id=row["id"])["task_id"] is None
|
||||
assert inbox() == 0 # 알림은 커밋 뒤에만
|
||||
finally:
|
||||
with ST._pool.connection() as conn: # noqa: SLF001
|
||||
conn.execute("DROP TRIGGER IF EXISTS pj_test_fail_link ON goal_meeting_tasks")
|
||||
conn.execute("DROP FUNCTION IF EXISTS pj_test_fail_link()")
|
||||
# ② 트리거를 걷고 다시 — 업무는 정확히 하나, 배정 알림도 하나
|
||||
r = req("POST", apply, BOB)
|
||||
assert r.status_code == 201, r.text
|
||||
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 1 and inbox() == 1
|
||||
assert req("POST", apply, BOB).status_code == 200 # 다시 눌러도 그대로
|
||||
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 1
|
||||
# ③ 풀 연결 1개 — 예전 구조(잠근 연결 + create_task 의 두 번째 연결)는 여기서 풀 대기에 걸렸다
|
||||
small = ProjectStore(DSN, max_size=1)
|
||||
try:
|
||||
APP.state.project_store = small
|
||||
row2 = req("POST", url, BOB, json={"title": f"풀1-{RUN}", "project_id": p["id"], "stage_id": s["id"]}).json()["task"]
|
||||
t0 = _time.monotonic()
|
||||
r = req("POST", f"/project/api/goals/meeting-quick-tasks/{row2['id']}/apply", BOB)
|
||||
assert r.status_code == 201 and _time.monotonic() - t0 < 10, (r.status_code, _time.monotonic() - t0)
|
||||
finally:
|
||||
APP.state.project_store = ST
|
||||
small.close()
|
||||
# ④ 그사이 줄이 바뀌면(확인한 값과 다르면) 만들지 않고 409 — 확인하지 않은 값으로 업무가 생기지 않게
|
||||
row3 = req("POST", url, BOB, json={"title": f"바뀜-{RUN}", "project_id": p["id"], "stage_id": s["id"]}).json()["task"]
|
||||
snap = ST.get_meeting_task(item_id=row3["id"])
|
||||
ST.update_meeting_task(item_id=row3["id"], fields={"title": f"바뀜2-{RUN}"}, by=BOB)
|
||||
try:
|
||||
ST.apply_meeting_task(item_id=row3["id"], task_fields={"project_id": p["id"], "title": snap["title"],
|
||||
"stage_id": s["id"], "created_by": BOB}, expect=snap)
|
||||
raise AssertionError("409 가 나야 한다")
|
||||
except store.GoalCellConflict:
|
||||
pass
|
||||
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title LIKE %s", f"바뀜%-{RUN}") == 0
|
||||
_clear_quick(w)
|
||||
|
||||
|
||||
def test_subtask_followers_and_reaction_alert():
|
||||
"""업무 창 세부 업무 줄의 협업자(상세 응답 subtasks[].followers) + 댓글 이모티콘 반응 알림(2026-10-13)."""
|
||||
p = _project("P-subfol", ADMIN, (ALICE, BOB))
|
||||
|
||||
Reference in New Issue
Block a user