22 Commits

Author SHA1 Message Date
king 80b7becd45 Merge branch 'fix/meta-ads-no-vat' 2026-10-16 14:04:58 +09:00
king 8051e7f207 fix(performance): 메타 광고비에 부가세 1.1 곱하지 않음
- 메타 지출 금액은 이미 부가세 포함(사용자 확인) — 광고비 = 지출 금액 그대로(외화 계정은 × 그날 환율만).
  × 1.1 은 비용이 부가세 별도인 구글만 그대로.
- 일자별 표: "광고비(부가세 포함)"·"지출 금액(부가세 별도)" 두 열 → "지출 금액(부가세 포함)" 한 열.
- 설정·광고비 탭 안내 문구, 문서, 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:04:57 +09:00
king 7933f163b4 Merge branch 'feat/meta-ads-usd-fx' 2026-10-16 13:59:50 +09:00
king 0836d6a926 feat(performance): 메타 외화(USD) 광고 계정 — 그날 환율로 원화 환산
- 예전엔 원화가 아닌 계정이면 "원화 계정만" 오류로 저장 안 함 → 이제 지출 금액·구매 전환값을 그날 환율로 원화 환산해
  다른 계정과 합산(광고비 = 지출 × 환율 × 1.1, ROAS 는 비율이라 그대로).
- fx.py: Frankfurter v2(키 없음, 중앙은행 고시 환율 종합, 매일)에서 기간 환율 한 번에, 빈 날은 앞 가장 가까운 날,
  못 구하면 그 회차 저장 안 함, 지난 날 환율은 프로세스 캐시.
- 계정 탭에 지출 금액(USD)·적용 환율(원)(합계 = 광고비 가중 평균), 연결 테스트·설정 안내 문구 갱신.
- 테스트: 혼합 계정 환산·빈 날 환율·환율 장애·캐시·환율 합계, 실제 Frankfurter 응답으로 파싱 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:59:49 +09:00
king 36b1f49340 Merge branch 'feat/meta-ads-account-tabs' 2026-10-16 13:38:18 +09:00
king b2710a0831 feat(performance): 메타 광고 상세보기 [합계 | 계정별] 탭
- 가져올 때 그날 메타 행 metrics 에 계정별 값(_accounts: 이름·광고비·ROAS·항목, insights account_name)을 함께 저장
  — 새 마이그레이션 없음. "_" 키는 일자별 표 열·합계·화면 값에서 제외.
- ad_spend.detail_tabs: 합계 탭 + 계정 탭(그 계정이 광고 낸 날만, 광고비 큰 계정부터), 계정별 값 없는 날 수 안내.
- 상세보기 창: 탭(주황 강조, 계정 ID 말풍선), 계정 탭은 1원 반올림 차이 안내. 네이버·구글은 그대로 표 하나.
- 테스트: 계정별 변환·탭 순서/이름/가중 ROAS·옛 자료 안내·API 응답, jsdom 탭 전환.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:38:17 +09:00
king 8bbb1f9ab2 Merge branch 'fix/meta-ads-diagnosis-cut' 2026-10-16 13:26:50 +09:00
king 8a597007cb fix(performance): 메타 연결 테스트 진단이 잘리던 문제
- 비밀값 가림(redact_text)의 기본 300자 한도에서 긴 메타 원문·안내 뒤의 [진단]이 "[진…"으로 잘렸다.
- 연결 테스트 문구를 [진단] 먼저 + 메타 원문(긴 안내 주소 제거) 뒤로 바꾸고,
  광고 연동 오류 문구 한도를 ad_sync.AD_MESSAGE_MAX(1200자)로.
- 테스트: 설정 연결 테스트 경로(AdSyncService)에서 진단 전체·순서·주소 제거·토큰 미포함 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:26:49 +09:00
king dc54553d2f Merge branch 'fix/meta-ads-permission-diagnosis' 2026-10-16 13:21:51 +09:00
king 527ec83b30 feat(performance): 메타 광고 권한 오류(#200) 원인 진단
- 연결 테스트가 권한 오류를 받으면 메타에 debug_token(권한·대상 계정·만료, 안 되면 me/permissions)과
  me/adaccounts(보이는 계정)를 물어 원인 하나를 짚는다: ads_read 없음 / 계정 미배정 / 권한이 다른 계정에만 / 앱 쪽.
- 광고비 탭 불러오기의 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내. 진단 문구에도 토큰 미포함.
- 테스트 7개 추가(원인별 결론·폴백·안내 위치).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:21:50 +09:00
king abf03f0a80 Merge branch 'feat/meta-ads-api' 2026-10-16 13:09:44 +09:00
king b397bdf83b feat(performance): 메타 광고 API 연동 — 광고비·구매 ROAS 자동 가져오기
- ad_sources/meta_ads.py + registry 한 줄: Meta Marketing API Insights(기본 v26.0),
  level=account·하루 단위, 광고 계정 여러 개를 날짜별로 합산, paging.next 따라감(graph.facebook.com 밖 주소 거부).
- 설정(실적 설정 → 광고 API 연동): 광고 계정 ID(여러 개)·액세스 토큰(암호화)·앱 시크릿(선택, appsecret_proof)·API 버전.
- 광고비 = 지출 금액 × 1.1(부가세 포함, 구글과 같은 기준), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS).
  구매 값은 omni_purchase → purchase → 픽셀 구매 중 처음 있는 것 하나(겹친 값 더하지 않음). 원화 계정만.
- 메타 오류 코드 안내(토큰 만료 190·권한 200·계정 ID 100·호출 한도), 오류 문구에 토큰·주소 미포함.
- 메타 머리글 = 일자별 보고서 표(DETAIL_CHANNELS), 화면 안내 문구·문서 갱신. 새 마이그레이션·환경변수 없음.
- 테스트: test_meta_ads.py(가짜 메타 서버, 실제 fetch_days → AdSyncService), 메타 연동 반영해 기존 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:09:43 +09:00
king 32457e4ce8 Merge branch 'feat/project-options-system' 2026-10-16 10:29:39 +09:00
king 94fac65238 feat(project): Project 옵션 시스템 전체 적용 + 모달 안 말풍선 가림 수정
- 프로젝트 화면(처음 여는 탭)·보드(카드 표지)는 서버 저장(project_db.project_options, 마이그레이션 029)
  → 수퍼관리자·Admin 이 바꾸면 모든 사용자에게 적용. 일반(폰트)은 그대로 이 브라우저(localStorage).
- GET/PUT /project/api/options(쓰기는 Admin 이상, 보낸 키만, 029 미적용 503). 검사·기본값은
  store.normalize/validate_project_options 한 곳. 프로젝트 화면은 data-default-view·data-board-cover 로 받음
  (읽기 실패해도 기본값으로 열림).
- 옵션 창: 열 때 서버 최신값 읽기(실패 시 시스템 칸 잠금·폰트만 저장), 바뀐 키만 PUT, 실패면 창 유지.
  분류 제목 옆 적용 범위 배지(이 브라우저에만 / 모든 사용자에게).
- 공용 말풍선: 모달 대화창(showModal) 안에서는 popover(top layer)로 띄워 대화창 뒤에 가려지지 않게.
- 테스트: tests/test_project_options_api.py, jsdom 옵션 테스트 갱신. 도움말·문서·DEPLOYMENT(029) 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:29:37 +09:00
king 1cabad8e3b Merge branch 'feat/project-options-admin' 2026-10-16 10:11:46 +09:00
king e753e55aa1 feat(project): Project 옵션 — 처음 여는 탭·보드 표지를 Admin 에게도
- 프로젝트 화면·보드 분류: 수퍼관리자 → 수퍼관리자·Admin(pj_admin / project.js isPAdmin).
- 관리자(긴급 공지) 분류는 그대로 수퍼관리자만(공지 화면이 수퍼관리자 전용).
- Pro user·User 는 폰트만, 브라우저에 남은 첫 탭·표지 값은 무시(기본값).
- Admin 테스트 추가, 도움말·문서 갱신, project.js 캐시 버전 올림.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:11:45 +09:00
king 31db917eb8 chore(notice): project.js 캐시 버전 맞춤(20261016b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:08:41 +09:00
king 59dd7e2ef9 Merge branch 'feat/project-options-super-only' 2026-10-16 10:08:22 +09:00
king 30b0366818 feat(project): Project 옵션 — 폰트만 모두에게, 처음 여는 탭·보드 표지·관리자는 수퍼관리자만
- 옵션 창의 프로젝트 화면·보드 분류를 수퍼관리자에게만 렌더(관리자 분류와 같은 조건).
- 수퍼관리자가 아니면 project.js 가 브라우저에 남은 pj_default_view·pj_board_cover 를 무시하고
  기본값(보드·표지 켬)으로 동작. 일반 사용자 저장은 pj_font 만 씀.
- 테스트: 수퍼관리자 렌더(project_super_render.html) 추가, 일반 사용자 경우 테스트. 도움말·문서 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:08:21 +09:00
king d6b15a6aec Merge branch 'feat/project-options-dialog' 2026-10-16 10:03:33 +09:00
king ed7b2ef3ca feat(project): Project 옵션 창 개편 — 분류별 설정 + 보드 카드 표지·처음 여는 탭
- 옵션 창을 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정 구조로 개편,
  아래 [기본값으로]·취소·저장(한꺼번에 저장). 폰트·긴급 공지(수퍼관리자)는 그대로.
- 보드: 카드 표지 이미지 켜기/끄기(localStorage pj_board_cover, 기본 켬) — 저장하면 보던 보드에 바로 반영.
- 프로젝트 화면: 처음 여는 탭(pj_default_view — 보드·목록·캘린더·타임라인·대시보드).
  달력 월 이동 복원·전체 보기(대시보드)·업무 창 패널(embed)은 기존 동작 유지.
- 도움말·docs/PROJECT_MODULE.md·CLAUDE.md 갱신, jsdom 테스트 추가, 정적 파일 버전 올림.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:03:32 +09:00
king 70743394d8 Merge branch 'fix/code-review-2026-10-15' 2026-10-15 18:54:19 +09:00
40 changed files with 1886 additions and 110 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
@@ -2,7 +2,7 @@
{% block head_extra %} {% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261013i" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script> <script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %} {% endblock %}
@@ -64,7 +64,7 @@
</section> </section>
</div> </div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script> <script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script> <script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
@@ -16,6 +16,12 @@ from typing import Any
from ..adapters.base import AdapterContext, CredentialField, NotConfigured from ..adapters.base import AdapterContext, CredentialField, NotConfigured
# AdDay.metrics 안의 계정별 값(여러 광고 계정을 합치는 채널 — 메타, 2026-10-16):
# {ACCOUNTS_KEY: {계정 ID: {"name", "amount", "roas", "metrics"}}} — 상세보기 [합계 | 계정…] 탭(ad_spend.detail_tabs).
# "_" 로 시작하는 metrics 키는 일자별 표 열·합계에 넣지 않는다(ad_spend.detail_table).
ACCOUNTS_KEY = "_accounts"
@dataclass @dataclass
class AdDay: class AdDay:
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로.""" """광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
@@ -0,0 +1,389 @@
"""메타 광고(Meta Marketing API — Insights) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-16 사용자: 토큰·광고 계정 ID 준비 완료)
- 액세스 토큰 하나(시스템 사용자 토큰 권장 — 만료 없음. 사용자 토큰은 약 60일 뒤 만료) + 광고 계정 ID 여러 개.
토큰에 ads_read 권한이 있어야 하고, 토큰 주인(시스템 사용자 등)이 각 광고 계정에 배정돼 있어야 한다.
- 메타 문서대로 토큰은 access_token 매개변수로 보낸다. 앱 설정에서 "앱 시크릿 필요"를 켰다면 앱 시크릿을 넣어
appsecret_proof(HMAC-SHA256)를 같이 보낸다. 토큰은 오류 문구에 넣지 않고(주소도 넣지 않음),
ad_sync 가 저장된 비밀값을 다시 한 번 가린다. httpx 요청 로그(INFO)는 주소에 토큰이 들어가므로 켜지 않는다.
조회(GET /{버전}/act_{계정}/insights)
level=account · time_increment=1(하루씩) · time_range={since, until} · fields=spend·노출·클릭·구매 전환 등.
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다.
- 원화가 아닌 계정(USD 등, 2026-10-16)은 지출 금액·구매 전환값을 그날 환율로 원화 환산(fx.krw_rates — Frankfurter 중앙은행 고시 환율 종합,
그날 값이 없으면 앞 가장 가까운 날). 계정 탭에 원래 통화 지출·적용 환율. ROAS 는 비율이라 환율과 무관.
- 기여(어트리뷰션)는 메타가 광고 관리자 설정을 그대로 따른다(2025-06 부터 API 의 기여 매개변수는 무시됨) — 화면 값과 같다.
- 구매 전환값·구매수 = action_values·actions 의 구매 항목 하나(omni_purchase → purchase → 픽셀 구매 순서로 처음 있는 것).
메타는 같은 구매를 여러 action_type 에 같은 값으로 겹쳐 주므로 더하지 않는다.
- 금액(광고비) = 지출 금액 그대로(원 반올림) — **메타 지출 금액은 이미 부가세 포함**(2026-10-16 사용자 확인).
부가세를 더하는(× 1.1) 것은 비용이 부가세 별도인 구글만이다.
- ROAS(%) = 구매 전환값 ÷ 지출 금액 × 100 — 광고 관리자 "구매 ROAS" 와 같은 값, 지출 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·링크 클릭·구매수·구매 전환값)은 광고비 탭 메타 머리글 → 일자별 표.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 메타는 버전을 약 2년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import re
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .. import fx
from .base import ACCOUNTS_KEY, AdDay, AdSource
API_BASE = "https://graph.facebook.com"
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
MAX_DAYS = 366
MAX_ACCOUNTS = 30
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase")
INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND = "지출 금액(부가세 포함)" # = 광고비(메타 지출 금액은 부가세 포함 — 구글처럼 따로 더하지 않음)
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
M_FX = "적용 환율(원)" # 외화 계정 탭에만 — 그날 1 계정 통화 = ? 원(fx.krw_rates)
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임). 권한 오류는 연결 테스트가 원인을 진단한다(_diagnose) —
# 불러오기에서 난 오류엔 그 안내를 붙이고, 연결 테스트 자체에서는 진단 결과로 바꿔 쓴다.
_DIAG_HINT = "(실적 설정 → 광고 API 연동 → 메타 [연결 테스트]가 원인을 진단합니다)"
_HINTS = {
190: "토큰이 만료됐거나 무효입니다. 비즈니스 설정 → 시스템 사용자에서 토큰을 다시 만들어 [액세스 토큰]에 넣으세요(시스템 사용자 토큰은 만료 없음).",
102: "토큰을 읽을 수 없습니다. 토큰을 다시 복사해 넣으세요.",
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요"
+ _DIAG_HINT + ".",
10: "토큰에 권한이 없습니다(ads_read). 앱·토큰 권한을 확인하세요.",
100: "요청 값이 올바르지 않습니다 — 광고 계정 ID 가 맞는지, 토큰 주인이 그 계정을 볼 수 있는지 확인하세요.",
803: "광고 계정 ID 를 찾을 수 없습니다(숫자만, act_ 는 있어도 됨).",
4: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
17: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
613: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80000: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80004: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
2635: "API 버전이 종료됐습니다 — 실적 설정에서 API 버전을 최신으로 바꾸세요.",
}
_RATE_LIMIT = {4, 17, 613, 80000, 80004}
_AUTH = {10, 102, 200}
_ACCOUNT_STATUS = {1: "운영 중", 2: "사용 중지", 3: "미결제", 7: "검토 대기", 8: "결제 대기", 9: "유예 기간", 100: "종료 대기", 101: "종료"}
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def parse_account_ids(raw: str) -> list[str]:
"""'act_123, 456\\n789' → ['123', '456', '789'](순서 유지·중복 제거). 형식이 틀리면 ValueError."""
out: list[str] = []
for part in re.split(r"[\s,;]+", raw or ""):
if not part:
continue
v = part[4:] if part.lower().startswith("act_") else part
if not re.fullmatch(r"\d{5,20}", v):
raise ValueError("광고 계정 ID 는 숫자여야 합니다(act_ 는 있어도 됨, 여러 개는 쉼표나 줄바꿈으로 구분).")
if v not in out:
out.append(v)
if len(out) > MAX_ACCOUNTS:
raise ValueError(f"광고 계정은 {MAX_ACCOUNTS}개까지 넣을 수 있습니다.")
return out
def _num(v: Any) -> Decimal:
"""메타 응답 숫자(문자열로 옴, 0 이면 빠지기도 함) → Decimal."""
if v is None or v == "":
return Decimal(0)
try:
return Decimal(str(v))
except ArithmeticError:
return Decimal(0)
def _won(v: Decimal) -> int:
return int(v.quantize(Decimal(1), rounding=ROUND_HALF_UP))
def _purchase(items: Any) -> Decimal:
"""actions / action_values 목록에서 구매 값 하나(PURCHASE_TYPES 순서로 처음 있는 것 — 겹친 값을 더하지 않는다)."""
by_type = {str((i or {}).get("action_type")): (i or {}).get("value") for i in (items or []) if isinstance(i, dict)}
for t in PURCHASE_TYPES:
if t in by_type:
return _num(by_type[t])
return Decimal(0)
def _meta_error(resp: httpx.Response) -> tuple[int, str]:
"""메타 오류 응답 {"error": {"message", "code", "error_subcode", ...}} → (코드, 문구)."""
try:
err = (resp.json() or {}).get("error") or {}
except ValueError:
return 0, f"HTTP {resp.status_code}"
if not isinstance(err, dict):
return 0, f"HTTP {resp.status_code}"
msg = str(err.get("error_user_msg") or err.get("message") or f"HTTP {resp.status_code}")
try:
code = int(err.get("code") or 0)
except (TypeError, ValueError):
code = 0
return code, msg
class MetaAdsSource(AdSource):
code = "meta"
name = "메타 광고"
docs_url = "https://developers.facebook.com/docs/marketing-api/insights"
note = ("메타 마케팅 API(Insights)로 광고 계정별 날짜별 지출 금액·구매 ROAS·노출수·클릭수·구매를 가져와 계정을 합칩니다. "
"준비: ① ads_read 권한이 있는 액세스 토큰(비즈니스 설정 → 시스템 사용자 토큰 권장 — 만료 없음) "
"② 토큰 주인을 각 광고 계정에 배정. 광고비 = 메타 지출 금액 그대로(이미 부가세 포함)입니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("account_ids", "광고 계정 ID", multiline=True, placeholder="act_1234567890\nact_9876543210",
help="광고비를 가져올 광고 계정 번호(광고 관리자 주소의 act= 뒤 숫자). 여러 개면 줄바꿈이나 쉼표로 — "
"날짜별로 합쳐서 메타 한 칸에 들어갑니다."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="ads_read 권한이 있는 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("app_secret", "앱 시크릿", secret=True, required=False, placeholder="앱에서 '앱 시크릿 필요'를 켰을 때만",
help="메타 앱 설정 → 고급에서 'API 호출에 앱 시크릿 필요'를 켰다면 넣습니다(appsecret_proof). 아니면 비워 둡니다."),
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
help=f"비워 두면 {DEFAULT_VERSION}. 메타가 버전 종료를 알리면 새 버전(예: v27.0)으로 바꿉니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
ids = (values.get("account_ids") or "").strip()
if ids and ids != "__stored__":
try:
parse_account_ids(ids)
except ValueError as exc:
errors.append(str(exc))
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
ver = (values.get("api_version") or "").strip()
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}\.0", ver):
errors.append("API 버전은 v26.0 처럼 입력하세요.")
return errors
# ── 요청 ──────────────────────────────────────────────
def _setup(self, ctx: AdapterContext) -> tuple[list[str], str, dict[str, str]]:
self.require_configured(ctx)
try:
accounts = parse_account_ids(ctx.credentials.get("account_ids"))
except ValueError as exc:
raise NotConfigured(str(exc)) from None
if not accounts:
raise NotConfigured("광고 계정 ID 를 입력하세요.")
token = (ctx.credentials.get("access_token") or "").strip()
auth = {"access_token": token}
secret = (ctx.credentials.get("app_secret") or "").strip()
if secret:
auth["appsecret_proof"] = hmac.new(secret.encode(), token.encode(), hashlib.sha256).hexdigest()
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
return accounts, version, auth
def _get(self, ctx: AdapterContext, client: httpx.Client, url: str, params: dict[str, Any] | None) -> dict[str, Any]:
ctx.progress.check()
try:
resp = client.get(url, params=params)
except httpx.HTTPError as exc:
raise ApiError(f"메타 API 에 연결하지 못했습니다({type(exc).__name__}).") from None # 주소(토큰 포함)는 넣지 않는다
if resp.status_code != 200:
code, msg = _meta_error(resp)
hint = _HINTS.get(code, "")
text = f"메타 API 오류({code or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
if code == 190:
raise TokenExpired(text)
auth_problem = code in _AUTH or (resp.status_code in (401, 403) and code not in _RATE_LIMIT)
raise (AuthFailed if auth_problem else ApiError)(text)
try:
body = resp.json()
except ValueError:
raise ApiError("메타 API 응답을 읽을 수 없습니다.") from None
return body if isinstance(body, dict) else {}
# ── 권한 진단(연결 테스트가 권한 오류를 받았을 때) ─────────
def _diagnose(self, ctx: AdapterContext, client: httpx.Client, version: str, auth: dict[str, str],
accounts: list[str]) -> str:
"""토큰이 받은 권한·권한 대상 계정·볼 수 있는 광고 계정을 메타에 물어 원인을 짚는다(2026-10-16 #200 오류).
조회가 실패해도 예외를 내지 않는다(진단은 덧붙이는 정보). 토큰 값은 문구에 넣지 않는다."""
lines: list[str] = []
scopes: set[str] | None = None
ads_targets: set[str] | None = None # ads_read/ads_management 가 특정 계정에만 걸려 있으면 그 계정들
try: # ① 토큰 점검 — 앱 개발자 토큰·시스템 사용자 토큰이면 같은 토큰으로 된다
d = (self._get(ctx, client, f"{API_BASE}/{version}/debug_token",
{**auth, "input_token": auth["access_token"]}).get("data") or {})
scopes = {str(s) for s in d.get("scopes") or []}
for g in d.get("granular_scopes") or []:
if str((g or {}).get("scope")) in ("ads_read", "ads_management") and (g or {}).get("target_ids"):
ads_targets = (ads_targets or set()) | {str(t) for t in g["target_ids"]}
exp = int(d.get("expires_at") or 0)
expires = "만료 없음" if exp == 0 else date.fromtimestamp(exp).isoformat() + " 만료"
lines.append(f"토큰: 앱 {d.get('application') or d.get('app_id') or '?'}({d.get('app_id') or '?'}) · {expires}"
+ ("" if d.get("is_valid", True) else " · 무효"))
except AdapterError:
try: # ② 토큰 점검을 못 하면 받은 권한 목록만
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/permissions", dict(auth)).get("data") or []
scopes = {str(r.get("permission")) for r in rows if r.get("status") == "granted"}
except AdapterError:
pass
if scopes is not None:
has = sorted(scopes & {"ads_read", "ads_management"})
lines.append("광고 권한: " + (", ".join(has) if has else "없음(ads_read·ads_management 둘 다 없음)"))
visible: set[str] | None = None
try: # ③ 이 토큰으로 볼 수 있는 광고 계정
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/adaccounts",
{**auth, "fields": "account_id,name", "limit": 200}).get("data") or []
visible = {str(r.get("account_id") or "") for r in rows}
lines.append(f"이 토큰으로 보이는 광고 계정 {len(visible)}개")
except AdapterError:
pass
missing = [a for a in accounts if visible is not None and a not in visible]
not_target = [a for a in accounts if ads_targets is not None and a not in ads_targets]
# 결론 — 가장 앞선 원인 하나
if scopes is not None and not scopes & {"ads_read", "ads_management"}:
todo = ("토큰에 ads_read 권한이 없습니다 → 토큰을 새로 만들면서 ads_read 를 체크하세요"
"(비즈니스 설정 → 사용자 → 시스템 사용자 → 새 토큰 생성 → 권한에서 ads_read).")
elif missing:
todo = ("입력한 계정 중 이 토큰 주인에게 배정되지 않은 계정: " + ", ".join("act_" + a for a in missing)
+ " → 비즈니스 설정 → 사용자 → 시스템 사용자(토큰 주인) → [자산 할당] → 광고 계정에서 그 계정을 고르고 "
"'성과 보기'(또는 전체 권한)를 켠 뒤, 토큰을 새로 만들어 넣으세요(배정 전에 만든 토큰은 권한이 안 바뀔 수 있음).")
elif not_target:
todo = ("토큰의 ads_read 권한이 다른 계정에만 걸려 있습니다(대상 아님: " + ", ".join("act_" + a for a in not_target)
+ ") → 토큰을 새로 만들 때 이 광고 계정도 대상에 포함하세요.")
elif visible is not None:
todo = ("토큰 권한·계정 배정은 맞습니다 → 앱 쪽 문제일 가능성이 큽니다: 앱이 이 광고 계정을 가진 비즈니스에 연결돼 있는지"
"(비즈니스 설정 → 계정 → 앱), 앱 대시보드에 Marketing API 제품이 추가돼 있는지, 앱이 '제한 액세스'라면 토큰 주인이 앱의 "
"관리자·개발자 역할인지 확인하세요.")
else:
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
return "[진단] " + " · ".join(lines + [todo])
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
accounts, version, auth = self._setup(ctx)
parts: list[str] = []
not_krw = False
with _http(ctx) as client:
for acc in accounts:
try:
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
{**auth, "fields": "name,currency,timezone_name,account_status"})
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
# 진단(고칠 곳)을 맨 앞에, 메타 원문은 짧게 뒤에 — 길면 화면·기록에서 뒤가 잘리므로(2026-10-16 "[진…" 잘림)
original = str(exc).split(" — ")[0]
original = re.sub(r",?\s*refer to https?://\S+(?: for details)?", "", original)
raise AuthFailed(self._diagnose(ctx, client, version, auth, accounts)
+ f" (메타 원문: {original})") from None
cur = str(info.get("currency") or "?")
not_krw = not_krw or cur != "KRW"
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
parts.append(f"{info.get('name') or acc}({cur}·{info.get('timezone_name') or '?'}{'·' + status if status else ''})")
msg = f"연결됨 — 광고 계정 {len(accounts)}개: " + ", ".join(parts)
if not_krw:
msg += f" (원화가 아닌 계정은 날마다 그날 환율로 원화로 바꿔 넣습니다 — {fx.SOURCE_LABEL})"
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}일까지 가져올 수 있습니다.")
accounts, version, auth = self._setup(ctx)
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})}
raw: list[tuple[str, date, str, dict[str, Any]]] = [] # (계정, 날짜, 통화, insights 한 줄)
names: dict[str, str] = {}
with _http(ctx) as client:
for acc in accounts:
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
page_params: dict[str, Any] | None = params
for _ in range(MAX_PAGES):
body = self._get(ctx, client, url, page_params)
for r in body.get("data") or []:
try:
day = date.fromisoformat(str(r.get("date_start")))
except ValueError:
continue
if r.get("account_name"):
names[acc] = str(r["account_name"])[:100]
raw.append((acc, day, str(r.get("account_currency") or "KRW").upper(), r))
nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt:
break
if not nxt.startswith(API_BASE + "/"):
raise ApiError("메타 API 다음 쪽 주소가 올바르지 않습니다.")
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
else:
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
# 원화가 아닌 계정(USD 등) — 그날 환율로 원화 환산(2026-10-16). 통화마다 기간 환율을 한 번에.
rates: dict[str, dict[date, Decimal]] = {}
for cur in sorted({c for _a, _d, c, _r in raw if c != "KRW"}):
if not re.fullmatch(r"[A-Z]{3}", cur):
raise ApiError(f"광고 계정 통화({cur[:10]})를 알 수 없습니다.")
try:
rates[cur] = fx.krw_rates(client, cur, start, end)
except fx.FxError as exc:
raise ApiError(f"{cur} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합(원화)
per_acc: dict[date, dict[str, dict[str, Any]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
for acc, day, cur, r in raw:
rate = Decimal(1) if cur == "KRW" else rates[cur][day]
one = per_acc.setdefault(day, {}).setdefault(acc, {**_zero(), "cur": cur, "rate": rate, "orig": Decimal(0)})
_add(one, r, rate)
one["orig"] += _num(r.get("spend")) # 그 계정 통화 그대로의 지출 금액
_add(sums.setdefault(day, _zero()), r, rate)
out: list[AdDay] = []
for day in sorted(sums):
amount, roas, metrics = _convert(sums[day])
# 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
# 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
accounts_out: dict[str, Any] = {}
for acc, a in per_acc.get(day, {}).items():
a_amount, a_roas, a_metrics = _convert(a)
if a["cur"] != "KRW": # 외화 계정 — 원래 통화 지출과 적용 환율도 보여 준다(계정 탭)
a_metrics[f"지출 금액({a['cur']})"] = float(a["orig"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
a_metrics[M_FX] = float(a["rate"])
accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
"roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
metrics[ACCOUNTS_KEY] = accounts_out
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
def _zero() -> dict[str, Decimal]:
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
def _add(acc: dict[str, Any], r: dict[str, Any], rate: Decimal = Decimal(1)) -> None:
"""insights 한 줄(계정 하나·하루)을 더한다 — 금액(지출·구매 전환값)은 × rate(그날 1 계정 통화 = ? 원)로 원화."""
acc["spend"] += _num(r.get("spend")) * rate
acc["impr"] += _num(r.get("impressions"))
acc["clicks"] += _num(r.get("clicks"))
acc["link"] += _num(r.get("inline_link_clicks"))
acc["purchases"] += _purchase(r.get("actions"))
acc["value"] += _purchase(r.get("action_values")) * rate
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]:
"""더한 값 → (광고비 원, ROAS %, 일자별 표 항목). 광고비 = 지출 금액 그대로(메타 지출은 부가세 포함, 2026-10-16)."""
amount = _won(a["spend"])
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
return amount, roas, {
M_SPEND: amount,
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_LINK: int(a["link"]),
M_PURCHASES: int(a["purchases"]),
M_VALUE: _won(a["value"]),
M_ROAS: float(roas) if roas is not None else None,
}
@@ -4,8 +4,9 @@ from __future__ import annotations
from .base import AdSource from .base import AdSource
from .google_ads import GoogleAdsSource from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),) _SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES} _BY_CODE = {s.code: s for s in _SOURCES}
+41 -4
View File
@@ -27,6 +27,7 @@ from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence from typing import Any, Callable, Mapping, Sequence
from . import calc from . import calc
from .ad_sources.base import ACCOUNTS_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang). # 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
@@ -341,8 +342,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe
return merged, sorted(overlap) return merged, sorted(overlap)
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15) # 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
DETAIL_CHANNELS = frozenset({"naver", "google"}) DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]: def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
@@ -351,11 +352,13 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
cols: list[str] = [] cols: list[str] = []
for r in rows: for r in rows:
for k in (r.get("metrics") or {}): for k in (r.get("metrics") or {}):
if k not in cols: if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
cols.append(k) cols.append(k)
sums: dict[str, Decimal] = {} sums: dict[str, Decimal] = {}
for r in rows: for r in rows:
for k, v in (r.get("metrics") or {}).items(): for k, v in (r.get("metrics") or {}).items():
if k.startswith("_"):
continue
if isinstance(v, (int, float)) and not isinstance(v, bool): if isinstance(v, (int, float)) and not isinstance(v, bool):
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v)) sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()} total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
@@ -367,12 +370,46 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
if r.get("roas") is not None and int(r.get("amount") or 0) > 0) if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
total[k] = float(round(rev / spend, 2)) if spend else None total[k] = float(round(rev / spend, 2)) if spend else None
elif "환율" in k: # 외화 광고 계정 적용 환율(메타 USD 계정, 2026-10-16) — 더하지 않고 광고비 가중 평균
pairs = [(Decimal(str((r.get("metrics") or {})[k])), int(r.get("amount") or 0)) for r in rows
if isinstance((r.get("metrics") or {}).get(k), (int, float)) and int(r.get("amount") or 0) > 0]
weight = sum(w for _v, w in pairs)
total[k] = float(round(sum(v * w for v, w in pairs) / weight, 2)) if weight else None
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0), out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
"roas": float(r["roas"]) if r.get("roas") is not None else None, "roas": float(r["roas"]) if r.get("roas") is not None else None,
"values": r.get("metrics") or {}} for r in rows] "values": {k: v for k, v in (r.get("metrics") or {}).items() if not k.startswith("_")}} for r in rows]
return {"columns": cols, "rows": out_rows, "total": total} return {"columns": cols, "rows": out_rows, "total": total}
def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""상세보기 탭 — 계정별 값(ACCOUNTS_KEY)이 있는 채널(메타, 2026-10-16)은 [합계 | 계정…], 없으면 탭 없음.
계정 탭 = 그 계정이 광고를 낸 날만(그날 행의 계정 값으로 detail_table). 계정 이름은 가장 최근 날의 이름,
순서는 기간 광고비가 큰 계정부터(같으면 이름). accounts_missing = 광고비가 있는데 계정별 값이 없는 날 수
(계정별 저장 전에 가져온 날 — 다시 불러오면 생긴다)."""
per: dict[str, list[dict[str, Any]]] = {}
names: dict[str, str] = {}
missing = 0
for r in rows:
accs = (r.get("metrics") or {}).get(ACCOUNTS_KEY)
if not isinstance(accs, dict):
if int(r.get("amount") or 0):
missing += 1
continue
for acc, a in accs.items():
if not isinstance(a, dict):
continue
names[acc] = str(a.get("name") or f"act_{acc}")
per.setdefault(acc, []).append({"date": r["date"], "amount": int(a.get("amount") or 0),
"roas": a.get("roas"), "metrics": a.get("metrics") or {}})
if not per:
return {"tabs": [], "accounts_missing": 0}
spend = {acc: sum(x["amount"] for x in days) for acc, days in per.items()}
order = sorted(per, key=lambda acc: (-spend[acc], names[acc]))
tabs = [{"key": "total", "label": "합계", **detail_table(rows)}]
tabs += [{"key": acc, "label": names[acc], "account_id": acc, **detail_table(per[acc])} for acc in order]
return {"tabs": tabs, "accounts_missing": missing}
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 화면 데이터 # 화면 데이터
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
+3 -1
View File
@@ -22,6 +22,7 @@ from .security.redact import redact_text
logger = logging.getLogger("performance.ad_sync") logger = logging.getLogger("performance.ad_sync")
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for) AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
AD_MESSAGE_MAX = 1200 # 광고 연동 오류 문구 길이 한도(비밀값 가린 뒤)
_locks: dict[str, threading.Lock] = {} _locks: dict[str, threading.Lock] = {}
_locks_guard = threading.Lock() _locks_guard = threading.Lock()
@@ -57,7 +58,8 @@ class AdSyncService:
@staticmethod @staticmethod
def _message(exc: Exception, ctx: AdapterContext) -> str: def _message(exc: Exception, ctx: AdapterContext) -> str:
known = getattr(ctx.credentials, "known_secrets", lambda: [])() known = getattr(ctx.credentials, "known_secrets", lambda: [])()
return redact_text(str(getattr(exc, "message", "") or exc), known) # 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 300자에서 자르면 안내가 잘린다(2026-10-16 메타 #200 진단)
return redact_text(str(getattr(exc, "message", "") or exc), known, max_len=AD_MESSAGE_MAX)
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "", def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
cleared: set[str] | None = None) -> dict[str, Any]: cleared: set[str] | None = None) -> dict[str, Any]:
+90
View File
@@ -0,0 +1,90 @@
"""외화 → 원화 날짜별 환율(2026-10-16 사용자 요청: 메타 USD 광고 계정 — "그날 환율로 원화 환산").
출처: Frankfurter(https://frankfurter.dev, API 키 없음) v2 `GET /v2/rates?base=USD&quotes=KRW&from=&to=`
— 여러 나라 중앙은행 고시 환율을 합친 값(blended)이고 주말·공휴일 포함 매일 있다. 서울외국환중개 매매기준율과는
조금(보통 0.5% 안쪽) 다를 수 있다. 응답: [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1357.92}, …]
그날 값이 없으면(오늘처럼 아직 안 나온 날 등) 그 앞 가장 가까운 날 값을 쓴다(LOOKBACK_DAYS 안).
지난 날(2일 이상 지난) 환율은 프로세스 안에 기억해 30분마다 도는 자동 업데이트가 같은 날을 다시 묻지 않게 한다.
"""
from __future__ import annotations
import threading
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
import httpx
from app.timezone import today_kst
FX_API = "https://api.frankfurter.dev/v2/rates"
SOURCE_LABEL = "Frankfurter(중앙은행 고시 환율 종합)"
LOOKBACK_DAYS = 10 # 그날 환율이 없으면 이만큼 앞까지 찾는다
_SETTLED_AFTER = 2 # 오늘에서 이만큼 지난 날 환율만 기억(최근 값은 나중에 고시될 수 있음)
_cache_lock = threading.Lock()
_cache: dict[tuple[str, date], Decimal] = {}
class FxError(Exception):
"""환율을 가져오지 못함 — 문구는 화면에 그대로 보인다."""
def krw_rates(client: httpx.Client, currency: str, start: date, end: date, *, today: date | None = None) -> dict[date, Decimal]:
"""start~end(양 끝 포함) 날마다 1 {currency} = ? 원. 하루라도 못 정하면 FxError(일부만 환산해 저장하지 않게)."""
cur = (currency or "").upper()
if cur == "KRW":
return {start + timedelta(days=i): Decimal(1) for i in range((end - start).days + 1)}
days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
with _cache_lock:
known = {d: _cache[(cur, d)] for d in days if (cur, d) in _cache}
if len(known) == len(days):
return known
fetched = _fetch(client, cur, start - timedelta(days=LOOKBACK_DAYS), end)
today = today or today_kst()
out: dict[date, Decimal] = {}
for d in days:
rate = next((fetched[d - timedelta(days=k)] for k in range(LOOKBACK_DAYS + 1) if d - timedelta(days=k) in fetched), None)
if rate is None:
raise FxError(f"{d.isoformat()} 의 {cur}→KRW 환율을 찾지 못했습니다({SOURCE_LABEL}).")
out[d] = rate
with _cache_lock:
for d, rate in out.items():
if d in fetched and (today - d).days >= _SETTLED_AFTER:
_cache[(cur, d)] = rate
return out
def _fetch(client: httpx.Client, cur: str, start: date, end: date) -> dict[date, Decimal]:
try:
resp = client.get(FX_API, params={"base": cur, "quotes": "KRW", "from": start.isoformat(), "to": end.isoformat()})
except httpx.HTTPError as exc:
raise FxError(f"환율 서버({SOURCE_LABEL})에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
try:
msg = str((resp.json() or {}).get("message") or "")
except ValueError:
msg = ""
raise FxError(f"환율을 가져오지 못했습니다(HTTP {resp.status_code}{': ' + msg[:120] if msg else ''}).")
try:
rows = resp.json()
except ValueError:
raise FxError("환율 서버 응답을 읽을 수 없습니다.") from None
out: dict[date, Decimal] = {}
for r in rows if isinstance(rows, list) else []:
if not isinstance(r, dict) or str(r.get("quote") or "").upper() != "KRW":
continue
try:
d = date.fromisoformat(str(r.get("date")))
rate = Decimal(str(r.get("rate")))
except (ValueError, InvalidOperation):
continue
if rate > 0:
out[d] = rate
return out
def clear_cache() -> None:
"""테스트용."""
with _cache_lock:
_cache.clear()
+3 -3
View File
@@ -17,8 +17,8 @@ JSON API — 모듈 권한
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지) PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액, POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목) 네이버 광고 보고서 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일 넘으면 관리자 POST /performance/api/ad-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
JSON API — 관리자 JSON API — 관리자
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음) GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값) POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
@@ -490,7 +490,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
except ad_spend.AdMigrationNeeded as exc: except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(), return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
"to": end.isoformat(), **ad_spend.detail_table(rows)}) "to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
@router.post("/api/ad-spend/upload") @router.post("/api/ad-spend/upload")
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%} {%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -89,7 +89,7 @@
<thead> <thead>
<tr> <tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th> <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] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% 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 %} {% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 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> <th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr> </tr>
</thead> </thead>
@@ -119,10 +119,10 @@
</div> </div>
{% if period_kind != 'year' %} {% if period_kind != 'year' %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. <p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고, 칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목. 네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다. 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p> 구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% endif %} {% endif %}
</div> </div>
@@ -200,8 +200,8 @@
</div> </div>
<p class="perf-foot perf-muted"> <p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함). 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
메타는 지금은 직접 입력합니다. 메타는 지금은 직접 입력합니다.
</p> </p>
@@ -224,4 +224,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{%- macro won(v) -%} {%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span> {%- if v is none -%}<span class="perf-na"></span>
@@ -255,4 +255,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -103,13 +103,13 @@
</div> </div>
{% if is_admin %} {% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장. {# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #} 가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
<div class="erp-card perf-card" id="perf-ad-sources"> <div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head"> <div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2> <h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다. <span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span> 설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
</div> </div>
{% if not ad_api_ready %} {% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007 <div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
@@ -142,7 +142,8 @@
</table> </table>
</div> </div>
<p class="perf-foot perf-muted"> <p class="perf-foot perf-muted">
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다. 구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.<br>
메타 광고: 광고비 = 광고 관리자의 "지출 금액" 그대로(메타 금액은 이미 부가세 포함), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 "구매 ROAS"). 광고 계정이 여러 개면 날짜별로 합칩니다. 날짜는 광고 계정 시간대 기준이며, 달러 등 외화 계정은 그날 환율로 원화로 바꿔 넣습니다(중앙은행 고시 환율 종합, 그날 값이 없으면 직전 값).
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다. 가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
</p> </p>
</div> </div>
@@ -248,4 +249,4 @@
</section> </section>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %} {% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
@@ -126,7 +126,7 @@ def test_ad_dashboard_month():
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000 assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"] assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"] assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
assert ctx["detail_channels"] == ["google", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15) assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
assert ctx["api_cells"] == [] assert ctx["api_cells"] == []
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01") 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 day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
@@ -306,7 +306,9 @@ def test_sync_endpoint(monkeypatch):
assert r.status_code == 403 # 92일 넘으면 관리자만 assert r.status_code == 403 # 92일 넘으면 관리자만
admin["v"] = True 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/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 assert client.post("/performance/api/ad-sources/kakao/sync", json={}).status_code == 404 # 광고 API 연동이 없는 채널
r = client.post("/performance/api/ad-sources/meta/sync", json={}) # 메타(2026-10-16) — 연동은 있으나 미설정
assert r.status_code == 400 and "설정되지 않았습니다" in r.json()["detail"]
svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"} svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"}
r = client.post("/performance/api/ad-sources/google/sync", json={}) r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 502 and "권한 없음" in r.json()["detail"] assert r.status_code == 502 and "권한 없음" in r.json()["detail"]
@@ -0,0 +1,501 @@
"""메타 광고 API 연동(2026-10-16) — 입력 검사·요청 매개변수·여러 계정 합산·쪽 넘김·구매 값·부가세·ROAS·오류 안내·저장 서비스.
메타 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import hashlib
import hmac
import json
from datetime import date
from decimal import Decimal
import httpx
import pytest
from app.modules.performance import ad_spend, ad_sync
from app.modules.performance.ad_sources import meta_ads as ma
from app.modules.performance.ad_sources.registry import get_source
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured, TokenExpired
from app.modules.performance.credentials import CredentialService
TOKEN = "EAAGtesttoken0123456789abcdefSECRET"
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 k, v in self.values.items() if v and k in ("access_token", "app_secret")]
def _ctx(**over):
values = {"account_ids": "act_1111111111\n2222222222", "access_token": TOKEN}
values.update(over)
return AdapterContext(code="meta", credentials=Creds(values))
def _install(monkeypatch, handler):
"""가짜 메타 서버 — handler(request) 가 응답을 만든다. 보낸 요청을 돌려준다."""
seen = []
def route(request: httpx.Request) -> httpx.Response:
seen.append(request)
return handler(request)
monkeypatch.setattr(ma, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
return seen
def _row(day, spend, **extra):
r = {"date_start": day, "date_stop": day, "account_currency": "KRW", "spend": spend}
r.update(extra)
return r
# 계정 1: 두 쪽(paging.next), 계정 2: 한 쪽. 10-01 은 두 계정 모두 있음 → 날짜별 합산.
PAGE1 = {"data": [_row("2026-10-01", "100000", account_name="본계정", impressions="20000", clicks="400", inline_link_clicks="300",
actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"},
{"action_type": "link_click", "value": "300"}],
action_values=[{"action_type": "omni_purchase", "value": "450000"},
{"action_type": "purchase", "value": "450000"},
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "450000"}])],
"paging": {"next": "https://graph.facebook.com/v26.0/act_1111111111/insights?after=CUR&access_token=" + TOKEN}}
PAGE2 = {"data": [_row("2026-10-02", "0", impressions="10")], "paging": {}}
ACC2 = {"data": [_row("2026-10-01", "50000.5", account_name="서브계정", impressions="5000", clicks="100", inline_link_clicks="80",
actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}],
action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]}
def _insights_server(request: httpx.Request) -> httpx.Response:
path, q = request.url.path, request.url.params
if path == "/v26.0/act_1111111111/insights":
return httpx.Response(200, json=PAGE2 if q.get("after") == "CUR" else PAGE1)
if path == "/v26.0/act_2222222222/insights":
return httpx.Response(200, json=ACC2)
return httpx.Response(404, json={"error": {"message": "unknown path", "code": 100}})
def test_registered_and_detail_channel():
assert get_source("meta").name == "메타 광고"
assert "meta" in ad_spend.DETAIL_CHANNELS and "meta" in ad_spend.FILE_ROAS # 머리글 → 일자별 표, ROAS 는 광고 쪽 값
def test_parse_account_ids():
assert ma.parse_account_ids("act_123456, 654321\n\nACT_123456;777777") == ["123456", "654321", "777777"]
assert ma.parse_account_ids("") == []
for bad in ("act_abc", "12-34", "act_"):
with pytest.raises(ValueError):
ma.parse_account_ids(bad)
with pytest.raises(ValueError):
ma.parse_account_ids(",".join(str(100000 + i) for i in range(ma.MAX_ACCOUNTS + 1)))
def test_validate_credentials():
src = ma.MetaAdsSource()
ok = {"account_ids": "act_1111111111", "access_token": TOKEN}
assert src.validate_credentials(ok) == []
assert src.validate_credentials({**ok, "access_token": "__stored__"}) == []
assert {f.key for f in src.visible_fields()} == {"account_ids", "access_token", "app_secret", "api_version"}
assert {f.key for f in src.visible_fields() if f.secret} == {"access_token", "app_secret"}
errs = src.validate_credentials({"account_ids": "act_x", "access_token": "short token", "api_version": "26"})
assert len(errs) == 3 and not any("short token" in e for e in errs) # 토큰 값은 문구에 없음
assert "입력하세요" in " ".join(src.validate_credentials({}))
def test_fetch_days_sums_accounts_pages_and_converts(monkeypatch):
seen = _install(monkeypatch, _insights_server)
days = ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 2))
first = seen[0]
assert first.url.path == "/v26.0/act_1111111111/insights"
q = first.url.params
assert q["access_token"] == TOKEN and "appsecret_proof" not in q
assert (q["level"], q["time_increment"]) == ("account", "1")
assert json.loads(q["time_range"]) == {"since": "2026-10-01", "until": "2026-10-02"}
assert {"spend", "action_values", "actions", "account_currency", "date_start"} <= set(q["fields"].split(","))
assert [r.url.params.get("after") for r in seen] == [None, "CUR", None] # 계정 1 두 쪽 → 계정 2
d1, d2 = days
# 10-01: 지출 100,000 + 50,000.5 = 150,000.5 → 광고비 = 지출 그대로(메타는 부가세 포함, 2026-10-16) → 150,001
# 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000
# ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 150001, Decimal("400.00"))
total_metrics = {k: v for k, v in d1.metrics.items() if k != "_accounts"}
assert total_metrics == {"지출 금액(부가세 포함)": 150001, "노출수": 25000, "클릭수": 500,
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
assert list(d1.metrics)[0] == "지출 금액(부가세 포함)" # 일자별 표 첫 열(× 1.1 없음 — 부가세 별도 열도 없음)
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음
# 계정별(상세보기 탭, 2026-10-16) — 계정마다 따로 변환. 이름은 insights 의 account_name(없는 쪽은 같은 계정 앞 줄 이름)
a1, a2 = d1.metrics["_accounts"]["1111111111"], d1.metrics["_accounts"]["2222222222"]
assert (a1["name"], a1["amount"], a1["roas"]) == ("본계정", 100000, 450.0) # 지출 그대로, 450,000 ÷ 100,000
assert (a2["name"], a2["amount"], a2["roas"]) == ("서브계정", 50001, 300.0) # 50,000.5 → 50,001, 150,000 ÷ 50,000.5 = 299.997 → 300.00
assert a1["metrics"]["구매수"] == 10 and a2["metrics"]["구매 전환값"] == 150000 and a2["metrics"]["링크 클릭"] == 80
assert list(d2.metrics["_accounts"]) == ["1111111111"] and d2.metrics["_accounts"]["1111111111"]["name"] == "본계정"
assert "account_name" in seen[0].url.params["fields"].split(",")
def test_app_secret_proof_and_version(monkeypatch):
seen = _install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
out = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333", app_secret="appsecret", api_version="v27.0"),
date(2026, 10, 1), date(2026, 10, 1))
assert out == []
assert seen[0].url.path == "/v27.0/act_333333/insights"
expected = hmac.new(b"appsecret", TOKEN.encode(), hashlib.sha256).hexdigest()
assert seen[0].url.params["appsecret_proof"] == expected
def test_limits(monkeypatch):
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
with pytest.raises(ApiError, match="366"):
ma.MetaAdsSource().fetch_days(_ctx(), date(2025, 1, 1), date(2026, 10, 1))
with pytest.raises(NotConfigured):
ma.MetaAdsSource().fetch_days(_ctx(access_token=""), date(2026, 10, 1), date(2026, 10, 1))
# 다음 쪽 주소가 메타가 아니면 따라가지 않는다(토큰을 다른 곳에 보내지 않게)
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": [], "paging": {"next": "https://evil.example/x"}}))
with pytest.raises(ApiError, match="다음 쪽"):
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
@pytest.mark.parametrize("code,status,exc,hint", [
(190, 400, TokenExpired, "시스템 사용자"),
(200, 403, AuthFailed, "ads_read"),
(100, 400, ApiError, "광고 계정 ID"),
(17, 400, ApiError, "호출 한도"),
(80004, 403, ApiError, "호출 한도"), # 403 이어도 호출 한도는 인증 실패가 아님
])
def test_errors_are_explained(monkeypatch, code, status, exc, hint):
_install(monkeypatch, lambda req: httpx.Response(status, json={"error": {"message": "meta says no", "code": code}}))
with pytest.raises(exc) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
assert hint in str(info.value) and f"({code})" in str(info.value) and TOKEN not in str(info.value)
def test_network_error_has_no_token(monkeypatch):
def boom(req):
raise httpx.ConnectError("connect failed for " + str(req.url))
_install(monkeypatch, boom)
with pytest.raises(ApiError) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
assert "ConnectError" in str(info.value) and TOKEN not in str(info.value)
def test_connection_message(monkeypatch):
accounts = {"/v26.0/act_1111111111": {"name": "본계정", "currency": "KRW", "timezone_name": "Asia/Seoul", "account_status": 1},
"/v26.0/act_2222222222": {"name": "해외", "currency": "USD", "timezone_name": "America/Los_Angeles", "account_status": 2}}
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=accounts[req.url.path]))
msg = ma.MetaAdsSource().test_connection(_ctx())
assert "광고 계정 2개" in msg and "본계정(KRW·Asia/Seoul·운영 중)" in msg and "해외(USD" in msg and "사용 중지" in msg
assert "원화가 아닌 계정" in msg
assert seen[0].url.params["fields"] == "name,currency,timezone_name,account_status"
class FakeStore:
def __init__(self):
self.replaced, self.status = [], []
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 test_sync_service_end_to_end(monkeypatch):
"""실제 MetaAdsSource.fetch_days → AdSyncService 저장·상태. 실패 문구에서 토큰은 가린다."""
_install(monkeypatch, _insights_server)
store = FakeStore()
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx()
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 2), user="king@x")
assert res["ok"] and res["days"] == 2 and res["total"] == 150001 and res["name"] == "메타 광고"
code, start, end, days, user = store.replaced[0]
assert (code, start, end, user) == ("meta", date(2026, 10, 1), date(2026, 10, 2), "king@x")
assert [(d, amt, roas) for d, amt, roas, _m in days] == [(date(2026, 10, 1), 150001, Decimal("400.00")),
(date(2026, 10, 2), 0, None)]
assert store.status[-1] == ("meta", "ok", True, "", "sync")
# 메타가 오류 문구에 토큰을 되돌려 줘도 저장·화면 문구에서는 가린다
_install(monkeypatch, lambda req: httpx.Response(400, json={"error": {"message": "bad token " + TOKEN, "code": 190}}))
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 1))
assert not res["ok"] and res["status"] == "token_expired" and TOKEN not in res["message"]
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("token_expired", False) and TOKEN not in store.status[-1][3]
# ── 권한 오류(#200) 진단 — 연결 테스트가 메타에 토큰 정보를 물어 원인 하나를 짚는다(2026-10-16) ──
DENIED = {"error": {"message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission", "code": 200}}
def _diag_server(debug=None, perms=None, adaccounts=None):
"""debug/perms/adaccounts = 응답 dict, None 이면 그 조회도 실패(권한 오류)."""
def handler(req: httpx.Request) -> httpx.Response:
path = req.url.path
if path.endswith("/debug_token"):
assert req.url.params["input_token"] == TOKEN
return httpx.Response(200, json=debug) if debug is not None else httpx.Response(400, json=DENIED)
if path.endswith("/me/permissions"):
return httpx.Response(200, json=perms) if perms is not None else httpx.Response(400, json=DENIED)
if path.endswith("/me/adaccounts"):
return httpx.Response(200, json=adaccounts) if adaccounts is not None else httpx.Response(400, json=DENIED)
return httpx.Response(400, json=DENIED) # 광고 계정 조회 = 권한 오류
return handler
def _diag(monkeypatch, **server):
_install(monkeypatch, _diag_server(**server))
with pytest.raises(AuthFailed) as info:
ma.MetaAdsSource().test_connection(_ctx(account_ids="1111111111,2222222222"))
msg = str(info.value)
assert "(#200)" in msg and "[진단]" in msg and TOKEN not in msg
return msg
def _debug(scopes, granular=None, exp=0):
return {"data": {"app_id": "777", "application": "DBX ERP", "is_valid": True, "expires_at": exp,
"scopes": scopes, "granular_scopes": granular or []}}
ALL_VISIBLE = {"data": [{"account_id": "1111111111"}, {"account_id": "2222222222"}]}
def test_diagnose_missing_ads_read(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["public_profile", "business_management"]), adaccounts=ALL_VISIBLE)
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg and "DBX ERP(777)" in msg and "만료 없음" in msg
def test_diagnose_account_not_assigned(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts={"data": [{"account_id": "1111111111"}]})
assert "광고 권한: ads_read" in msg and "보이는 광고 계정 1개" in msg
assert "배정되지 않은 계정: act_2222222222" in msg and "act_1111111111" not in msg.split("배정되지 않은 계정")[1].split("→")[0]
assert "자산 할당" in msg
def test_diagnose_scope_targets_other_accounts(monkeypatch):
granular = [{"scope": "ads_read", "target_ids": ["1111111111"]}]
msg = _diag(monkeypatch, debug=_debug(["ads_read"], granular), adaccounts=ALL_VISIBLE)
assert "다른 계정에만" in msg and "act_2222222222" in msg
def test_diagnose_points_to_app_when_token_and_accounts_ok(monkeypatch):
msg = _diag(monkeypatch, debug=_debug(["ads_read", "ads_management"]), adaccounts=ALL_VISIBLE)
assert "광고 권한: ads_management, ads_read" in msg and "앱 쪽 문제" in msg
def test_diagnose_falls_back_to_permissions(monkeypatch):
perms = {"data": [{"permission": "ads_read", "status": "declined"}, {"permission": "public_profile", "status": "granted"}]}
msg = _diag(monkeypatch, debug=None, perms=perms, adaccounts=None)
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg # 거절(declined)은 받은 권한이 아님
def test_diagnose_unknown_when_meta_says_nothing(monkeypatch):
msg = _diag(monkeypatch, debug=None, perms=None, adaccounts=None)
assert "원인을 좁히지 못했습니다" in msg
def test_diag_hint_only_outside_connection_test(monkeypatch):
"""불러오기(fetch_days) 권한 오류엔 '연결 테스트가 진단' 안내, 연결 테스트 자체엔 그 안내 대신 진단 결과."""
_install(monkeypatch, _diag_server(debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE))
with pytest.raises(AuthFailed) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="1111111111"), date(2026, 10, 1), date(2026, 10, 1))
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
assert ma._DIAG_HINT not in msg
def test_connection_test_shows_full_diagnosis_first(monkeypatch):
"""설정 [연결 테스트](AdSyncService) 문구 — 진단이 맨 앞, 잘리지 않음, 메타 원문의 긴 주소는 뺌(2026-10-16 "[진…" 잘림)."""
long_denied = {"error": {"code": 200, "message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission, "
"refer to https://developers.facebook.com/docs/marketing-api/get-started/authorization/"
"#permissions-and-features for details"}}
def handler(req):
if req.url.path.endswith("/debug_token"):
return httpx.Response(200, json=_debug(["ads_read"]))
if req.url.path.endswith("/me/adaccounts"):
return httpx.Response(200, json={"data": []})
return httpx.Response(400, json=long_denied)
_install(monkeypatch, handler)
store = FakeStore()
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx(account_ids="1111111111,2222222222")
res = svc.test_connection("meta")
msg = res["message"]
assert not res["ok"] and res["status"] == "auth_failed"
assert msg.startswith("[진단]") and not msg.endswith("…") and len(msg) > 300 # 예전 300자 한도면 잘렸을 길이
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg
# ── 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
def _stored(day, amount, roas, metrics):
"""저장소 ad_details 행 모양."""
return {"date": day, "amount": amount, "roas": roas, "metrics": metrics, "source": "api"}
def test_detail_tabs_total_and_accounts():
def acc(name, amount, roas, spend_metric):
return {"name": name, "amount": amount, "roas": roas,
"metrics": {"지출 금액(부가세 포함)": amount, "노출수": spend_metric, "클릭수": spend_metric // 100, "클릭률(%)": 1.0,
"ROAS(%)": roas}}
rows = [
_stored("2026-10-01", 300, 200.0, {"지출 금액(부가세 포함)": 300, "노출수": 3000, "클릭수": 30, "클릭률(%)": 1.0, "ROAS(%)": 200.0,
"_accounts": {"1": acc("작은계정", 100, 100.0, 1000), "2": acc("큰계정", 200, 250.0, 2000)}}),
_stored("2026-10-02", 500, 300.0, {"지출 금액(부가세 포함)": 500, "노출수": 5000, "클릭수": 50, "클릭률(%)": 1.0, "ROAS(%)": 300.0,
"_accounts": {"2": acc("큰계정(새 이름)", 500, 300.0, 5000)}}),
_stored("2026-10-03", 70, None, {"지출 금액(부가세 포함)": 70}), # 계정별 저장 전에 가져온 날
]
t = ad_spend.detail_table(rows)
assert "_accounts" not in t["columns"] and "_accounts" not in t["total"] # "_" 키는 표 열·합계에 없음
assert all("_accounts" not in r["values"] for r in t["rows"]) # 화면으로도 보내지 않음
out = ad_spend.detail_tabs(rows)
tabs = out["tabs"]
assert [x["key"] for x in tabs] == ["total", "2", "1"] # 합계 → 광고비 큰 계정부터
assert [x["label"] for x in tabs] == ["합계", "큰계정(새 이름)", "작은계정"] # 이름 = 최근 날 이름
assert tabs[0]["total"] == t["total"] and len(tabs[0]["rows"]) == 3
big = tabs[1]
assert big["account_id"] == "2" and [r["date"] for r in big["rows"]] == ["2026-10-01", "2026-10-02"]
assert big["total"]["지출 금액(부가세 포함)"] == 700 and big["total"]["노출수"] == 7000
assert big["total"]["ROAS(%)"] == round((200 * 250 + 500 * 300) / 700, 2) # 광고비 가중 평균
assert [r["date"] for r in tabs[2]["rows"]] == ["2026-10-01"] # 광고를 낸 날만
assert out["accounts_missing"] == 1
def test_detail_tabs_absent_without_accounts():
rows = [_stored("2026-10-01", 100, 150.0, {"지출 금액(부가세 포함)": 100, "ROAS(%)": 150.0})]
assert ad_spend.detail_tabs(rows) == {"tabs": [], "accounts_missing": 0} # 네이버·구글·옛 메타 자료 = 탭 없음
def test_details_endpoint_returns_tabs(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")
rows = [_stored("2026-10-01", 110, 450.0, {"지출 금액(부가세 포함)": 110, "_accounts": {
"1": {"name": "본계정", "amount": 110, "roas": 450.0, "metrics": {"지출 금액(부가세 포함)": 110}}}})]
class Store:
def ad_details(self, code, start, end):
assert code == "meta"
return rows
monkeypatch.setattr(common, "require_store", lambda request: (Store(), {"email": "a@x"}))
app = FastAPI()
app.include_router(perf_router.router)
d = TestClient(app).get("/performance/api/ad-spend/meta/details?from=2026-10-01&to=2026-10-31").json()
assert d["columns"] == ["지출 금액(부가세 포함)"] and [t["label"] for t in d["tabs"]] == ["합계", "본계정"]
assert d["accounts_missing"] == 0
# ── 외화(USD) 광고 계정 — 그날 환율로 원화 환산(2026-10-16) ──
from app.modules.performance import fx # noqa: E402
FX_ROWS = [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1350.0},
{"date": "2026-10-02", "base": "USD", "quote": "KRW", "rate": 1360.5}] # 10-03 은 없음 → 10-02 값
def _fx_and_meta(insights_by_account, fx_rows=FX_ROWS, fx_status=200):
calls = {"fx": []}
def handler(req: httpx.Request) -> httpx.Response:
if req.url.host == "api.frankfurter.dev":
calls["fx"].append(req)
return httpx.Response(fx_status, json=fx_rows if fx_status == 200 else {"status": fx_status, "message": "down"})
acc = req.url.path.split("/act_")[1].split("/")[0]
return httpx.Response(200, json={"data": insights_by_account.get(acc, [])})
return handler, calls
def _usd(day, spend, value, **extra):
return {**_row(day, spend, account_currency="USD", account_name="US 계정",
action_values=[{"action_type": "omni_purchase", "value": value}]), **extra}
def test_usd_account_converted_with_daily_rate(monkeypatch):
fx.clear_cache()
handler, calls = _fx_and_meta({
"333333": [_usd("2026-10-01", "100", "400"), _usd("2026-10-03", "10.5", "0")],
"444444": [_row("2026-10-01", "50000", account_name="원화 계정")],
})
_install(monkeypatch, handler)
d1, d3 = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333,444444"), date(2026, 10, 1), date(2026, 10, 3))
q = calls["fx"][0].url.params
assert (q["base"], q["quotes"], q["to"]) == ("USD", "KRW", "2026-10-03") and q["from"] <= "2026-10-01"
assert len(calls["fx"]) == 1 # 통화마다 기간 한 번
# 10-01: USD 100 × 1,350 = 135,000원 + 원화 50,000 = 185,000 = 광고비(메타 지출은 부가세 포함 — × 1.1 없음)
# 구매 전환값 USD 400 × 1,350 = 540,000 → ROAS = 540,000 ÷ 185,000 = 291.89%
assert (d1.amount, d1.roas) == (185000, Decimal("291.89"))
assert d1.metrics["지출 금액(부가세 포함)"] == 185000 and d1.metrics["구매 전환값"] == 540000
us = d1.metrics["_accounts"]["333333"]
assert (us["amount"], us["roas"]) == (135000, 400.0) # 100 × 1,350, ROAS 는 환율과 무관(400 ÷ 100)
assert us["metrics"]["지출 금액(USD)"] == 100.0 and us["metrics"]["적용 환율(원)"] == 1350.0
assert "적용 환율(원)" not in d1.metrics["_accounts"]["444444"]["metrics"] # 원화 계정엔 없음
assert "적용 환율(원)" not in d1.metrics # 합계 표에도 없음
# 10-03: 그날 환율 없음 → 10-02 값(1,360.5). 10.5 × 1,360.5 = 14,285.25 → 14,285
assert d3.day == date(2026, 10, 3) and d3.amount == 14285
assert d3.metrics["_accounts"]["333333"]["metrics"]["적용 환율(원)"] == 1360.5
def test_usd_rate_unavailable_saves_nothing(monkeypatch):
fx.clear_cache()
handler, _calls = _fx_and_meta({"333333": [_usd("2026-10-01", "100", "0")]}, fx_status=503)
_install(monkeypatch, handler)
with pytest.raises(ApiError) as info:
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
assert "USD 광고 계정을 원화로 바꿀 환율" in str(info.value) and "503" in str(info.value) and TOKEN not in str(info.value)
def test_krw_rates_fill_cache_and_errors():
fx.clear_cache()
seen = []
def route(req):
seen.append(req)
return httpx.Response(200, json=FX_ROWS + [{"date": "x", "quote": "KRW", "rate": 1}, {"date": "2026-10-02", "quote": "JPY", "rate": 9}])
client = httpx.Client(transport=httpx.MockTransport(route))
rates = fx.krw_rates(client, "usd", date(2026, 10, 1), date(2026, 10, 4), today=date(2026, 10, 10))
assert rates == {date(2026, 10, 1): Decimal("1350.0"), date(2026, 10, 2): Decimal("1360.5"),
date(2026, 10, 3): Decimal("1360.5"), date(2026, 10, 4): Decimal("1360.5")} # 빈 날 = 앞 날 값
# 실제로 고시된 지난 날(10-01·10-02)만 기억 — 그 두 날만 다시 물으면 서버에 묻지 않는다
assert fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 2), today=date(2026, 10, 10))[date(2026, 10, 2)] == Decimal("1360.5")
assert len(seen) == 1
fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 3), today=date(2026, 10, 10)) # 10-03 은 앞 날 값이라 기억 안 함
assert len(seen) == 2
assert fx.krw_rates(client, "KRW", date(2026, 10, 1), date(2026, 10, 2)) == {date(2026, 10, 1): 1, date(2026, 10, 2): 1}
with pytest.raises(fx.FxError, match="찾지 못했습니다"): # 앞 열흘에도 없음
fx.krw_rates(client, "USD", date(2026, 11, 1), date(2026, 11, 1), today=date(2026, 11, 5))
def down(req):
raise httpx.ConnectError("boom")
with pytest.raises(fx.FxError, match="ConnectError"):
fx.krw_rates(httpx.Client(transport=httpx.MockTransport(down)), "EUR", date(2026, 10, 1), date(2026, 10, 1))
def test_detail_table_rate_total_is_weighted_average():
rows = [_stored("2026-10-01", 1000, None, {"적용 환율(원)": 1300.0}),
_stored("2026-10-02", 3000, None, {"적용 환율(원)": 1400.0}),
_stored("2026-10-03", 0, None, {"적용 환율(원)": 9999.0})] # 광고비 0 인 날은 빼고
assert ad_spend.detail_table(rows)["total"]["적용 환율(원)"] == 1375.0 # (1300×1000 + 1400×3000) ÷ 4000
def test_connection_mentions_conversion(monkeypatch):
_install(monkeypatch, lambda req: httpx.Response(200, json={"name": "US", "currency": "USD", "timezone_name": "America/Los_Angeles",
"account_status": 1}))
msg = ma.MetaAdsSource().test_connection(_ctx(account_ids="333333"))
assert "그날 환율로 원화로 바꿔 넣습니다" in msg and "가져올 수 없습니다" not in msg
+24
View File
@@ -1842,6 +1842,30 @@ class ProjectStore:
return False return False
return row is not None return row is not None
# ── Project 옵션(시스템 전체, 마이그레이션 029) — 키 하나 = 행 하나, 값 검사는 store 한 곳 ──
def get_project_options(self) -> dict[str, Any]:
"""저장된 시스템 옵션 원본 {key: value}. 029 미적용이면 {}(화면은 기본값)."""
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT key, value FROM project_options").fetchall()
except psycopg_errors.UndefinedTable:
return {}
return {r["key"]: r["value"] for r in rows}
def set_project_options(self, *, values: dict[str, Any], updated_by: str) -> None:
"""검사를 마친 값만 넣는다(store.validate_project_options). 한 트랜잭션 — 전부 아니면 전무.
029 미적용이면 psycopg_errors.UndefinedTable(라우터가 503)."""
by = store.norm_str(updated_by, lower=True)
with self._pool.connection() as conn:
with conn.transaction():
for key, value in values.items():
conn.execute(
"INSERT INTO project_options (key, value, updated_by, updated_at) VALUES (%s, %s, %s, now()) "
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, "
"updated_at = now()",
(key, Jsonb(value), by),
)
def notifier_revoke_token(self, *, token: str) -> None: def notifier_revoke_token(self, *, token: str) -> None:
with self._pool.connection() as conn: with self._pool.connection() as conn:
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL", conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
+38
View File
@@ -899,6 +899,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user),
"pj_options": _project_options(st),
"can_manage": can_manage, "can_manage": can_manage,
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"page_title": project["name"], "page_title": project["name"],
@@ -967,6 +968,43 @@ def _db_or_503(request: Request) -> Any:
return st return st
def _project_options(st: Any) -> dict[str, Any]:
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
if st is None:
return store.normalize_project_options(None)
try:
return store.normalize_project_options(st.get_project_options())
except Exception: # noqa: BLE001 — 옵션 때문에 프로젝트 화면이 안 열리면 안 된다
logger.warning("Project 옵션 읽기 실패 — 기본값 사용", exc_info=True)
return store.normalize_project_options(None)
@router.get("/api/options")
def api_get_options(request: Request) -> JSONResponse:
"""Project 옵션 창 — 시스템 전체 설정(모든 사용자에게 적용)과 내가 바꿀 수 있는지(Admin 이상)."""
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse({"options": _project_options(st), "can_edit": access.is_project_admin(user)})
@router.put("/api/options")
def api_put_options(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""시스템 Project 옵션 저장 — 수퍼관리자·Admin 만. 보낸 키만 바꾼다. 029 미적용이면 503."""
user = _require_user(request)
if not access.is_project_admin(user):
raise HTTPException(status_code=403, detail="수퍼관리자·Admin 만 바꿀 수 있습니다.")
st = _db_or_503(request)
try:
values = store.validate_project_options(payload)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
try:
st.set_project_options(values=values, updated_by=user.get("email", ""))
except UndefinedTable:
raise HTTPException(status_code=503, detail="DB 마이그레이션 029(Project 옵션)가 아직 적용되지 않았습니다.")
return JSONResponse({"options": _project_options(st)})
@router.get("/api/projects") @router.get("/api/projects")
def api_list_projects(request: Request) -> JSONResponse: def api_list_projects(request: Request) -> JSONResponse:
user = _require_user(request) user = _require_user(request)
+41
View File
@@ -375,6 +375,47 @@ def validate_time(t: Any) -> str | None:
return f"{hh:02d}:{mm:02d}" return f"{hh:02d}:{mm:02d}"
# ════════════════════════════════════════════════════════════
# Project 옵션 — 시스템 전체 설정(마이그레이션 029 project_options, 수퍼관리자·Admin 수정)
# 폰트 같은 "일반" 옵션은 브라우저별(localStorage)이라 여기 없다.
# ════════════════════════════════════════════════════════════
PROJECT_VIEWS: tuple[str, ...] = ("board", "list", "calendar", "timeline", "dashboard")
PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
}
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
"""DB 에서 읽은 값 → 화면용. 모르는 키는 버리고, 이상한 값·없는 키는 기본값(읽기는 실패하지 않는다)."""
out = dict(PROJECT_OPTION_DEFAULTS)
raw = raw or {}
if raw.get("default_view") in PROJECT_VIEWS:
out["default_view"] = raw["default_view"]
if isinstance(raw.get("board_cover"), bool):
out["board_cover"] = raw["board_cover"]
return out
def validate_project_options(payload: Any) -> dict[str, Any]:
"""저장 요청 검사 — 보낸 키만 돌려준다(일부만 바꿀 수 있게). 모르는 키·잘못된 값·빈 요청은 ValueError."""
if not isinstance(payload, dict) or not payload:
raise ValueError("바꿀 옵션이 없습니다.")
unknown = set(payload) - set(PROJECT_OPTION_DEFAULTS)
if unknown:
raise ValueError("알 수 없는 옵션입니다: " + ", ".join(sorted(unknown)))
out: dict[str, Any] = {}
if "default_view" in payload:
if payload["default_view"] not in PROJECT_VIEWS:
raise ValueError("처음 여는 탭 값이 올바르지 않습니다.")
out["default_view"] = payload["default_view"]
if "board_cover" in payload:
if not isinstance(payload["board_cover"], bool):
raise ValueError("카드 표지 값이 올바르지 않습니다.")
out["board_cover"] = payload["board_cover"]
return out
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도 # 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
@@ -1,10 +1,42 @@
{# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다.
· 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원).
· 프로젝트 화면(처음 여는 탭)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view·
data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영.
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션"> <button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
<span class="material-symbols-outlined">settings</span> <span class="material-symbols-outlined">settings</span>
</button> </button>
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title"> <dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
<form id="pj-options-form"> <form id="pj-options-form">
<h2 id="pj-options-title">Project 옵션</h2> <header class="pj-options-head">
<label for="pj-options-font">폰트</label> <h2 id="pj-options-title"><span class="material-symbols-outlined">tune</span> Project 옵션</h2>
<button type="button" class="pj-options-x" id="pj-options-x" aria-label="닫기" title="닫기">
<span class="material-symbols-outlined">close</span>
</button>
</header>
<div class="pj-options-body">
<nav class="pj-options-nav" role="tablist" aria-orientation="vertical" aria-label="옵션 분류">
<button type="button" role="tab" class="is-active" aria-selected="true" aria-controls="pj-opt-pane-general" id="pj-opt-tab-general" data-pane="general">
<span class="material-symbols-outlined">text_fields</span>일반</button>
{% if pj_admin %}
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-view" id="pj-opt-tab-view" data-pane="view" tabindex="-1">
<span class="material-symbols-outlined">space_dashboard</span>프로젝트 화면</button>
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-board" id="pj-opt-tab-board" data-pane="board" tabindex="-1">
<span class="material-symbols-outlined">view_kanban</span>보드</button>
{% endif %}
{% if user and user.is_super_admin %}
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-admin" id="pj-opt-tab-admin" data-pane="admin" tabindex="-1">
<span class="material-symbols-outlined">admin_panel_settings</span>관리자</button>
{% endif %}
</nav>
<div class="pj-options-panes">
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-general" aria-labelledby="pj-opt-tab-general" data-pane="general">
<h3>일반 <span class="pj-options-badge"><span class="material-symbols-outlined">computer</span>이 브라우저에만 적용</span></h3>
<div class="pj-options-group">
<div class="pj-options-row is-stack">
<label for="pj-options-font"><b>폰트</b><small>Project 화면 전체의 글꼴</small></label>
<select id="pj-options-font" name="font"> <select id="pj-options-font" name="font">
<option value="system">기본 시스템 폰트</option> <option value="system">기본 시스템 폰트</option>
<option value="pretendard">프리텐다드</option> <option value="pretendard">프리텐다드</option>
@@ -13,13 +45,57 @@
<option value="nanum-square-round">나눔 스퀘어 라운드</option> <option value="nanum-square-round">나눔 스퀘어 라운드</option>
</select> </select>
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div> <div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p> </div>
{% if user and user.is_super_admin %}<p class="pj-options-notice"><a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 긴급 공지 만들기·관리</a> <small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></p>{% endif %} </div>
</section>
{% if pj_admin %}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-view" aria-labelledby="pj-opt-tab-view" data-pane="view" hidden>
<h3>프로젝트 화면 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
<div class="pj-options-group">
<div class="pj-options-row is-stack">
<span class="pj-options-label" id="pj-options-view-label"><b>처음 여는 탭</b><small>왼쪽에서 프로젝트를 고르면 바로 보이는 보기</small></span>
<div class="pj-options-views" role="radiogroup" aria-labelledby="pj-options-view-label">
<label><input type="radio" name="default_view" value="board"><span class="material-symbols-outlined">view_kanban</span>보드</label>
<label><input type="radio" name="default_view" value="list"><span class="material-symbols-outlined">format_list_bulleted</span>목록</label>
<label><input type="radio" name="default_view" value="calendar"><span class="material-symbols-outlined">calendar_month</span>캘린더</label>
<label><input type="radio" name="default_view" value="timeline"><span class="material-symbols-outlined">view_timeline</span>타임라인</label>
<label><input type="radio" name="default_view" value="dashboard"><span class="material-symbols-outlined">monitoring</span>대시보드</label>
</div>
<small class="pj-options-note">왼쪽 "전체 보기"는 지금처럼 대시보드로 열립니다.</small>
</div>
</div>
</section>
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-board" aria-labelledby="pj-opt-tab-board" data-pane="board" hidden>
<h3>보드 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
<div class="pj-options-group">
<label class="pj-options-row" for="pj-options-cover">
<span class="pj-options-label"><b>카드 표지 이미지</b><small>메인 업무 설명의 첫 이미지를 보드 카드 위에 보여 줍니다</small></span>
<span class="pj-switch"><input type="checkbox" role="switch" id="pj-options-cover" name="board_cover"><span aria-hidden="true"></span></span>
</label>
</div>
</section>
{% endif %}
{% if user and user.is_super_admin %}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-admin" aria-labelledby="pj-opt-tab-admin" data-pane="admin" hidden>
<h3>관리자</h3>
<div class="pj-options-group">
<div class="pj-options-row">
<span class="pj-options-label"><b>긴급 공지</b><small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></span>
<a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 만들기·관리</a>
</div>
</div>
</section>
{% endif %}
</div>
</div>
<footer class="pj-options-foot">
<button type="button" class="pj-btn pj-options-reset" id="pj-options-reset" title="모든 옵션을 처음 값으로(저장해야 반영)">기본값으로</button>
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p> <p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
<div class="pj-options-actions">
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button> <button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
<button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button> <button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
</div> </footer>
</form> </form>
</dialog> </dialog>
<script> <script>
@@ -29,4 +105,4 @@
document.documentElement.dataset.pjFont = pf; document.documentElement.dataset.pjFont = pf;
} catch (_) {} } catch (_) {}
</script> </script>
<script src="/static/project-options.js?v=20261002g" defer></script> <script src="/static/project-options.js?v=20261016c" defer></script>
@@ -1,7 +1,7 @@
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -298,5 +298,5 @@
<script src="/static/project-goal-text.js?v=20261003d" defer></script> <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-meeting-cells.js?v=20261012a" defer></script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -207,5 +207,5 @@
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261003d" defer></script> <script src="/static/project-goal-text.js?v=20261003d" defer></script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" /> <link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -116,8 +116,13 @@
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li> <li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li> <li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li>
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li> <li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 폰트를 고르고 미리 본 뒤 <span class="pjh-ui">저장</span>을 누르면 Project 화면에 적용되고 창이 닫힙니다. <li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li> <b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
</ul> </ul>
<h3>프로젝트 제목</h3> <h3>프로젝트 제목</h3>
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p> <p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -106,5 +106,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }} "today": {{ today | tojson }}
} }
</script> </script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -108,5 +108,5 @@
}); });
})(); })();
</script> </script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host --> <!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host --> <!-- 타임라인 vis-timeline — self-host -->
@@ -29,6 +29,8 @@
data-can-manage="{{ 'true' if can_manage else 'false' }}" data-can-manage="{{ 'true' if can_manage else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}" data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}" data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
data-default-view="{{ pj_options.default_view if pj_options else 'board' }}"
data-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}"
data-me="{{ user.email }}"> data-me="{{ user.email }}">
<div class="pj-layout"> <div class="pj-layout">
@@ -470,5 +472,5 @@
</script> </script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script> <script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261015e" /> <link rel="stylesheet" href="/static/project.css?v=20261016b" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261015c" defer></script> <script src="/static/project.js?v=20261016d" defer></script>
{% endblock %} {% endblock %}
+3
View File
@@ -75,6 +75,9 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-detail-btn .material-symbols-outlined { font-size: 16px; } .perf-detail-btn .material-symbols-outlined { font-size: 16px; }
.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; } .perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; }
.perf-detail-table th, .perf-detail-table td { white-space: nowrap; } .perf-detail-table th, .perf-detail-table td { white-space: nowrap; }
/* 상세보기 [합계 | 계정…] 탭(메타 — 여러 광고 계정) */
.perf-detail-tabs { flex-wrap: wrap; margin-bottom: 10px; }
.perf-detail-tabs .perf-seg.is-active { background: var(--perf-ad); }
.perf-ad-upload-btn { margin-left: auto; } .perf-ad-upload-btn { margin-left: auto; }
.perf-kpi-pct { font-size: 26px; font-weight: 700; } .perf-kpi-pct { font-size: 26px; font-weight: 700; }
+37 -8
View File
@@ -403,7 +403,7 @@
} }
}); });
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계. // 광고 보고서 일자별 상세(네이버·구글·메타 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
root.addEventListener("click", async function (e) { root.addEventListener("click", async function (e) {
const btn = e.target.closest("[data-detail-channel]"); const btn = e.target.closest("[data-detail-channel]");
if (!btn) return; if (!btn) return;
@@ -425,15 +425,44 @@
const d = new Date(iso + "T00:00:00"); const d = new Date(iso + "T00:00:00");
return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")"; return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")";
}; };
m.body.innerHTML = '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' + const table = function (t) {
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" + const tcols = t.columns || cols;
res.rows.map(function (r) { return '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
tcols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
(t.rows || []).map(function (r) {
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" + return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>"; tcols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' + }).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("") + tcols.map(function (c) { return '<td class="perf-num">' + cell((t.total || {})[c]) + "</td>"; }).join("") +
"</tr></tfoot></table></div>" + "</tr></tfoot></table></div>";
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>'; };
const foot = '<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
const tabs = res.tabs || [];
if (tabs.length < 2) { m.body.innerHTML = table(res) + foot; return; }
// 여러 광고 계정을 합치는 채널(메타) — [합계 | 계정…] 탭. 계정 탭 = 그 계정이 광고를 낸 날만.
const missing = res.accounts_missing
? '<p class="perf-notice">' + fmt(res.accounts_missing) + "일은 계정별 자료가 없어 합계 탭에만 있습니다 — [" + esc(name) +
" 광고 불러오기]로 그 기간을 다시 가져오면 계정별로 나뉩니다.</p>"
: "";
m.body.innerHTML = '<div class="perf-quick perf-detail-tabs" role="tablist" aria-label="계정">' +
tabs.map(function (t, i) {
return '<button type="button" class="perf-seg' + (i ? "" : " is-active") + '" role="tab" aria-selected="' + (i ? "false" : "true") +
'" data-tab="' + i + '"' + (t.account_id ? ' title="act_' + esc(t.account_id) + '"' : "") + ">" + esc(t.label) + "</button>";
}).join("") + '</div><div class="perf-detail-tab-body"></div>' + missing + foot;
const bodyEl = m.body.querySelector(".perf-detail-tab-body");
const show = function (i) {
m.body.querySelectorAll(".perf-detail-tabs [data-tab]").forEach(function (b) {
const on = Number(b.dataset.tab) === i;
b.classList.toggle("is-active", on);
b.setAttribute("aria-selected", on ? "true" : "false");
});
bodyEl.innerHTML = table(tabs[i]) + (i ? '<p class="perf-muted">계정마다 따로 반올림해 계정 광고비의 합이 합계 탭과 1원 다를 수 있습니다.</p>' : "");
};
m.body.querySelector(".perf-detail-tabs").addEventListener("click", function (ev) {
const b = ev.target.closest("[data-tab]");
if (b) show(Number(b.dataset.tab));
});
show(0);
} catch (err) { } catch (err) {
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>"; m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} }
+111 -13
View File
@@ -5,36 +5,134 @@
button.dataset.bound = "1"; button.dataset.bound = "1";
const names = { system: null, pretendard: "Pretendard Variable", "nanum-square": "NanumSquare", const names = { system: null, pretendard: "Pretendard Variable", "nanum-square": "NanumSquare",
"nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" }; "nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" };
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
const FONT_DEFAULT = "system";
const SYS_DEFAULTS = { default_view: "board", board_cover: true }; // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게
const form = document.getElementById("pj-options-form");
const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview"); const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview");
const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save"); const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save");
const cancel = document.getElementById("pj-options-cancel"); const cancel = document.getElementById("pj-options-cancel"), closeX = document.getElementById("pj-options-x");
function current() { const v = document.documentElement.dataset.pjFont; return Object.hasOwn(names, v) ? v : "system"; } const reset = document.getElementById("pj-options-reset");
const tabs = Array.from(dialog.querySelectorAll(".pj-options-nav [role=tab]"));
const panes = Array.from(dialog.querySelectorAll(".pj-options-pane"));
// 처음 여는 탭·카드 표지 = 시스템 전체 설정(서버, 모든 사용자) — 수퍼관리자·Admin 창에만 있다(_options.html).
// 없으면 폰트(이 브라우저)만 다룬다.
const cover = document.getElementById("pj-options-cover");
const views = form.elements.default_view || null;
const sysControls = [cover].concat(Array.from(views || [])).filter(Boolean);
const localControls = [select, cancel, closeX, reset];
let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장)
let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다
function setError(msg) { error.textContent = msg || ""; error.hidden = !msg; }
async function request(method, body) {
const opts = { method: method, headers: { "Content-Type": "application/json" } };
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch("/project/api/options", opts);
let data = null;
try { data = await res.json(); } catch (_) {}
if (!res.ok) throw new Error((data && typeof data.detail === "string" && data.detail) || res.statusText || "오류");
return data || {};
}
function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; }
function fillSys(o) {
if (views) views.value = o.default_view;
if (cover) cover.checked = o.board_cover;
}
function paint() { function paint() {
const font = names[select.value]; const font = names[select.value];
preview.style.fontFamily = font ? '"' + font + '", sans-serif' : "var(--pj-system-font)"; preview.style.fontFamily = font ? '"' + font + '", sans-serif' : "var(--pj-system-font)";
} }
function showPane(name, focus) {
tabs.forEach(function (t) {
const on = t.dataset.pane === name;
t.classList.toggle("is-active", on);
t.setAttribute("aria-selected", on ? "true" : "false");
t.tabIndex = on ? 0 : -1;
if (on && focus) t.focus();
});
panes.forEach(function (p) { p.hidden = p.dataset.pane !== name; });
}
function busy(on) {
save.disabled = on;
localControls.forEach(function (c) { c.disabled = on; });
sysControls.forEach(function (c) { c.disabled = on || !sys; });
}
function close() { if (!save.disabled) dialog.close(); }
async function loadSys() {
if (!sysControls.length) return;
const seq = ++openSeq;
sys = null; busy(false); // 읽는 동안 시스템 칸은 잠금
try {
const data = await request("GET");
if (seq !== openSeq) return;
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
fillSys(sys);
} catch (err) {
if (seq !== openSeq) return;
setError("모든 사용자 설정을 불러오지 못했습니다(" + err.message + "). 폰트만 저장됩니다.");
}
if (!save.disabled) busy(false);
}
button.addEventListener("click", function () { button.addEventListener("click", function () {
select.value = current(); error.hidden = true; paint(); dialog.showModal(); select.focus(); select.value = currentFont(); fillSys(SYS_DEFAULTS); paint(); setError("");
showPane(tabs[0].dataset.pane); dialog.showModal(); tabs[0].focus();
loadSys();
});
dialog.querySelector(".pj-options-nav").addEventListener("click", function (e) {
const t = e.target.closest("[role=tab]");
if (t) showPane(t.dataset.pane);
});
// 분류 목록 — 위/아래 화살표로 이동(데스크톱 프로그램 설정 창처럼)
dialog.querySelector(".pj-options-nav").addEventListener("keydown", function (e) {
const i = tabs.indexOf(document.activeElement);
if (i < 0 || (e.key !== "ArrowDown" && e.key !== "ArrowUp")) return;
e.preventDefault();
showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true);
}); });
select.addEventListener("change", paint); select.addEventListener("change", paint);
cancel.addEventListener("click", function () { if (!save.disabled) dialog.close(); }); reset.addEventListener("click", function () {
select.value = FONT_DEFAULT; paint();
if (sys) fillSys(SYS_DEFAULTS);
});
cancel.addEventListener("click", close);
closeX.addEventListener("click", close);
dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); }); dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); });
dialog.addEventListener("close", function () { button.focus(); }); dialog.addEventListener("close", function () { openSeq++; button.focus(); });
document.getElementById("pj-options-form").addEventListener("submit", async function (e) { form.addEventListener("submit", async function (e) {
e.preventDefault(); if (save.disabled) return; e.preventDefault(); if (save.disabled) return;
const value = select.value, font = names[value]; const fontValue = select.value, font = names[fontValue];
if (!Object.hasOwn(names, value)) return; if (!Object.hasOwn(names, fontValue)) return;
save.disabled = select.disabled = cancel.disabled = true; error.hidden = true; // 시스템 옵션은 바뀐 키만 보낸다(그대로면 서버에 쓰지 않음)
const sysChanges = {};
if (sys) {
if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value;
if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked;
}
busy(true); setError("");
try { try {
if (font && document.fonts) { if (font && document.fonts) {
const loaded = await Promise.all([document.fonts.load('400 14px "' + font + '"', "가나다 Project"), document.fonts.load('700 14px "' + font + '"', "가나다 Project")]); const loaded = await Promise.all([document.fonts.load('400 14px "' + font + '"', "가나다 Project"), document.fonts.load('700 14px "' + font + '"', "가나다 Project")]);
if (loaded.some(function (list) { return !list.length; })) throw new Error("폰트를 불러오지 못했습니다. 다시 시도해 주세요."); if (loaded.some(function (list) { return !list.length; })) throw new Error("폰트를 불러오지 못했습니다. 다시 시도해 주세요.");
} }
localStorage.setItem("pj_font", value); const changed = Object.keys(sysChanges);
document.documentElement.dataset.pjFont = value; if (changed.length) {
const data = await request("PUT", sysChanges);
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
}
if (fontValue !== currentFont()) changed.push("font");
localStorage.setItem("pj_font", fontValue);
document.documentElement.dataset.pjFont = fontValue;
// project.js 가 듣는다 — 보드 표지가 바뀌면 보던 보드를 다시 그린다(다른 사용자는 다음에 화면을 열 때부터).
if (changed.length) {
window.dispatchEvent(new CustomEvent("pj-options-change", {
detail: { options: Object.assign({ font: fontValue }, sys || {}), changed: changed },
}));
}
window.dispatchEvent(new Event("resize")); window.dispatchEvent(new Event("resize"));
dialog.close(); dialog.close();
} catch (err) { error.textContent = "설정을 저장하지 못했습니다. " + err.message; error.hidden = false; } } catch (err) { setError("설정을 저장하지 못했습니다. " + err.message); }
finally { save.disabled = select.disabled = cancel.disabled = false; } finally { busy(false); }
}); });
})(); })();
+61 -7
View File
@@ -554,6 +554,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
.pj-hovertip.is-below { transform: translate(-50%, 0); } .pj-hovertip.is-below { transform: translate(-50%, 0); }
.pj-hovertip.is-below::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: #1e1f21; } .pj-hovertip.is-below::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: #1e1f21; }
.pj-hovertip[hidden] { display: none; } .pj-hovertip[hidden] { display: none; }
/* 모달 대화창(showModal) 안의 말풍선은 popover(브라우저 맨 위 층)로 띄운다 — 브라우저 기본 popover 모양(가운데 배치·테두리·스크롤)을 지운다 */
.pj-hovertip[popover] { inset: auto; margin: 0; border: 0; overflow: visible; }
@keyframes pj-tip-in { from { opacity: 0; } to { opacity: 1; } } @keyframes pj-tip-in { from { opacity: 0; } to { opacity: 1; } }
/* ── 달력 (휴가 모듈과 동일한 월간 그리드 룩) ── */ /* ── 달력 (휴가 모듈과 동일한 월간 그리드 룩) ── */
@@ -3131,15 +3133,67 @@ html[data-pj-font="pretendard"] { --pj-font: "Pretendard Variable", var(--pj-sys
html[data-pj-font="nanum-square"] { --pj-font: "NanumSquare", var(--pj-system-font); } html[data-pj-font="nanum-square"] { --pj-font: "NanumSquare", var(--pj-system-font); }
html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); } html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); }
html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); } html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); }
.pj-options-dialog { width: min(440px, calc(100vw - 40px)); box-sizing: border-box; padding: 24px; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; } /* ── Project 옵션 대화창(_options.html) — 데스크톱 프로그램 설정 창처럼 왼쪽 분류 | 오른쪽 설정 ── */
.pj-options-dialog { width: min(720px, calc(100vw - 40px)); max-height: min(600px, calc(100vh - 40px)); box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; }
.pj-options-dialog[open] { display: flex; }
.pj-options-dialog::backdrop { background: #0005; } .pj-options-dialog::backdrop { background: #0005; }
.pj-options-dialog h2 { margin: 0 0 22px; font-size: 20px; font-weight: 500; } .pj-options-dialog form { display: flex; flex-direction: column; width: 100%; min-height: 0; }
.pj-options-dialog label { display: block; margin-bottom: 8px; } .pj-options-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 14px 20px; border-bottom: 1px solid var(--pj-border); }
.pj-options-head h2 { display: flex; align-items: center; gap: 8px; margin: 0; font-size: 18px; font-weight: 500; }
.pj-options-head h2 .material-symbols-outlined { font-size: 22px; color: var(--pj-accent); }
.pj-options-x { display: inline-flex; padding: 4px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; }
.pj-options-x:hover { background: #f1f2f4; color: var(--pj-ink); }
.pj-options-body { display: flex; flex: 1; min-height: 380px; overflow: hidden; }
.pj-options-nav { flex: 0 0 180px; display: flex; flex-direction: column; gap: 2px; padding: 12px 8px; background: #f7f8fa; border-right: 1px solid var(--pj-border); }
.pj-options-nav button { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border: 0; border-radius: 6px; background: none; color: #3d3f42; font: inherit; font-size: 14px; text-align: left; cursor: pointer; }
.pj-options-nav button .material-symbols-outlined { font-size: 20px; color: #6d6e6f; }
.pj-options-nav button:hover { background: #eceef1; }
.pj-options-nav button.is-active { background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; }
.pj-options-nav button.is-active .material-symbols-outlined { color: var(--pj-accent); }
.pj-options-nav button:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: -2px; }
.pj-options-panes { flex: 1; min-width: 0; padding: 20px 24px; overflow-y: auto; }
.pj-options-pane h3 { display: flex; align-items: center; gap: 10px; margin: 0 0 14px; font-size: 15px; font-weight: 600; }
/* 설정이 어디에 적용되나 — 이 브라우저(회색) · 모든 사용자(보라) */
.pj-options-badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px 2px 6px; border-radius: 999px; background: #f1f2f4; color: #5f6368; font-size: 11.5px; font-weight: 500; }
.pj-options-badge .material-symbols-outlined { font-size: 15px; }
.pj-options-badge.is-global { background: var(--pj-accent-tint); color: var(--pj-accent-dark); }
.pj-options-group { border: 1px solid var(--pj-border); border-radius: 8px; }
.pj-options-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 16px; }
.pj-options-row + .pj-options-row { border-top: 1px solid var(--pj-border); }
.pj-options-row.is-stack { flex-direction: column; align-items: stretch; gap: 10px; }
label.pj-options-row[for] { cursor: pointer; }
.pj-options-row > label, .pj-options-label { display: flex; flex-direction: column; gap: 3px; font-size: 14px; }
.pj-options-row > label b, .pj-options-label b { font-weight: 500; }
.pj-options-row small, .pj-options-note { font-size: 12px; color: var(--pj-ink-soft); }
.pj-options-dialog select { width: 100%; padding: 9px; border: 1px solid #d8dce2; border-radius: 6px; font: inherit; } .pj-options-dialog select { width: 100%; padding: 9px; border: 1px solid #d8dce2; border-radius: 6px; font: inherit; }
.pj-options-preview { padding: 18px 12px; margin-top: 16px; border: 1px solid #e5e6e8; border-radius: 6px; font-size: 16px; line-height: 1.7; } .pj-options-preview { padding: 16px 12px; border: 1px solid #e5e6e8; border-radius: 6px; background: #fcfcfd; font-size: 16px; line-height: 1.7; }
.pj-options-dialog p { font-size: 12px; color: var(--pj-ink-soft); } /* 처음 여는 탭 — 아이콘 카드 5개 중 하나 */
.pj-options-dialog .pj-options-error { color: #c22b10; } .pj-options-views { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; }
.pj-options-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 22px; } .pj-options-views label { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 4px 10px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; cursor: pointer; transition: border-color .12s, background .12s; }
.pj-options-views label .material-symbols-outlined { font-size: 26px; color: #6d6e6f; }
.pj-options-views label:hover { border-color: var(--pj-accent); }
.pj-options-views input { position: absolute; opacity: 0; pointer-events: none; }
.pj-options-views label:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; box-shadow: 0 0 0 1px var(--pj-accent) inset; }
.pj-options-views label:has(input:checked) .material-symbols-outlined { color: var(--pj-accent); }
.pj-options-views label:has(input:focus-visible) { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
/* 켜기/끄기 스위치 */
.pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; }
.pj-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
.pj-switch span { position: absolute; inset: 0; border-radius: 999px; background: #c9ccd1; transition: background .15s; pointer-events: none; }
.pj-switch span::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px #0003; transition: transform .15s; }
.pj-switch input:checked + span { background: var(--pj-accent); }
.pj-switch input:checked + span::after { transform: translateX(18px); }
.pj-switch input:focus-visible + span { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
.pj-switch input:disabled + span { opacity: .5; }
.pj-options-foot { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--pj-border); background: #fafbfc; }
.pj-options-foot .pj-options-reset { margin-right: auto; }
.pj-options-dialog .pj-options-error { margin: 0 6px 0 0; font-size: 12px; color: #c22b10; }
@media (max-width: 560px) {
.pj-options-body { flex-direction: column; min-height: 0; overflow-y: auto; }
.pj-options-nav { flex: none; flex-direction: row; overflow-x: auto; border-right: 0; border-bottom: 1px solid var(--pj-border); }
.pj-options-nav button { white-space: nowrap; }
.pj-options-views { grid-template-columns: repeat(3, 1fr); }
}
.pj-goal-format { position: fixed; z-index: 1200; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 4px 6px; max-width: calc(100vw - 16px); box-sizing: border-box; border: 1px solid var(--pj-border); border-radius: 8px; box-shadow: 0 4px 16px #0002; background: #fff; color: var(--pj-ink); font-family: var(--pj-font); font-size: 12px; } .pj-goal-format { position: fixed; z-index: 1200; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 4px 6px; max-width: calc(100vw - 16px); box-sizing: border-box; border: 1px solid var(--pj-border); border-radius: 8px; box-shadow: 0 4px 16px #0002; background: #fff; color: var(--pj-ink); font-family: var(--pj-font); font-size: 12px; }
.pj-goal-format[hidden], .pj-goal-color-grid[hidden] { display: none; } .pj-goal-format[hidden], .pj-goal-color-grid[hidden] { display: none; }
.pj-goal-format-group { display: inline-flex; align-items: center; gap: 2px; } .pj-goal-format-group { display: inline-flex; align-items: center; gap: 2px; }
+43 -10
View File
@@ -3419,6 +3419,9 @@
// isPAdmin = Admin 이상(남이 만든 섹션도 삭제). // isPAdmin = Admin 이상(남이 만든 섹션도 삭제).
const isPro = root.dataset.isPro === "true"; const isPro = root.dataset.isPro === "true";
const isPAdmin = root.dataset.isPadmin === "true"; const isPAdmin = root.dataset.isPadmin === "true";
// 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔.
// 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래).
let boardCover = root.dataset.boardCover !== "0";
const me = (root.dataset.me || "").toLowerCase(); const me = (root.dataset.me || "").toLowerCase();
// 섹션 삭제 — Admin 이상은 누구 것이든, 그 밖은 만든 사람만. created_by 없으면 서버가 최종 판정. // 섹션 삭제 — Admin 이상은 누구 것이든, 그 밖은 만든 사람만. created_by 없으면 서버가 최종 판정.
function canDelete(createdBy) { function canDelete(createdBy) {
@@ -3575,19 +3578,22 @@
} }
let timeline = null; let timeline = null;
// 기본 보기는 항상 보드(왼쪽 프로젝트 클릭 등으로 들어오면 보드). // 기본 보기는 시스템 Project 옵션의 "처음 여는 탭"(서버 project_options → data-default-view, 없으면 보드) —
// 왼쪽 프로젝트 클릭 등으로 들어오면 그 탭.
// 예외: 달력 이전/다음달 이동은 페이지를 통째로 새로고침하므로(?y=&m=), // 예외: 달력 이전/다음달 이동은 페이지를 통째로 새로고침하므로(?y=&m=),
// 그때만 마지막으로 보던 뷰를 되살린다 — 안 그러면 달력을 넘기다가 // 그때만 마지막으로 보던 뷰를 되살린다 — 안 그러면 달력을 넘기다가
// 보드로 튕겨나간다. // 처음 탭으로 튕겨나간다.
// 왼쪽 "전체 보기"(?scope=all)로 들어오면 기본 보기는 대시보드. // 왼쪽 "전체 보기"(?scope=all)로 들어오면 기본 보기는 대시보드(옵션과 무관).
const VIEW_KEY = "pj_view"; const VIEW_KEY = "pj_view";
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
let currentView = "board"; let currentView = "board";
try { try {
const qs = new URLSearchParams(location.search); const qs = new URLSearchParams(location.search);
const saved = localStorage.getItem(VIEW_KEY); const saved = localStorage.getItem(VIEW_KEY);
if ((qs.has("y") || qs.has("m")) && saved && const preferred = root.dataset.defaultView; // 시스템 옵션(서버가 넣어 줌)
["board", "list", "calendar", "timeline", "dashboard"].indexOf(saved) >= 0) currentView = saved; if ((qs.has("y") || qs.has("m")) && saved && VIEWS.indexOf(saved) >= 0) currentView = saved;
else if (isPro && qs.get("scope") === "all") currentView = "dashboard"; else if (isPro && qs.get("scope") === "all") currentView = "dashboard";
else if (qs.get("embed") !== "1" && VIEWS.indexOf(preferred) >= 0) currentView = preferred; // 업무 창 패널(iframe)은 그대로 보드
} catch (_) {} } catch (_) {}
// ── 프로젝트 스코프 — 아사나처럼 기본은 "이 프로젝트만", "전체 프로젝트"로 // ── 프로젝트 스코프 — 아사나처럼 기본은 "이 프로젝트만", "전체 프로젝트"로
@@ -3706,6 +3712,14 @@
if (!btn) return; if (!btn) return;
selectView(btn.dataset.view); selectView(btn.dataset.view);
}); });
// Project 옵션 저장 — 보드 표지 켜기/끄기는 보고 있는 보드에 바로 반영(다른 사용자는 다음에 화면을 열 때)
window.addEventListener("pj-options-change", function (e) {
const d = e.detail || {}, changed = d.changed || [], opts = d.options || {};
if (typeof opts.default_view === "string") root.dataset.defaultView = opts.default_view;
if (changed.indexOf("board_cover") < 0 || typeof opts.board_cover !== "boolean") return;
boardCover = opts.board_cover;
if (currentView === "board") renderBoard();
});
// 서버가 그린 기본 탭(보드)과 기억된 탭이 다르면 화면을 맞춰준다. // 서버가 그린 기본 탭(보드)과 기억된 탭이 다르면 화면을 맞춰준다.
if (currentView !== "board") { if (currentView !== "board") {
tabs.querySelectorAll(".pj-tab").forEach(function (t) { tabs.querySelectorAll(".pj-tab").forEach(function (t) {
@@ -5935,8 +5949,8 @@
const showProjTag = viewScope === "all" || t.project_id !== projectId; const showProjTag = viewScope === "all" || t.project_id !== projectId;
// 카드 윗부분(배지·제목·담당자/마감일/세부 작업 줄)은 .pj-card-head 로 묶는다 — // 카드 윗부분(배지·제목·담당자/마감일/세부 작업 줄)은 .pj-card-head 로 묶는다 —
// 세부 작업을 펼쳐 컬럼을 스크롤하면 이 부분이 컬럼 맨 위에 고정된다(CSS sticky). // 세부 작업을 펼쳐 컬럼을 스크롤하면 이 부분이 컬럼 맨 위에 고정된다(CSS sticky).
// 설명에 이미지가 있으면 첫 이미지를 카드 위에(아사나 카드 표지) // 설명에 이미지가 있으면 첫 이미지를 카드 위에(아사나 카드 표지) — Project 옵션 "카드 표지 이미지"로 끌 수 있다
const cover = cardCoverSrc(t.description); const cover = boardCover ? cardCoverSrc(t.description) : "";
card.classList.toggle("has-cover", !!cover); card.classList.toggle("has-cover", !!cover);
card.innerHTML = card.innerHTML =
(cover ? '<div class="pj-card-cover"><img src="' + escapeHtml(cover) + '" alt="" loading="lazy" draggable="false"></div>' : "") + (cover ? '<div class="pj-card-cover"><img src="' + escapeHtml(cover) + '" alt="" loading="lazy" draggable="false"></div>' : "") +
@@ -9805,7 +9819,25 @@
function initHoverTips() { function initHoverTips() {
let tipEl = null; let tipEl = null;
let shown = false; let shown = false;
function show(text, x, y) { // 모달 대화창(dialog.showModal — Project 옵션 등)은 브라우저 맨 위 층(top layer)에 떠서 body 의 말풍선이
// z-index 와 상관없이 그 뒤에 가려진다. 그 안에서는 말풍선을 popover 로 띄워 같은 층, 대화창보다 위에 둔다.
function inModal(target) {
const dlg = target.closest("dialog[open]");
if (!dlg) return false;
try { return dlg.matches(":modal"); } catch (_) { return true; }
}
function topLayer(on) {
if (typeof tipEl.showPopover !== "function") return; // popover 미지원 브라우저 — 예전처럼
const open = tipEl.hasAttribute("popover") && tipEl.matches(":popover-open");
if (on) {
if (!tipEl.hasAttribute("popover")) tipEl.setAttribute("popover", "manual");
if (!open) tipEl.showPopover();
} else if (tipEl.hasAttribute("popover")) {
if (open) tipEl.hidePopover();
tipEl.removeAttribute("popover");
}
}
function show(text, x, y, modal) {
if (!tipEl) { if (!tipEl) {
tipEl = document.createElement("div"); tipEl = document.createElement("div");
tipEl.className = "pj-hovertip"; tipEl.className = "pj-hovertip";
@@ -9813,6 +9845,7 @@
} }
tipEl.textContent = text; tipEl.textContent = text;
tipEl.hidden = false; tipEl.hidden = false;
topLayer(!!modal);
// 화면 가장자리 보정 — 좌우로 넘치면 말풍선만 안쪽으로 밀고 꼬리는 // 화면 가장자리 보정 — 좌우로 넘치면 말풍선만 안쪽으로 밀고 꼬리는
// 커서를 계속 가리키게(--pj-tip-shift). // 커서를 계속 가리키게(--pj-tip-shift).
// 늘 커서 **위**에 — 마우스 화살표(핫스팟에서 아래로 약 20px)에 가려지지 않게. 화면 맨 위(회의록 머리 버튼 등)라 // 늘 커서 **위**에 — 마우스 화살표(핫스팟에서 아래로 약 20px)에 가려지지 않게. 화면 맨 위(회의록 머리 버튼 등)라
@@ -9829,7 +9862,7 @@
tipEl.style.left = cx + "px"; tipEl.style.left = cx + "px";
tipEl.style.top = (below ? y + 28 : roomy ? y - 10 : y - 2) + "px"; tipEl.style.top = (below ? y + 28 : roomy ? y - 10 : y - 2) + "px";
} }
function hide() { shown = false; if (tipEl) tipEl.hidden = true; } function hide() { shown = false; if (tipEl) { topLayer(false); tipEl.hidden = true; } }
document.addEventListener("mouseover", function (e) { document.addEventListener("mouseover", function (e) {
const el = e.target.closest ? e.target.closest("[title]") : null; const el = e.target.closest ? e.target.closest("[title]") : null;
if (!el) return; if (!el) return;
@@ -9841,7 +9874,7 @@
const target = e.target.closest ? e.target.closest("[data-tip]") : null; const target = e.target.closest ? e.target.closest("[data-tip]") : null;
if (!target || !target.dataset.tip) { if (shown) hide(); return; } if (!target || !target.dataset.tip) { if (shown) hide(); return; }
shown = true; shown = true;
show(target.dataset.tip, e.clientX, e.clientY); show(target.dataset.tip, e.clientX, e.clientY, inModal(target));
}); });
// 누르거나 스크롤하면 숨긴다 — 클릭으로 요소가 다시 그려지면 말풍선만 // 누르거나 스크롤하면 숨긴다 — 클릭으로 요소가 다시 그려지면 말풍선만
// 허공에 남는 일이 없게. // 허공에 남는 일이 없게.
+14
View File
@@ -150,6 +150,20 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT COUNT(*) FROM
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_028_followers_exclude_assignee.sql docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_028_followers_exclude_assignee.sql
``` ```
## Project 옵션(시스템 전체 설정) 마이그레이션 (029)
029는 `project_options` 테이블만 추가한다(키 하나 = 행 하나, 기존 값 변경 없음, 다시 실행 가능). 수퍼관리자·Admin 이 Project 옵션 창에서
바꾸는 "처음 여는 탭"·"보드 카드 표지"를 모든 사용자에게 적용하는 저장소다. 행이 없으면 기본값(보드·표지 켬).
미적용이면 화면은 기본값으로 열리고, 옵션 저장만 503 안내(폰트는 브라우저 저장이라 그대로 동작).
되돌리기 = `DROP TABLE project_options;`(사용자 확인 후 — 저장한 시스템 설정만 사라지고 기본값으로).
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_029_$(date +%Y%m%d%H%M).sql
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_029_project_options.sql
docker exec postgres-db psql -U postgres -d project_db -c "SELECT key, value, updated_by, updated_at FROM project_options;"
```
## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002) ## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002)
002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를 002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를
+37 -2
View File
@@ -378,7 +378,7 @@
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로. 머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`): - **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`. 열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력. - **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007)·**메타 = 메타 마케팅 API**(2026-10-16, 새 마이그레이션 없음) — 아래 "광고 API 연동".
- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양, - **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양,
돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단). 돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단).
- **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로 - **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로
@@ -397,6 +397,38 @@
ROAS = 전환 가치 ÷ 비용(부가세 별도) × 100(소수 둘째, 구글 화면 값 그대로), 항목에 광고비(부가세 포함)·비용(부가세 별도) 둘 다, ROAS = 전환 가치 ÷ 비용(부가세 별도) × 100(소수 둘째, 구글 화면 값 그대로), 항목에 광고비(부가세 포함)·비용(부가세 별도) 둘 다,
항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`). 항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내. 통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내.
- **메타 광고**(`ad_sources/meta_ads.py`, 2026-10-16): 입력 = 광고 계정 ID(여러 개 — 줄바꿈·쉼표, `act_` 있어도 됨, 30개까지, 비밀 아님 여러 줄) ·
액세스 토큰(비밀 — `ads_read` 권한, 비즈니스 설정 → 시스템 사용자 토큰 권장(만료 없음), 토큰 주인을 각 광고 계정에 배정) ·
앱 시크릿(비밀, 선택 — 앱에서 "API 호출에 앱 시크릿 필요"를 켰을 때만, `appsecret_proof` = HMAC-SHA256(토큰)) · API 버전(기본 `v26.0`).
조회 = `GET graph.facebook.com/{버전}/act_{계정}/insights` `level=account`·`time_increment=1`·`time_range`, 계정마다 `paging.next` 따라감
(다음 쪽 주소가 graph.facebook.com 이 아니면 중단 — 토큰을 다른 곳에 보내지 않음). 토큰은 메타 문서대로 `access_token` 매개변수
(주소에 들어가므로 오류 문구에 주소를 넣지 않고, httpx INFO 요청 로그는 켜지 않는다). 여러 계정은 날짜별로 더함, 날짜는 광고 계정 시간대.
기여(어트리뷰션)는 메타가 광고 관리자 설정을 따른다(2025-06 부터 API 기여 매개변수 무시) — 광고 관리자 화면 값과 같음.
금액 = 지출 금액(`spend`) 그대로 원 반올림 — **메타 지출 금액은 이미 부가세 포함**(2026-10-16 사용자 확인, × 1.1 은 구글만), ROAS = 구매 전환값 ÷ 지출 금액 × 100
(= 광고 관리자 "구매 ROAS"). 구매 전환값·구매수 = `action_values`·`actions` 에서 `omni_purchase` → `purchase` → 픽셀 구매 순서로 처음 있는 것 하나
(메타가 같은 구매를 여러 종류에 같은 값으로 겹쳐 주므로 더하지 않음). 항목 `metrics` = 지출 금액(부가세 포함 = 광고비)·노출수·클릭수·
클릭률(%)·링크 클릭·구매수·구매 전환값·ROAS(%) → 메타 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
**외화 계정**(2026-10-16, 사용자 요청 — USD 계정 1314634672357695): 원화가 아닌 계정은 지출 금액·구매 전환값을 **그날 환율로 원화 환산**한 뒤
다른 계정과 더한다(`fx.py` `krw_rates` — Frankfurter v2 `https://api.frankfurter.dev/v2/rates?base=USD&quotes=KRW&from=&to=`, API 키 없음,
여러 중앙은행 고시 환율 종합(blended)이라 주말 포함 매일 있음, 서울외국환중개 매매기준율과는 조금 다를 수 있음). 그날 값이 없으면 앞 10일 안 가장 가까운 날 값,
그래도 없거나 환율 서버 장애면 그 회차는 저장하지 않음(일부만 환산 금지, 오류 안내). 통화마다 기간 한 번 요청, 2일 이상 지난 날 환율은 프로세스 안 캐시.
광고비 = 지출 × 환율(메타 지출은 부가세 포함), ROAS 는 비율이라 환율과 무관. 계정 탭에 `지출 금액(USD)`·`적용 환율(원)`(합계 줄 = 광고비 가중 평균).
오류 코드 안내(`_HINTS`): 190 = 토큰 만료·무효(상태 "Token 만료"), 200·10 = 권한(ads_read·계정 배정),
100·803 = 계정 ID, 4·17·613·80000·80004 = 호출 한도, 2635 = 버전 종료. 연결 테스트 = 계정마다 이름·통화·시간대·상태.
**권한 오류 진단**(2026-10-16, 실제로 `(#200) Ad account owner has NOT grant ads_management or ads_read permission` 발생): 연결 테스트가
권한 오류를 받으면 메타에 ① `debug_token`(같은 토큰 — 앱·만료·`scopes`·`granular_scopes.target_ids`, 안 되면 `me/permissions`)
② `me/adaccounts`(이 토큰으로 보이는 계정)를 물어 원인 하나를 짚는다(`_diagnose`): ads_read 없음 → 토큰 재발급 /
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
**상세보기 계정별 탭**(2026-10-16): 메타 머리글 상세보기 = [합계 | 계정…] 탭. 가져올 때 그날 메타 행 `metrics` 에 계정별 값을
예약 키 `_accounts`(`ad_sources.base.ACCOUNTS_KEY` — `{계정 ID: {name, amount, roas, metrics}}`, 이름 = insights `account_name`)로 함께 저장
(새 마이그레이션 없음). `ad_spend.detail_table` 은 `_` 로 시작하는 키를 표 열·합계·화면 값에서 뺀다. `ad_spend.detail_tabs` = 합계 탭 +
계정 탭(그 계정이 광고를 낸 날만, 이름 = 가장 최근 날 이름, 순서 = 기간 광고비 큰 계정부터) + `accounts_missing`(계정별 값 없이 광고비만 있는 날 —
계정별 저장 전에 가져온 날, 다시 불러오면 생김, 화면 안내). 계정마다 따로 반올림해 계정 광고비 합이 합계와 1원 다를 수 있다.
계정별 값이 없는 채널(네이버·구글)은 `tabs: []` → 예전 그대로 표 하나.
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
연결 테스트 문구는 **[진단]을 맨 앞에**, 메타 원문은 짧게(긴 안내 주소 뺌) 뒤에. 광고 연동 오류 문구 길이 한도는 `ad_sync.AD_MESSAGE_MAX`(1200자,
비밀값 가린 뒤) — 예전엔 공용 기본 300자에서 잘려 진단이 "[진…" 으로 끊겼다.
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도), - **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값. 기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일, - **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
@@ -408,7 +440,7 @@
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG), [총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내). 월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태 - **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 — (정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고·메타 광고 —
설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`). 설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`).
## 8. 테스트 ## 8. 테스트
@@ -421,3 +453,6 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest
동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다. 동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키), `tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키),
광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증. 광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증.
`tests/test_meta_ads.py` — 메타 광고 입력 검사(계정 ID 여러 개·토큰·버전), 요청 매개변수(기간·level·appsecret_proof·버전), 여러 계정 날짜별 합산·
쪽 넘김(메타 밖 주소 거부), 구매 값 겹침 처리·광고비 = 지출 그대로(× 1.1 없음)·ROAS·항목, 외화 환율·366일, 오류 코드 안내·토큰 미노출, 연결 테스트 문구,
실제 fetch_days → AdSyncService 저장·상태·토큰 가림을 가짜 메타 서버로 검증.
+15
View File
@@ -25,6 +25,21 @@
`project.css`의 `--pj-font`만 변경하므로 다른 ERP 화면은 영향을 받지 않으며 아이콘·코드 고정폭 폰트는 유지한다. `project.css`의 `--pj-font`만 변경하므로 다른 ERP 화면은 영향을 받지 않으며 아이콘·코드 고정폭 폰트는 유지한다.
폰트는 `static/vendor/project-fonts/`에 원본·저작권/OFL을 함께 보관하고 `project-fonts.css`에서 선언한다(외부 CDN 없음). 폰트는 `static/vendor/project-fonts/`에 원본·저작권/OFL을 함께 보관하고 `project-fonts.css`에서 선언한다(외부 CDN 없음).
저장 시 400/700 글꼴 로딩을 확인하고, 실패하면 이전 설정과 열린 창을 유지해 재시도할 수 있다. 저장 시 400/700 글꼴 로딩을 확인하고, 실패하면 이전 설정과 열린 창을 유지해 재시도할 수 있다.
2026-10-16 설정 창 개편 — 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정, 아래 [기본값으로]·취소·저장(한꺼번에 저장).
- **일반(폰트)** — 모두에게 보이고 **이 브라우저에만** 저장(`localStorage.pj_font`).
- **프로젝트 화면·보드** — 수퍼관리자·Admin(템플릿 `pj_admin` = `access.is_project_admin`)에게만 보이고, **서버에 저장해 모든 사용자에게 적용**
(`project_db.project_options`, 마이그레이션 029, 키 하나 = 행 하나, 값 JSONB). 키: `default_view`(왼쪽에서 프로젝트를 열 때 첫 탭
board/list/calendar/timeline/dashboard, 기본 board) · `board_cover`(보드 카드 표지 = 설명의 첫 이미지, 기본 켬).
허용 키·값·기본값은 `store.PROJECT_OPTION_DEFAULTS`·`normalize_project_options`(읽기 — 이상한 값은 기본값)·`validate_project_options`(쓰기 — 400) 한 곳.
API: `GET /project/api/options`(모듈 권한자 누구나, `can_edit`) · `PUT /project/api/options`(Admin 이상, 보낸 키만, 029 미적용 503).
프로젝트 화면(`/project/p/{id}`)은 서버가 `pj_options` → 루트 `data-default-view`·`data-board-cover` 로 넣고 `project.js` 가 쓴다
(읽기 실패·029 미적용이면 기본값 — 화면은 늘 열린다). 달력 월 이동 `?y=&m=` 은 마지막 뷰 `pj_view` 복원, `?scope=all` 은 대시보드, `?embed=1` 은 보드 그대로.
창은 열 때 서버 최신값을 읽고(못 읽으면 시스템 칸 잠금·폰트만 저장), 저장은 바뀐 키만 PUT → 성공해야 폰트도 적용(실패 시 창 유지·사유 표시).
저장하면 `pj-options-change` 이벤트로 보던 보드에 바로 반영, 다른 사용자는 다음에 화면을 열 때부터.
- **관리자(긴급 공지)** — 수퍼관리자만(`user.is_super_admin` — 공지 화면이 수퍼관리자 전용).
- 각 분류 제목 옆 배지로 적용 범위 표시(이 브라우저에만 / 모든 사용자에게). 새 옵션도 이 창의 분류·패널로 추가한다.
- 모달 대화창(`showModal`) 안의 말풍선은 공용 말풍선이 popover(top layer)로 띄운다(`initHoverTips` — 안 그러면 대화창 뒤에 가려짐).
테스트: `tests/test_project_options_api.py`, jsdom `project_ui.test.js`(렌더 `project_admin_render.html`·`project_super_render.html`).
**멤버 이름 표기** — 이메일 아이디의 첫 글자만 대문자(king → King). JS 는 `idOf(email)`/`capName(s)`, **멤버 이름 표기** — 이메일 아이디의 첫 글자만 대문자(king → King). JS 는 `idOf(email)`/`capName(s)`,
템플릿은 `{{ nm[:1]|upper }}{{ nm[1:] }}` 로 화면에 그릴 때만 바꾼다(API `id`·DB 값은 그대로 — 멘션·검색은 이메일 기준). 템플릿은 `{{ nm[:1]|upper }}{{ nm[1:] }}` 로 화면에 그릴 때만 바꾼다(API `id`·DB 값은 그대로 — 멘션·검색은 이메일 기준).
**프로젝트 색상·아이콘(아사나식)** — 색상표는 32색(`store.COLOR_PALETTE`, 8칸×4줄 — 위 2줄은 아사나 프로젝트 16색, 아래 2줄은 같은 열의 진한 색. 진한 칸은 체크를 흰색 `.is-dark`. 새 프로젝트 **프로젝트 색상·아이콘(아사나식)** — 색상표는 32색(`store.COLOR_PALETTE`, 8칸×4줄 — 위 2줄은 아사나 프로젝트 16색, 아래 2줄은 같은 열의 진한 색. 진한 칸은 체크를 흰색 `.is-dark`. 새 프로젝트
@@ -0,0 +1,23 @@
-- =====================================================================
-- project_db 마이그레이션 029 — Project 옵션(시스템 전체 설정)
-- =====================================================================
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
--
-- 왜(2026-10-16 사용자 요청): Project 옵션 창에서 "일반"(폰트)은 브라우저별(localStorage) 그대로 두고,
-- 수퍼관리자·Admin 이 바꾸는 "프로젝트 화면"(처음 여는 탭)·"보드"(카드 표지 이미지)는 모든 사용자에게 반영한다.
-- 키 하나 = 설정 하나(값은 JSONB). 허용 키·값 검사와 기본값은 앱(store.normalize_project_options) 한 곳에서 한다.
-- 행이 없으면 기본값(처음 여는 탭 = 보드, 카드 표지 = 켬) — 이 파일은 기본 행을 넣지 않는다.
-- 미적용이면: 화면은 기본값으로 동작하고, 옵션 저장만 503 안내.
-- 되돌리기: DROP TABLE project_options; (사용자 확인 후 — 저장한 시스템 설정만 사라지고 기본값으로 돌아감)
-- =====================================================================
BEGIN;
CREATE TABLE IF NOT EXISTS project_options (
key TEXT PRIMARY KEY CHECK (char_length(key) BETWEEN 1 AND 64),
value JSONB NOT NULL,
updated_by TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE project_options IS 'Project 옵션 — 시스템 전체 설정(수퍼관리자·Admin 수정, 모든 사용자에게 적용). 키: default_view, board_cover';
COMMIT;
+30 -1
View File
@@ -28,6 +28,17 @@ async function env(file) {
return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 }, return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 },
rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } }; rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } };
} }
if (/^\/performance\/api\/ad-spend\/meta\/details/.test(url)) { // 메타 — [합계 | 계정…] 탭(2026-10-16)
const tbl = function (amount, roas) {
return { columns: ["광고비(부가세 포함)", "ROAS(%)"], total: { "광고비(부가세 포함)": amount, "ROAS(%)": roas },
rows: [{ date: "2026-10-03", amount: amount, roas: roas, values: { "광고비(부가세 포함)": amount, "ROAS(%)": roas } }] };
};
return { ok: true, status: 200, json: async function () {
return Object.assign(tbl(165001, 400), { accounts_missing: e.metaMissing || 0, tabs: [
Object.assign({ key: "total", label: "합계" }, tbl(165001, 400)),
Object.assign({ key: "111", label: "본계정", account_id: "111" }, tbl(110000, 450)),
Object.assign({ key: "222", label: "서브<계정>", account_id: "222" }, tbl(55001, 300))] }); } };
}
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) { if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
return { ok: true, status: 200, json: async function () { return { ok: true, status: 200, json: async function () {
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } }; return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } };
@@ -225,7 +236,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]'); const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
const detailChans = Array.from(e.d.querySelectorAll(".perf-main thead [data-detail-channel]")).map(function (b) { return b.dataset.detailChannel; }); const detailChans = Array.from(e.d.querySelectorAll(".perf-main thead [data-detail-channel]")).map(function (b) { return b.dataset.detailChannel; });
// 구글도 광고 API 로 가져온 보고서 항목이 있어 상세 보기(2026-10-15) — 그 밖의 채널은 아님 // 구글도 광고 API 로 가져온 보고서 항목이 있어 상세 보기(2026-10-15) — 그 밖의 채널은 아님
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글만)", !!hb && detailChans.sort().join(",") === "google,naver", detailChans); check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글·메타만)", !!hb && detailChans.sort().join(",") === "google,meta,naver", detailChans);
hb.click(); await settle(); hb.click(); await settle();
const call = e.calls.find(function (c) { return /\/details/.test(c.url); }); 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); check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);
@@ -235,6 +246,24 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" && check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" &&
row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]); row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]);
check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent)); check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent));
check("[네이버] 계정 탭 없음(탭 자료 없는 채널)", !modal.querySelector(".perf-detail-tabs"));
}
// ── 메타 — 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
{
const e = await env("perf_ads.html");
e.metaMissing = 2;
e.d.querySelector('.perf-main thead [data-detail-channel="meta"]').click(); await settle();
const modal = e.d.querySelector(".perf-modal");
const tabs = Array.from(modal.querySelectorAll(".perf-detail-tabs [data-tab]"));
const foot = function () { return modal.querySelector(".perf-detail-tab-body tfoot").textContent; };
check("[메타] 탭 = 합계 + 계정(이름은 글자 그대로, 계정 ID 는 말풍선)", tabs.map(function (b) { return b.textContent; }).join("|") === "합계|본계정|서브<계정>" &&
tabs[1].getAttribute("title") === "act_111" && !tabs[0].hasAttribute("title"), tabs.map(function (b) { return b.outerHTML; }));
check("[메타] 처음엔 합계 탭", tabs[0].classList.contains("is-active") && tabs[0].getAttribute("aria-selected") === "true" && /165,001/.test(foot()) &&
modal.querySelectorAll(".perf-detail-tab-body table").length === 1);
tabs[2].click();
check("[메타] 계정 탭 누르면 그 계정 표", tabs[2].classList.contains("is-active") && !tabs[0].classList.contains("is-active") &&
/55,001/.test(foot()) && /1원 다를 수/.test(modal.textContent));
check("[메타] 계정별 자료 없는 날 안내", /2일은 계정별 자료가 없어/.test(modal.textContent) && modal.textContent.indexOf("[메타 광고 불러오기]") >= 0);
} }
// ── 설정: 수동 입력 토글 ── // ── 설정: 수동 입력 토글 ──
{ {
+114
View File
@@ -16,6 +16,7 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
const ROOT = path.join(__dirname, "..", ".."); const ROOT = path.join(__dirname, "..", "..");
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8"); const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8"); const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
const superHtml = fs.readFileSync(path.join(__dirname, ".out", "project_super_render.html"), "utf8");
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8"); const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
const mytasksHtml = fs.readFileSync(path.join(__dirname, ".out", "mytasks_render.html"), "utf8"); const mytasksHtml = fs.readFileSync(path.join(__dirname, ".out", "mytasks_render.html"), "utf8");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8"); const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
@@ -538,6 +539,119 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
check("[옵션] 폰트 로딩 실패는 이전 설정 유지·재시도 가능", dialog.open && !d.getElementById("pj-options-error").hidden && !select.disabled && w.localStorage.getItem("pj_font") === "pretendard"); check("[옵션] 폰트 로딩 실패는 이전 설정 유지·재시도 가능", dialog.open && !d.getElementById("pj-options-error").hidden && !select.disabled && w.localStorage.getItem("pj_font") === "pretendard");
} }
// 옵션 — 일반(폰트)은 이 브라우저, 프로젝트 화면·보드는 서버(시스템 전체, 수퍼관리자·Admin 만 수정).
// 가짜 서버: GET/PUT /project/api/options. 화면 값은 project.html 이 data-default-view·data-board-cover 로 넣는다.
function optionRoutes(env, state) {
env.route("GET", /\/project\/api\/options$/, function () {
if (state.getFail) return { status: 500, body: { detail: "DB 오류" } };
return { body: { options: Object.assign({}, state.options), can_edit: true } };
});
env.route("PUT", /\/project\/api\/options$/, function (url, body) {
if (state.putFail) return { status: 503, body: { detail: "DB 마이그레이션 029(Project 옵션)가 아직 적용되지 않았습니다." } };
Object.assign(state.options, body);
return { body: { options: Object.assign({}, state.options) } };
});
}
function withCover(d) {
const seed = JSON.parse(d.getElementById("pj-data").textContent);
seed.tasks.find(function (t) { return t.id === 101; }).description = '<p>표지</p><img src="/project/attachments/1/a.png">';
d.getElementById("pj-data").textContent = JSON.stringify(seed);
}
function pageOptions(d, view, coverOn) {
const root = d.querySelector(".pj-project-view");
root.dataset.defaultView = view; root.dataset.boardCover = coverOn ? "1" : "0";
}
const optCalls = function (env, method) { return env.calls.filter(function (c) { return c.method === method && /\/project\/api\/options$/.test(c.url); }); };
// 수퍼관리자 — 분류 탭, 서버 값 불러오기, 표지 끄기(보던 보드에 바로)·첫 탭 저장, 바뀐 키만 PUT, 기본값으로, 실패 처리.
{
const env = makeEnv(superHtml); baseRoutes(env); const d = env.d, w = env.w;
const state = { options: { default_view: "board", board_cover: true } }; optionRoutes(env, state);
withCover(d); await boot(env);
const dialog = d.getElementById("pj-options-dialog"), cover = d.getElementById("pj-options-cover");
const coverImg = function () { return d.querySelector('.pj-card[data-task-id="101"] .pj-card-cover img'); };
const pane = function (n) { return d.querySelector('.pj-options-pane[data-pane="' + n + '"]'); };
const checkedView = function () { return dialog.querySelector('input[name="default_view"]:checked').value; };
check("[옵션 표지] 기본은 설명 첫 이미지를 카드 표지로", !!coverImg() && coverImg().getAttribute("src") === "/project/attachments/1/a.png");
state.options = { default_view: "calendar", board_cover: true }; // 다른 관리자가 그 사이 바꿈 — 창은 서버 최신값
d.getElementById("pj-options-btn").click(); await settle();
check("[옵션] 열면 일반 분류부터·서버 값(캘린더) 불러옴", dialog.open && !pane("general").hidden && pane("board").hidden && optCalls(env, "GET").length === 1 && cover.checked && checkedView() === "calendar" && !cover.disabled);
check("[옵션] 적용 범위 표시 — 일반=이 브라우저, 보드=모든 사용자", /이 브라우저/.test(pane("general").querySelector(".pj-options-badge").textContent) && /모든 사용자/.test(pane("board").querySelector(".pj-options-badge.is-global").textContent));
d.getElementById("pj-opt-tab-board").click();
check("[옵션] 분류 탭 전환", pane("general").hidden && !pane("board").hidden && d.getElementById("pj-opt-tab-board").getAttribute("aria-selected") === "true");
cover.checked = false; dialog.querySelector('input[name="default_view"][value="list"]').checked = true;
d.getElementById("pj-options-cancel").click(); await settle();
check("[옵션] 취소는 서버에 저장하지 않음", !dialog.open && optCalls(env, "PUT").length === 0 && !!coverImg());
d.getElementById("pj-options-btn").click(); await settle();
check("[옵션] 다시 열면 취소한 값은 되돌림", cover.checked && checkedView() === "calendar");
cover.checked = false; dialog.querySelector('input[name="default_view"][value="timeline"]').checked = true;
d.getElementById("pj-options-save").click(); await settle();
const put = optCalls(env, "PUT")[0];
check("[옵션 시스템] 저장은 바뀐 키만 서버로(PUT)", !dialog.open && optCalls(env, "PUT").length === 1 && JSON.stringify(put.body) === JSON.stringify({ default_view: "timeline", board_cover: false }));
check("[옵션 시스템] 브라우저(localStorage)에는 시스템 옵션을 쓰지 않음", !w.localStorage.getItem("pj_board_cover") && !w.localStorage.getItem("pj_default_view"));
check("[옵션 표지] 끄고 저장하면 보던 보드에서 표지가 바로 사라짐", !coverImg() && !d.querySelector('.pj-card[data-task-id="101"]').classList.contains("has-cover"));
check("[옵션 첫 탭] 저장해도 지금 보던 탭은 그대로", !d.querySelector('.pj-view[data-view="board"]').hidden);
d.getElementById("pj-options-btn").click(); await settle(); d.getElementById("pj-options-font").value = "pretendard";
d.getElementById("pj-options-save").click(); await settle();
check("[옵션] 폰트만 바꾸면 서버에 쓰지 않음", optCalls(env, "PUT").length === 1 && w.localStorage.getItem("pj_font") === "pretendard");
d.getElementById("pj-options-btn").click(); await settle(); d.getElementById("pj-options-reset").click();
check("[옵션] 기본값으로 — 창 안의 값만 처음으로(저장 전)", cover.checked && checkedView() === "board" && d.getElementById("pj-options-font").value === "system" && optCalls(env, "PUT").length === 1);
d.getElementById("pj-options-save").click(); await settle();
check("[옵션 표지] 다시 켜면 표지 복귀", JSON.stringify(optCalls(env, "PUT")[1].body) === JSON.stringify({ default_view: "board", board_cover: true }) && !!coverImg() && w.localStorage.getItem("pj_font") === "system");
// 서버 저장 실패(029 미적용 등) — 창 유지·오류 안내, 폰트도 적용하지 않음(전부 아니면 전무)
state.putFail = true;
d.getElementById("pj-options-btn").click(); await settle();
cover.checked = false; d.getElementById("pj-options-font").value = "nanum-square";
d.getElementById("pj-options-save").click(); await settle();
check("[옵션 시스템] 저장 실패 — 창 유지·사유 표시·폰트 미적용·다시 시도 가능", dialog.open && /029/.test(d.getElementById("pj-options-error").textContent) && !d.getElementById("pj-options-error").hidden &&
w.localStorage.getItem("pj_font") === "system" && !!coverImg() && !cover.disabled && !d.getElementById("pj-options-save").disabled);
d.getElementById("pj-options-cancel").click();
// 서버 값 읽기 실패 — 시스템 칸 잠금, 폰트는 저장됨, PUT 없음
state.getFail = true; state.putFail = false;
d.getElementById("pj-options-btn").click(); await settle();
check("[옵션 시스템] 불러오기 실패 — 시스템 칸 잠금·안내", cover.disabled && /폰트만 저장/.test(d.getElementById("pj-options-error").textContent));
const putsBefore = optCalls(env, "PUT").length; // 위의 실패한 PUT 도 기록에 있다
d.getElementById("pj-options-font").value = "nanum-square"; d.getElementById("pj-options-save").click(); await settle();
check("[옵션 시스템] 불러오기 실패해도 폰트는 저장, 서버엔 쓰지 않음", !dialog.open && w.localStorage.getItem("pj_font") === "nanum-square" && optCalls(env, "PUT").length === putsBefore);
}
// 시스템 첫 탭(서버 값) — 누구든 그 탭으로 시작, 이상한 값은 보드
{
const env = makeEnv(); baseRoutes(env); const d = env.d;
pageOptions(d, "list", true); await boot(env);
check("[옵션 첫 탭] 일반 사용자도 시스템 첫 탭(목록)으로 시작", !d.querySelector('.pj-view[data-view="list"]').hidden && d.querySelector('.pj-view[data-view="board"]').hidden && d.querySelector('#pj-view-tabs .pj-tab.is-active').dataset.view === "list");
}
{
const env = makeEnv(superHtml); baseRoutes(env); const d = env.d;
pageOptions(d, "garbage", true); await boot(env);
check("[옵션 첫 탭] 이상한 값이면 보드", !d.querySelector('.pj-view[data-view="board"]').hidden);
}
// Admin — 프로젝트 화면·보드는 보이고 수정 가능, 관리자(긴급 공지)는 수퍼관리자만이라 없음.
{
const env = makeEnv(adminHtml); baseRoutes(env); const d = env.d;
const state = { options: { default_view: "board", board_cover: false } }; optionRoutes(env, state);
await boot(env);
d.getElementById("pj-options-btn").click(); await settle();
check("[옵션 Admin] 일반·프로젝트 화면·보드 분류, 관리자 분류는 없음, 서버 값 표시",
Array.from(d.querySelectorAll("#pj-options-dialog .pj-options-nav [role=tab]")).map(function (t) { return t.dataset.pane; }).join(",") === "general,view,board" &&
!d.getElementById("pj-opt-pane-admin") && !d.getElementById("pj-options-cover").checked && !d.getElementById("pj-options-cover").disabled);
d.getElementById("pj-options-cover").checked = true; d.getElementById("pj-options-save").click(); await settle();
check("[옵션 Admin] 저장하면 서버로", JSON.stringify((optCalls(env, "PUT")[0] || {}).body) === JSON.stringify({ board_cover: true }));
}
// 일반 사용자 — 폰트만 보이고 서버 옵션은 읽지도 쓰지도 않음, 시스템 표지 끔은 그대로 적용.
{
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
optionRoutes(env, { options: { default_view: "board", board_cover: true } });
withCover(d); pageOptions(d, "board", false); await boot(env);
const dialog = d.getElementById("pj-options-dialog");
check("[옵션 일반 사용자] 시스템 표지 끔이 적용 — 표지 없음", !!d.querySelector('.pj-card[data-task-id="101"]') && !d.querySelector('.pj-card[data-task-id="101"] .pj-card-cover'));
d.getElementById("pj-options-btn").click(); await settle();
check("[옵션 일반 사용자] 분류는 일반(폰트)만·서버 옵션 안 읽음", dialog.open && dialog.querySelectorAll(".pj-options-nav [role=tab]").length === 1 &&
dialog.querySelectorAll(".pj-options-pane").length === 1 && !d.getElementById("pj-options-cover") && !dialog.querySelector('input[name="default_view"]') && !d.getElementById("pj-opt-pane-admin") && optCalls(env, "GET").length === 0);
d.getElementById("pj-options-reset").click(); d.getElementById("pj-options-font").value = "pretendard";
d.getElementById("pj-options-save").click(); await settle();
check("[옵션 일반 사용자] 폰트만 이 브라우저에 저장 — 서버엔 안 씀", !dialog.open && w.localStorage.getItem("pj_font") === "pretendard" && optCalls(env, "PUT").length === 0);
}
// 카드 완료 체크 — 상세창과 분리, 중복 요청·실패 복구·읽기 전용. // 카드 완료 체크 — 상세창과 분리, 중복 요청·실패 복구·읽기 전용.
{ {
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w; const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
+5 -4
View File
@@ -50,8 +50,9 @@ def main() -> None:
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")), jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
])) ]))
env.globals["pj_kr_holidays"] = {} env.globals["pj_kr_holidays"] = {}
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)): for name, admin, sup in (("project_render.html", False, False), ("project_admin_render.html", True, False),
render_one(env, name, admin) ("project_super_render.html", True, True)):
render_one(env, name, admin, sup)
render_inbox(env) render_inbox(env)
render_mytasks(env) render_mytasks(env)
@@ -102,9 +103,9 @@ def render_inbox(env) -> None:
print("rendered:", path) print("rendered:", path)
def render_one(env, name: str, admin: bool) -> None: def render_one(env, name: str, admin: bool, sup: bool = False) -> None:
html = env.get_template("project/project.html").render( html = env.get_template("project/project.html").render(
user={"email": ME, "is_super_admin": False}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True, user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True,
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS, project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}], members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"], projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
+113
View File
@@ -0,0 +1,113 @@
"""Project 옵션(시스템 전체 — 처음 여는 탭·보드 카드 표지) API·검사. DB 없이 가짜 저장소로.
일반(폰트)은 브라우저 localStorage 라 서버에 없다. 수퍼관리자·Admin 만 저장, 읽기는 모듈 권한자 누구나.
"""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from psycopg.errors import UndefinedTable
api = importlib.import_module("app.modules.project.router")
store = importlib.import_module("app.modules.project.store")
ADMIN = {"email": "Boss@Test.local", "role": "admin"}
USER = {"email": "me@test.local", "role": "user"}
PRO = {"email": "pro@test.local", "role": "pro"}
class FakeStore:
def __init__(self, saved=None, *, missing=False, broken=False):
self.saved = dict(saved or {})
self.missing = missing # 029 미적용
self.broken = broken # 읽기 자체가 실패(연결 끊김 등)
self.writes = []
def get_project_options(self):
if self.broken:
raise RuntimeError("db down")
return {} if self.missing else dict(self.saved)
def set_project_options(self, *, values, updated_by):
if self.missing:
raise UndefinedTable("project_options")
self.writes.append((dict(values), updated_by))
self.saved.update(values)
class NormalizeTests(unittest.TestCase):
def test_defaults_when_nothing_saved(self):
self.assertEqual(store.normalize_project_options(None), {"default_view": "board", "board_cover": True})
self.assertEqual(store.normalize_project_options({}), {"default_view": "board", "board_cover": True})
def test_bad_or_unknown_saved_values_fall_back(self):
out = store.normalize_project_options({"default_view": "gantt", "board_cover": "no", "x": 1})
self.assertEqual(out, {"default_view": "board", "board_cover": True})
def test_saved_values_used(self):
out = store.normalize_project_options({"default_view": "timeline", "board_cover": False})
self.assertEqual(out, {"default_view": "timeline", "board_cover": False})
def test_validate_keeps_only_sent_keys(self):
self.assertEqual(store.validate_project_options({"board_cover": False}), {"board_cover": False})
def test_validate_rejects(self):
for bad in ({}, None, [], {"default_view": "gantt"}, {"board_cover": 0}, {"board_cover": "false"}, {"font": "x"}):
with self.subTest(bad=bad), self.assertRaises(ValueError):
store.validate_project_options(bad)
class OptionsApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
def call(self, method, user, st, body=None):
with patch.object(api, "_require_user", return_value=user), \
patch.object(api, "_db_or_503", return_value=st):
return self.client.request(method, "/project/api/options", json=body)
def test_anyone_with_module_reads_with_can_edit_flag(self):
st = FakeStore({"default_view": "list"})
out = self.call("GET", USER, st).json()
self.assertEqual(out, {"options": {"default_view": "list", "board_cover": True}, "can_edit": False})
self.assertTrue(self.call("GET", ADMIN, st).json()["can_edit"])
def test_admin_saves_only_sent_keys(self):
st = FakeStore({"default_view": "calendar"})
res = self.call("PUT", ADMIN, st, {"board_cover": False})
self.assertEqual(res.status_code, 200)
self.assertEqual(st.writes, [({"board_cover": False}, "Boss@Test.local")])
self.assertEqual(res.json()["options"], {"default_view": "calendar", "board_cover": False})
def test_user_and_pro_cannot_save(self):
for who in (USER, PRO):
st = FakeStore()
with self.subTest(role=who["role"]):
self.assertEqual(self.call("PUT", who, st, {"board_cover": False}).status_code, 403)
self.assertEqual(st.writes, [])
def test_invalid_payload_400_without_write(self):
st = FakeStore()
for body in ({"default_view": "gantt"}, {"board_cover": "yes"}, {}, {"font": "pretendard"}):
with self.subTest(body=body):
self.assertEqual(self.call("PUT", ADMIN, st, body).status_code, 400)
self.assertEqual(st.writes, [])
def test_migration_missing_read_defaults_write_503(self):
st = FakeStore(missing=True)
self.assertEqual(self.call("GET", USER, st).json()["options"], {"default_view": "board", "board_cover": True})
res = self.call("PUT", ADMIN, st, {"board_cover": False})
self.assertEqual(res.status_code, 503)
self.assertIn("029", res.json()["detail"])
def test_page_reader_never_fails(self):
self.assertEqual(api._project_options(None), {"default_view": "board", "board_cover": True})
self.assertEqual(api._project_options(FakeStore(broken=True)), {"default_view": "board", "board_cover": True})
if __name__ == "__main__":
unittest.main()