From e7b1e1757998a2d4224bf9ab0fdf8e733bdfad59 Mon Sep 17 00:00:00 2001 From: king Date: Thu, 15 Oct 2026 15:10:03 +0900 Subject: [PATCH] =?UTF-8?q?feat(performance):=20=EA=B4=91=EA=B3=A0?= =?UTF-8?q?=EB=B9=84=20=ED=83=AD=20=EA=B5=AC=EA=B8=80=20=EA=B4=91=EA=B3=A0?= =?UTF-8?q?=EB=B9=84=C2=B7ROAS=20=EB=A5=BC=20Google=20Ads=20API=20?= =?UTF-8?q?=EB=A1=9C=20=EA=B0=80=EC=A0=B8=EC=98=A4=EA=B8=B0=20+=20?= =?UTF-8?q?=EC=84=A4=EC=A0=95=EC=97=90=EC=84=9C=20=ED=82=A4=20=EC=9E=85?= =?UTF-8?q?=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 실적 설정 "광고 API 연동" 카드: 개발자 토큰·고객 ID·로그인 고객 ID(MCC)·서비스 계정 JSON·API 버전(기본 v26) → 쇼핑몰과 같은 마스터 키로 암호화(perf_ad_credentials, AAD perf:ad:…), 연결 테스트·상태(perf_ad_source_status) - ad_sources/(채널 하나 = 파일 하나) + google_ads.py: 서비스 계정 JWT 토큰(httpx) → REST searchStream GAQL, 비용(cost_micros 원 반올림, 부가세 별도)·ROAS(전환 가치÷비용)·노출·클릭·전환 항목, KRW 계정만, 오류 코드별 안내 - ad_sync.py: 기간 한 트랜잭션 저장(source='api', 안 준 날은 예전 API 값만 지움), 같은 채널 동시 실행 차단, 비밀값 가림 - 광고비 탭 [구글 광고 불러오기](보는 기간, 92일 넘으면 관리자) + 매출 자동 업데이트 회차에 함께, API 값 초록 숫자, 구글 머리글 = 일자별 항목 표 - 마이그레이션 007, 테스트 test_google_ads.py(가짜 구글 서버) — performance 테스트 83개 통과 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../performance/ad_sources/__init__.py | 5 + app/modules/performance/ad_sources/base.py | 70 +++++ .../performance/ad_sources/google_ads.py | 293 ++++++++++++++++++ .../performance/ad_sources/registry.py | 17 + app/modules/performance/ad_spend.py | 9 +- app/modules/performance/ad_sync.py | 119 +++++++ app/modules/performance/adapters/base.py | 2 + app/modules/performance/auto_sync.py | 12 +- app/modules/performance/credentials.py | 31 +- app/modules/performance/db.py | 164 ++++++++++ app/modules/performance/router.py | 157 +++++++++- .../templates/performance/ads.html | 30 +- .../templates/performance/index.html | 4 +- .../templates/performance/settings.html | 50 ++- .../performance/tests/test_ad_spend.py | 3 +- .../performance/tests/test_auto_sync.py | 4 +- .../performance/tests/test_google_ads.py | 292 +++++++++++++++++ app/static/performance.css | 7 + app/static/performance.js | 61 +++- docs/DEPLOYMENT.md | 16 + docs/PERFORMANCE_MODULE.md | 28 +- scripts/sql/performance_db_007_ad_api.sql | 53 ++++ tests/js/render_performance.py | 10 +- 24 files changed, 1379 insertions(+), 60 deletions(-) create mode 100644 app/modules/performance/ad_sources/__init__.py create mode 100644 app/modules/performance/ad_sources/base.py create mode 100644 app/modules/performance/ad_sources/google_ads.py create mode 100644 app/modules/performance/ad_sources/registry.py create mode 100644 app/modules/performance/ad_sync.py create mode 100644 app/modules/performance/tests/test_google_ads.py create mode 100644 scripts/sql/performance_db_007_ad_api.sql diff --git a/CLAUDE.md b/CLAUDE.md index d64fa62..c3bed75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지(`POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A` — NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨), 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매)을 수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다. 그래서 "마지막 쓰기가 권위": 상세설명은 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 쓰고(`store.resolve_description`), 스칼라(상품명·가격·이미지·진열/판매)는 PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌운다(`store.overlay_recent_write`). 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분). 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다. 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md` - 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색, 수정 창 12열)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011 + [아사나 아이콘] 탭 33종 `"asana:"+이름`, 채워진 모양 전용 부분 글꼴 `material-symbols-asana.woff2`)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작 — `create_project(seed_stages=True)` 일 때만 기본 4단계, 섹션 머리는 모두 `#f3f3f3` — 섹션별 색 지정 없음, 섹션 이름 굵게, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`)·내 작업(접이식) 메뉴. 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). **관리자 등급 4단계(2026-10-12) — 수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User** — 판단은 `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`, `is_admin` 은 ERP 상단 관리자 메뉴용 그대로). pro 는 프로젝트 모듈 밖에서는 user 와 같다. 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버 = Pro user 이상, 프로젝트·섹션 삭제 = Admin 이상 또는 만든 사람, 작업 삭제·서브프로젝트 = 멤버 누구나(표는 docs/PROJECT_MODULE.md 6-14). 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`). 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, Pro user 이상만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 Pro user 이상, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력(주차별 목표·연도 추가/삭제 포함)은 Pro user 이상. 3·6·9·12월 오른쪽 1~4분기 칸(글 칸 13=1분기·15=2분기·14=3분기·16=4분기 — 예전 반기 칸 번호 재사용, 15·16 은 마이그레이션 017) + 분기 월 칸 접기 애니메이션(localStorage `pj_goal_fold_q`, 표는 `width:1px`+`table-layout:fixed`), 영역·줄 이름 클릭 바로 수정, **엑셀식 칸 병합**(마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 분기 월 칸 가로, 글은 왼쪽 위 칸 — `goal_cell_merges`, 마이그레이션 014·015·017), 3열 줄 추가는 같은 항목 칸(2열) 안에(`goal_rows.label_cont`, 마이그레이션 016), 구조 변경은 새로고침 없이 제자리 다시 그리기(`refreshTable`)+애니메이션, 로아스는 % 표기. 월 머리 → **주간 회의록**(`/project/goals/{연도}/meetings/{월}`, 프로젝트 권한자 **누구나 수정** — Pro user 이상 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용), 삭제·완료·완료 해제는 Pro user 이상, 표 첫 열 머리 글자 "구분", 주차 탭 — **주차는 그 달 안**(`store.month_weeks`: 1일이 월~금이면 1일~일요일이 1주차, 토·일이면 1일~다음 주 일요일, 그 뒤 월~일, 말일이 월·화면 앞 주차에 붙음, 회의록 `week_start` = 주차 시작일, 마이그레이션 020), `goal_meetings`·`goal_meeting_items` 마이그레이션 015 — 지난주 = **바로 앞 주차**(`store.prev_week_period`) 회의록의 같은 연결키 줄(`line_key`, 마이그레이션 018 — 생성 순서·이름 변경과 무관, 이름 추정 연결 금지)로 리뷰(열: 주요 업무·정량 목표 ‖ 전주 업무·결과(글, `result_note` 020)·전주 목표·결과 — 정량 목표·결과는 숫자면 원 정수 칸, 아니면 글 칸 `target_text`·`result_text`(예: 20개, 021)), 실적 조회 장애는 0원이 아니라 "미확인", 위에 목표 표 그 달 열 글을 영역별 "N월 계획" 카드로, 참석자 옆 [회의록 보드] = 그 주차의 빈 Google 슬라이드를 독립 창으로(오른쪽 🔗 아이콘 = 그 보드 링크 복사)(공유 드라이브 `MEETING_BOARD_FOLDER_ID`, 없으면 만듦, `app/integrations/google_slides.py`, Drive appProperties 로 주차 연결 — Drive·Slides 권한 토큰 필요), 표를 스크롤해도 보이는 머리 영역 3칸 = ① 월 계획 + 머리 줄에 숫자 4개 작게 1행(월 목표 매출·월 누적 목표 매출(목표 표 **주차별 매출 목표** `goal_week_targets` 1주차~이 주차 합 — 목표 표 매출 목표 월 칸을 누르면 입력 창 — 월 전체 목표는 직접 입력(주차 합계와 별개), 맨 아래 차이 = 월 목표 − 주차 합계)·월 누적 실적(1일~오늘)·누적 목표 대비 차액·%) | ② 결정 사항·메모 | ③ "N주차 작업 등록" 표(제목·담당자·프로젝트·섹션 → [적용] = 서버가 그 프로젝트에 작업 생성, `initMeetQuickTasks` — 주차별 서버 표 `goal_meeting_tasks`(마이그레이션 025)라 모두가 같이 보고, 남의 프로젝트 이름은 가림, 완료 프로젝트·섹션은 목록에서 뺌, 작업 칸(마이그레이션 026 `parent_task_id`) = 이미 있는 작업을 고르면 그 작업의 세부 작업으로 등록, 등록된 줄 제목 = 오른쪽 작업 창(편집, 저장 대기), [크게 열기] = 같은 표를 넓은 창으로), 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력). 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제, 회의록 "주요 업무" 칸 우클릭 위/아래 줄 추가 = 항목 칸은 그대로 그 항목 안에(마이그레이션 027 `label_cont`, 항목 칸 나누기), 회의록 줄 작업은 새로고침 없이 제자리 다시 그리기(`refreshMeeting`)+애니메이션, 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`move-section`). 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008. 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지). 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 목표 표·회의록 칸 저장은 공용 `createFieldSaver`(같은 칸 요청 직렬화·보낸 값만 저장됨·실패 시 초안 유지·localStorage 초안 백업, 저장 실패면 구조 변경 중단 — docs/PROJECT_MODULE.md 6-9-3), 구역·항목 메뉴는 우클릭 + ⋮ 버튼(키보드·터치). ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title). **PC 알림 프로그램**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms exe 하나·트레이 상주, 마이그레이션 023 `notifier_links`·`notifier_tokens`) — 브라우저가 뒤에 있어도 태그·배정 알림을 웹 팝업과 같은 모양으로 화면 위에. 브라우저 `/project/notifier?code=` 승인으로 PC별 토큰(서버는 SHA-256 만, PC 는 DPAPI), `GET /project/api/notifier/alerts`(Bearer)는 웹 알림과 같은 `_alerts_payload`, 토큰마다 지금 사용자·권한 재확인. 프로그램이 돌고 있으면(최근 3분 확인, `notifier_active`) 웹 큰 팝업은 쉰다(`desktop: true`). 압축·난독화 금지(백신 오탐), 빌드 `desktop/notifier/build.ps1`, 상세 docs/PROJECT_MODULE.md 6-11. 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea), 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐. 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". 섹션 제목 오른쪽 담당자 아이콘 = 그 자리에서 기본 담당자 지정, 업무 창 세부 업무 줄 담당자 오른쪽 = 협업자 지정, 댓글 이모티콘 반응 = 댓글 쓴 사람에게 알림(`type=reaction`), 왼쪽 전체 보기 = 기본 대시보드, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(docs/PROJECT_MODULE.md 6-16). 세부 업무를 만들 때(업무 창 추가 칸·보드 카드 새 줄) 협업자도 같이(`POST …/tasks` 의 `followers`, 비멤버 400), 보드 카드 세부 업무 줄에도 협업자 아이콘, 대시보드 "업무 합계(프로젝트별)" 카드, **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17). **업무를 다른 프로젝트로 이동** — 보드 카드를 왼쪽 프로젝트 목록에 끌어 놓으면 섹션 선택 창 → `POST /project/api/tasks/{id}/move-project`(세부 업무 함께, 원 소속 권한 + 대상 프로젝트 멤버)(6-18). **담당자는 협업자가 아니다**(협업자 = 담당자 외의 멤버, `db.add_followers` 가 거르고 담당자 지정 시 협업자에서 뺌, 기존 겹친 행은 마이그레이션 028), 세부 업무 추가 칸은 동그라미 아이콘 버튼, 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe), 대시보드 섹션별 카드 삭제(6-19). 세부 업무는 만든 사람을 자동 협업자로 넣지 않음(고른 사람만), 세부 업무 줄 빈 마감일 아이콘 늘 옅게, 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20). 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`). 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남). 상세는 `docs/PROJECT_MODULE.md` -- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀, env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로). 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳). 일자별 표 [엑셀 업로드] 팝업(`manual_upload.py`, `POST /performance/api/manual-sales/upload`) — 1열 날짜·2열부터 쇼핑몰 이름 머리글, 수동 입력 켜진 쇼핑몰 열의 값 있는 칸만 반영(덮어씀, 빈 칸 그대로), 잘못된 칸이 하나라도 있으면 전부 저장 안 함, 샘플 = 모듈 폴더 `upload_sample.xlsx`. 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003). 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. **광고비**(`/performance/ads`, `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`) — 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로, 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS, 마이그레이션 006 `roas`·`metrics`), 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드(네이버 = 3열 기간·4열 총비용·12열 ROAS, 머리글 클릭 = 일자별 보고서 항목)(1열 날짜·19열 청구금액(+부가가치세)), 매출 대비 광고비 KPI. 상세는 `docs/PERFORMANCE_MODULE.md` +- 실적 (`app/modules/performance/`, `performance_db`) — 쇼핑몰 통합 매출. 네 영역 분리: ① 수집 `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리) ② 보안 `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py` ③ 계산 `calc.py`(주=월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py` ④ 화면 `dashboard.py`/`router.py`/템플릿. 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다. 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장. 매출 기준일: 결제=결제일, 취소·반품=발생일(`sync.sales_date_for`). 금액은 원 단위 정수. 권한키 `performance`, 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀, env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`. 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로). 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳). 일자별 표 [엑셀 업로드] 팝업(`manual_upload.py`, `POST /performance/api/manual-sales/upload`) — 1열 날짜·2열부터 쇼핑몰 이름 머리글, 수동 입력 켜진 쇼핑몰 열의 값 있는 칸만 반영(덮어씀, 빈 칸 그대로), 잘못된 칸이 하나라도 있으면 전부 저장 안 함, 샘플 = 모듈 폴더 `upload_sample.xlsx`. 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003). 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. **광고비**(`/performance/ads`, `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`) — 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로, 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS, 마이그레이션 006 `roas`·`metrics`), 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드(네이버 = 3열 기간·4열 총비용·12열 ROAS, 머리글 클릭 = 일자별 보고서 항목)(1열 날짜·19열 청구금액(+부가가치세)), 매출 대비 광고비 KPI. **구글 = Google Ads API**(2026-10-15, 마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드에서 개발자 토큰·고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26) 입력 → 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나)+`ad_sync.py`, 광고비 탭 [구글 광고 불러오기](보는 기간)·매출 자동 업데이트 회차에 함께, 비용(부가세 별도)·ROAS(전환 가치÷비용)·항목 → `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움). 상세는 `docs/PERFORMANCE_MODULE.md` - 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md` diff --git a/app/modules/performance/ad_sources/__init__.py b/app/modules/performance/ad_sources/__init__.py new file mode 100644 index 0000000..93a5846 --- /dev/null +++ b/app/modules/performance/ad_sources/__init__.py @@ -0,0 +1,5 @@ +"""광고 API 연동(구글 광고 등) — 광고 채널 하나 = 파일 하나 + registry.py 한 줄. + +쇼핑몰 어댑터(adapters/)와 같은 모양(입력칸·연결 테스트·인증정보 접근자)을 따르되, 돌려주는 것은 매출 사건이 아니라 +"날짜별 광고비·ROAS·보고서 항목"(AdDay)이다. 저장은 ad_sync.py 가 perf_ad_spend(source='api')에. +""" diff --git a/app/modules/performance/ad_sources/base.py b/app/modules/performance/ad_sources/base.py new file mode 100644 index 0000000..1f5e68d --- /dev/null +++ b/app/modules/performance/ad_sources/base.py @@ -0,0 +1,70 @@ +"""광고 API 연동 — 공통 인터페이스. + +광고 채널 코드(code)는 광고비 표 채널 코드(ad_spend.CHANNELS)와 같다 — 가져온 값은 그 채널 열로 들어간다. +인증정보는 쇼핑몰 인증정보와 같은 방식(설정 화면 입력 → 마스터 키로 암호화 → perf_ad_credentials)이고, +꺼낼 때는 ctx.credentials.get(key) 로만(서버 안에서만 복호화). 오류는 adapters.base 의 AdapterError 계열 — +status 가 곧 연결 상태 코드(설정 화면 표시)다. 오류 문구에 비밀값을 넣지 않는다. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date +from decimal import Decimal +from typing import Any + +from ..adapters.base import AdapterContext, CredentialField, NotConfigured + + +@dataclass +class AdDay: + """광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로.""" + + day: date + amount: int + roas: Decimal | None = None + metrics: dict[str, Any] = field(default_factory=dict) + + +class AdSource: + code: str = "" # 광고비 채널 코드(google 등) + name: str = "" # 설정 화면 이름 + docs_url: str = "" + note: str = "" # 설정 창 맨 위 안내 + + # 인증정보 서비스(credentials.CredentialService)가 쇼핑몰 어댑터와 같은 방식으로 다루게 맞춘 속성 + @property + def uses_shared_integration(self) -> bool: + return False + + def credential_fields(self) -> list[CredentialField]: + return [] + + def visible_fields(self) -> list[CredentialField]: + return [f for f in self.credential_fields() if not f.internal] + + def validate_credentials(self, values: dict[str, str]) -> list[str]: + """저장 전 검사. values 의 "__stored__" = 저장된 값이 있음(원문은 꺼내지 않음). 값 자체를 오류 문구에 넣지 않는다.""" + errors: list[str] = [] + for f in self.visible_fields(): + v = (values.get(f.key) or "").strip() + if f.required and not v: + errors.append(f"{f.label} 을(를) 입력하세요.") + elif v and len(v) > 20000: + errors.append(f"{f.label} 값이 너무 깁니다.") + return errors + + def is_configured(self, ctx: AdapterContext) -> bool: + return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required) + + def require_configured(self, ctx: AdapterContext) -> None: + if not self.is_configured(ctx): + raise NotConfigured("필수 인증정보가 입력되지 않았습니다. 실적 설정 → 광고 API 연동에서 입력하세요.") + + def test_connection(self, ctx: AdapterContext) -> str: + """성공하면 사람이 읽을 짧은 문구. 실패는 AdapterError.""" + raise NotImplementedError + + def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]: + """기간(양 끝 포함)의 날짜별 광고비. 광고가 없던 날은 빠질 수 있다(저장 쪽이 그날의 예전 API 값을 지운다).""" + raise NotImplementedError diff --git a/app/modules/performance/ad_sources/google_ads.py b/app/modules/performance/ad_sources/google_ads.py new file mode 100644 index 0000000..73b4dfd --- /dev/null +++ b/app/modules/performance/ad_sources/google_ads.py @@ -0,0 +1,293 @@ +"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목. + +인증(2026-10-15 사용자: 서비스 계정 + 개발자 토큰 Explorer 승인) + - 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx. + 서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다 + (2024-11 부터 도메인 전체 위임 없이 직접 추가 가능). + - 요청 머리글: Authorization(Bearer) · developer-token · login-customer-id(MCC 를 거쳐 들어갈 때만). + - 개발자 토큰 Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개. + +조회(REST googleAds:searchStream, GAQL) + SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, + metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date BETWEEN 'from' AND 'to' + - 날짜는 광고 계정 시간대 기준(한국 계정이면 KST). 광고가 없던 날은 행이 없을 수 있다. + - 금액 = cost_micros ÷ 1,000,000 을 원 단위로 반올림(구글 광고 비용은 부가세 별도). 계정 통화가 KRW 가 아니면 저장하지 않는다. + - ROAS(%) = 전환 가치 ÷ 비용 × 100(구글 광고 "전환 가치/비용"과 같은 값), 비용이 0 이면 없음. + - 나머지 항목(노출수·클릭수·클릭률·전환수·전환 가치)은 광고비 탭 구글 머리글 → 일자별 표. +API 버전은 설정 칸(기본 DEFAULT_VERSION) — 구글은 버전을 약 1년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다. +""" + +from __future__ import annotations + +import json +import re +import threading +import time +from datetime import date +from decimal import ROUND_HALF_UP, Decimal +from typing import Any + +import httpx + +from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured +from .base import AdDay, AdSource + +SCOPE = "https://www.googleapis.com/auth/adwords" +API_BASE = "https://googleads.googleapis.com" +DEFAULT_VERSION = "v26" # 2026-10 기준 최신(구글 광고 API 는 매월 부 버전·분기마다 새 버전) +TOKEN_URI = "https://oauth2.googleapis.com/token" +MAX_DAYS = 366 + +# 일자별 표(광고비 탭 구글 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산. +M_COST, M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "비용", "노출수", "클릭수", "클릭률(%)", "전환수", "전환 가치", "ROAS(%)" + +# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임) +_HINTS = { + "DEVELOPER_TOKEN_NOT_APPROVED": "개발자 토큰이 테스트 계정 전용입니다. API 센터에서 Explorer 이상 승인을 받은 토큰인지 확인하세요.", + "DEVELOPER_TOKEN_PROHIBITED": "이 개발자 토큰은 이 Google Cloud 프로젝트에서 쓸 수 없습니다(토큰을 받은 MCC·프로젝트 확인).", + "DEVELOPER_TOKEN_INVALID": "개발자 토큰이 올바르지 않습니다.", + "USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 " + "사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.", + "CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.", + "NOT_ADS_USER": "서비스 계정이 구글 광고 사용자로 등록돼 있지 않습니다(액세스 및 보안에서 추가).", + "INVALID_CUSTOMER_ID": "고객 ID 가 올바르지 않습니다(광고 계정 오른쪽 위 123-456-7890 형태 번호).", + "CUSTOMER_NOT_FOUND": "고객 ID 의 광고 계정을 찾을 수 없습니다.", + "SERVICE_ACCOUNT_NOT_ALLOWED": "이 계정은 서비스 계정 접근을 허용하지 않습니다.", +} + +_token_lock = threading.Lock() +_token_cache: dict[str, tuple[str, float]] = {} # (서비스 계정 이메일, 키 ID) → (액세스 토큰, 만료 시각) + + +def _digits(value: str) -> str: + return re.sub(r"[\s\-]", "", value or "") + + +def _http(ctx: AdapterContext) -> httpx.Client: + """HTTP 클라이언트 — 테스트가 바꿔 끼운다.""" + return httpx.Client(timeout=ctx.timeout_sec) + + +def parse_service_account(raw: str) -> dict[str, Any]: + """서비스 계정 JSON 키 → dict. 형식이 틀리면 ValueError(문구에 키 내용을 넣지 않는다).""" + try: + info = json.loads(raw) + except (TypeError, ValueError): + raise ValueError("서비스 계정 키가 JSON 형식이 아닙니다(구글 클라우드에서 내려받은 .json 파일 내용을 통째로 붙여 넣으세요).") from None + if not isinstance(info, dict) or info.get("type") != "service_account": + raise ValueError("서비스 계정 키가 아닙니다(\"type\": \"service_account\" 인 JSON 이어야 합니다).") + for k in ("client_email", "private_key"): + if not str(info.get(k) or "").strip(): + raise ValueError(f"서비스 계정 키에 {k} 가 없습니다.") + return info + + +def _won(micros: int) -> int: + return int((Decimal(int(micros)) / Decimal(1_000_000)).quantize(Decimal(1), rounding=ROUND_HALF_UP)) + + +def _num(v: Any) -> Decimal: + """REST 응답 숫자(int64 는 문자열, double 은 숫자, 0 은 아예 빠짐) → Decimal.""" + if v is None or v == "": + return Decimal(0) + return Decimal(str(v)) + + +def _google_error(resp: httpx.Response) -> tuple[str, str]: + """구글 오류 응답 → (오류 코드 이름, 사람이 읽을 문구). searchStream 오류는 배열에 싸여 올 수 있다.""" + try: + body = resp.json() + except ValueError: + return "", f"HTTP {resp.status_code}" + if isinstance(body, list): + body = next((b for b in body if isinstance(b, dict) and b.get("error")), body[0] if body else {}) + err = (body or {}).get("error") or {} + if isinstance(err, str): # 토큰 교환 오류 {"error": "invalid_grant", "error_description": "..."} + return err, str((body or {}).get("error_description") or err) + code_name, message = "", str(err.get("message") or f"HTTP {resp.status_code}") + for d in err.get("details") or []: + for e in (d or {}).get("errors") or []: + ec = e.get("errorCode") or {} + if ec: + code_name = str(next(iter(ec.values()))) + if e.get("message"): + message = str(e["message"]) + break + if code_name: + break + return code_name, message + + +class GoogleAdsSource(AdSource): + code = "google" + name = "구글 광고" + docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts" + note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. " + "준비: ① Google Cloud 서비스 계정 JSON 키 ② 구글 광고 API 센터의 개발자 토큰(Explorer 이상) " + "③ 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분).") + + def credential_fields(self) -> list[CredentialField]: + return [ + CredentialField("developer_token", "개발자 토큰", secret=True, + help="구글 광고 관리자(MCC) → 도구 → API 센터의 개발자 토큰. Explorer 이상 승인이어야 운영 계정을 조회할 수 있습니다."), + CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890", + help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."), + CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근", + help="서비스 계정을 관리자(MCC) 계정에 추가해 그 아래 광고 계정을 볼 때만 MCC 번호를 넣습니다."), + CredentialField("service_account_json", "서비스 계정 키(JSON)", secret=True, multiline=True, + help="Google Cloud → IAM → 서비스 계정 → 키 → JSON 으로 받은 파일 내용을 통째로 붙여 넣습니다. " + "저장 후에는 화면에 다시 보이지 않습니다."), + CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION, + help=f"비워 두면 {DEFAULT_VERSION}. 구글이 버전 종료를 알리면 새 버전(예: v27)으로 바꿉니다."), + ] + + def validate_credentials(self, values: dict[str, str]) -> list[str]: + errors = super().validate_credentials(values) + for key, label in (("customer_id", "고객 ID"), ("login_customer_id", "로그인 고객 ID")): + v = (values.get(key) or "").strip() + if v and v != "__stored__" and not re.fullmatch(r"\d{10}", _digits(v)): + errors.append(f"{label}는 숫자 10자리여야 합니다(예: 123-456-7890).") + sa = (values.get("service_account_json") or "").strip() + if sa and sa != "__stored__": + try: + parse_service_account(sa) + except ValueError as exc: + errors.append(str(exc)) + ver = (values.get("api_version") or "").strip() + if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}", ver): + errors.append("API 버전은 v26 처럼 v 뒤에 숫자로 입력하세요.") + return errors + + # ── 인증 ────────────────────────────────────────────── + def _access_token(self, ctx: AdapterContext, client: httpx.Client) -> str: + try: + info = parse_service_account(ctx.credentials.get("service_account_json")) + except ValueError as exc: + raise NotConfigured(str(exc)) from None + cache_key = f"{info['client_email']}|{info.get('private_key_id', '')}" + with _token_lock: + hit = _token_cache.get(cache_key) + if hit and hit[1] > time.time() + 120: + return hit[0] + from google.auth import crypt, jwt # noqa: WPS433 — google-auth(requirements) + + try: + signer = crypt.RSASigner.from_service_account_info(info) + except Exception: # noqa: BLE001 — 키 내용은 문구에 넣지 않는다 + raise AuthFailed("서비스 계정 키의 private_key 를 읽을 수 없습니다(JSON 파일 내용을 그대로 붙여 넣었는지 확인).") from None + now = int(time.time()) + token_uri = str(info.get("token_uri") or TOKEN_URI) + assertion = jwt.encode(signer, {"iss": info["client_email"], "scope": SCOPE, "aud": token_uri, + "iat": now, "exp": now + 3600}) + try: + resp = client.post(token_uri, data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": assertion.decode() if isinstance(assertion, bytes) else assertion}) + except httpx.HTTPError as exc: + raise ApiError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None + if resp.status_code != 200: + name, msg = _google_error(resp) + raise AuthFailed(f"서비스 계정 인증 실패({name or resp.status_code}): {msg[:200]} — 키가 삭제·사용 중지되지 않았는지 확인하세요.") + body = resp.json() + token = str(body.get("access_token") or "") + if not token: + raise AuthFailed("구글 인증 서버가 액세스 토큰을 주지 않았습니다.") + with _token_lock: + _token_cache[cache_key] = (token, time.time() + int(body.get("expires_in") or 3600)) + return token + + def _search(self, ctx: AdapterContext, query: str) -> list[dict[str, Any]]: + """GAQL 한 번 — searchStream 응답(묶음 배열)의 results 를 이어 붙여 돌려준다.""" + self.require_configured(ctx) + cid = _digits(ctx.credentials.get("customer_id")) + if not re.fullmatch(r"\d{10}", cid): + raise NotConfigured("고객 ID 는 숫자 10자리여야 합니다.") + version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION + with _http(ctx) as client: + token = self._access_token(ctx, client) + headers = {"Authorization": f"Bearer {token}", "developer-token": ctx.credentials.get("developer_token").strip(), + "Content-Type": "application/json"} + login = _digits(ctx.credentials.get("login_customer_id")) + if login: + headers["login-customer-id"] = login + ctx.progress.check() + try: + resp = client.post(f"{API_BASE}/{version}/customers/{cid}/googleAds:searchStream", + headers=headers, json={"query": query}) + except httpx.HTTPError as exc: + raise ApiError(f"구글 광고 API 에 연결하지 못했습니다({type(exc).__name__}).") from None + if resp.status_code == 404: + raise ApiError(f"구글 광고 API 버전 {version} 을(를) 쓸 수 없습니다(종료됐을 수 있음) — 실적 설정에서 API 버전을 최신으로 바꾸세요.") + if resp.status_code != 200: + name, msg = _google_error(resp) + hint = _HINTS.get(name, "") + text = f"구글 광고 API 오류({name or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "") + raise (AuthFailed if resp.status_code in (401, 403) else ApiError)(text) + try: + batches = resp.json() + except ValueError: + raise ApiError("구글 광고 API 응답을 읽을 수 없습니다.") from None + if isinstance(batches, dict): + batches = [batches] + out: list[dict[str, Any]] = [] + for b in batches or []: + out.extend((b or {}).get("results") or []) + return out + + # ── 연결 테스트 · 가져오기 ───────────────────────────── + def test_connection(self, ctx: AdapterContext) -> str: + rows = self._search(ctx, "SELECT customer.id, customer.descriptive_name, customer.currency_code, " + "customer.time_zone FROM customer LIMIT 1") + c = (rows[0].get("customer") if rows else None) or {} + currency = c.get("currencyCode") or "?" + msg = f"연결됨 — {c.get('descriptiveName') or '광고 계정'} · 통화 {currency} · 시간대 {c.get('timeZone') or '?'}" + if currency != "KRW": + msg += " (원화 계정이 아니라 광고비를 가져올 수 없습니다)" + return msg + + def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]: + if end < start: + start, end = end, start + if (end - start).days + 1 > MAX_DAYS: + raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.") + rows = self._search( + ctx, + "SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, " + "metrics.conversions, metrics.conversions_value FROM customer " + f"WHERE segments.date BETWEEN '{start.isoformat()}' AND '{end.isoformat()}'", + ) + sums: dict[date, dict[str, Decimal]] = {} + for r in rows: + cur = ((r.get("customer") or {}).get("currencyCode") or "").upper() + if cur and cur != "KRW": + raise ApiError(f"광고 계정 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.") + raw_day = (r.get("segments") or {}).get("date") + try: + day = date.fromisoformat(str(raw_day)) + except ValueError: + continue + m = r.get("metrics") or {} + acc = sums.setdefault(day, {"cost": Decimal(0), "impr": Decimal(0), "clicks": Decimal(0), + "conv": Decimal(0), "value": Decimal(0)}) + acc["cost"] += _num(m.get("costMicros")) + acc["impr"] += _num(m.get("impressions")) + acc["clicks"] += _num(m.get("clicks")) + acc["conv"] += _num(m.get("conversions")) + acc["value"] += _num(m.get("conversionsValue")) + out: list[AdDay] = [] + for day in sorted(sums): + a = sums[day] + amount = _won(int(a["cost"])) + cost = a["cost"] / Decimal(1_000_000) + roas = (a["value"] / cost * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if cost > 0 else None + ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None + metrics = { + M_COST: amount, + M_IMPR: int(a["impr"]), + M_CLICKS: int(a["clicks"]), + M_CTR: float(ctr) if ctr is not None else None, + M_CONV: float(a["conv"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)), + M_VALUE: int(a["value"].quantize(Decimal(1), rounding=ROUND_HALF_UP)), + M_ROAS: float(roas) if roas is not None else None, + } + out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics)) + return out diff --git a/app/modules/performance/ad_sources/registry.py b/app/modules/performance/ad_sources/registry.py new file mode 100644 index 0000000..05ef267 --- /dev/null +++ b/app/modules/performance/ad_sources/registry.py @@ -0,0 +1,17 @@ +"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다).""" + +from __future__ import annotations + +from .base import AdSource +from .google_ads import GoogleAdsSource + +_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),) +_BY_CODE = {s.code: s for s in _SOURCES} + + +def all_sources() -> tuple[AdSource, ...]: + return _SOURCES + + +def get_source(code: str) -> AdSource | None: + return _BY_CODE.get(code) diff --git a/app/modules/performance/ad_spend.py b/app/modules/performance/ad_spend.py index 11213cd..098c47c 100644 --- a/app/modules/performance/ad_spend.py +++ b/app/modules/performance/ad_spend.py @@ -2,7 +2,7 @@ 저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수). - 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀). - - 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계). + - 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만. 쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀): 1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비. @@ -341,8 +341,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe return merged, sorted(overlap) -# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) -DETAIL_CHANNELS = frozenset({"naver"}) +# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15) +DETAIL_CHANNELS = frozenset({"naver", "google"}) def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]: @@ -498,6 +498,9 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date, # 업로드로 들어온 칸(표시용) — "날짜|채널" "upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items() if s == "upload" and period.start <= d <= period.end), + # 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자) + "api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items() + if s == "api" and period.start <= d <= period.end), "upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS], "migration_needed": migration_needed, } diff --git a/app/modules/performance/ad_sync.py b/app/modules/performance/ad_sync.py new file mode 100644 index 0000000..9bf4720 --- /dev/null +++ b/app/modules/performance/ad_sync.py @@ -0,0 +1,119 @@ +"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api'). + + - 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다. + - 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류. + - 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다. + - 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact). +""" + +from __future__ import annotations + +import logging +import threading +from datetime import date +from typing import Any, Callable + +from .ad_sources.registry import all_sources, get_source +from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError +from .credentials import CredentialService +from .db import AdCredentialTable +from .security.redact import redact_text + +logger = logging.getLogger("performance.ad_sync") + +AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for) +_locks: dict[str, threading.Lock] = {} +_locks_guard = threading.Lock() + + +def _lock(code: str) -> threading.Lock: + with _locks_guard: + return _locks.setdefault(code, threading.Lock()) + + +class AdSyncBusy(Exception): + """같은 광고 채널 가져오기가 이미 진행 중.""" + + +def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService: + """광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표.""" + return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS) + + +class AdSyncService: + def __init__(self, store: Any, creds: CredentialService) -> None: + self._store = store + self._creds = creds + + def configured(self) -> dict[str, bool]: + return self._creds.configured_codes(list(all_sources())) + + def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> AdapterContext: + acc = self._creds.accessor(code, overrides=values, persist=values is None, user=user) + return AdapterContext(code=code, credentials=acc, timeout_sec=30.0) + + @staticmethod + def _message(exc: Exception, ctx: AdapterContext) -> str: + known = getattr(ctx.credentials, "known_secrets", lambda: [])() + return redact_text(str(getattr(exc, "message", "") or exc), known) + + def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]: + """values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험 — 그때는 상태를 기록하지 않는다.""" + src = get_source(code) + if src is None: + return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."} + ctx = self._ctx(code, values=values, user=user) + try: + src.require_configured(ctx) + msg = src.test_connection(ctx) + ok, status = True, "ok" + except AdapterError as exc: + ok, status, msg = False, exc.status, self._message(exc, ctx) + except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게 + logger.exception("ad test failed: %s", code) + ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}" + if not values: + self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test") + return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg, + "unsaved": bool(values)} + + def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]: + """기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy.""" + src = get_source(code) + if src is None: + raise KeyError(code) + lock = _lock(code) + if not lock.acquire(blocking=False): + raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.") + try: + ctx = self._ctx(code, user=user) + try: + src.require_configured(ctx) + days = src.fetch_days(ctx, start, end) + except AdapterError as exc: + msg = self._message(exc, ctx) + self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync") + return {"ok": False, "code": code, "name": src.name, "status": exc.status, + "label": STATUS_LABELS.get(exc.status, exc.status), "message": msg} + saved = self._store.replace_ad_api_range( + code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API") + self._store.record_ad_status(code, status="ok", ok=True, kind="sync") + return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days), + "from": start.isoformat(), "to": end.isoformat()} + finally: + lock.release() + + def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]: + """설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다.""" + out = [] + for code, ok in self.configured().items(): + if not ok: + continue + try: + out.append(self.sync(code, start, end, user=user)) + except AdSyncBusy as exc: + out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)}) + except Exception as exc: # noqa: BLE001 — 다음 채널은 계속 + logger.exception("ad sync failed: %s", code) + out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"}) + return out diff --git a/app/modules/performance/adapters/base.py b/app/modules/performance/adapters/base.py index 962c078..3b80c69 100644 --- a/app/modules/performance/adapters/base.py +++ b/app/modules/performance/adapters/base.py @@ -83,6 +83,7 @@ class CredentialField: """설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다. internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장. + multiline=True 면 여러 줄 입력칸(서비스 계정 JSON 키 등). """ key: str @@ -92,6 +93,7 @@ class CredentialField: help: str = "" placeholder: str = "" internal: bool = False + multiline: bool = False @dataclass diff --git a/app/modules/performance/auto_sync.py b/app/modules/performance/auto_sync.py index 7bf8bee..e43d183 100644 --- a/app/modules/performance/auto_sync.py +++ b/app/modules/performance/auto_sync.py @@ -1,6 +1,7 @@ """매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식). 기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다. + - 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관). - 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다. - 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음). - 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음). @@ -103,9 +104,18 @@ def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, except Exception: # noqa: BLE001 pass job.finish(error=error, last_update_at=last) + # 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15) + ads: list[dict[str, Any]] = [] + try: + from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433 + + ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER) + except Exception: # noqa: BLE001 — 스레드가 죽지 않게 + logger.exception("auto ad sync failed") ok = sum(1 for r in results if r.get("ok")) return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok, - "failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error} + "failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error, + "ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]} def start_auto_sync_thread(app_state: Any) -> bool: diff --git a/app/modules/performance/credentials.py b/app/modules/performance/credentials.py index dd3da1c..f95f91a 100644 --- a/app/modules/performance/credentials.py +++ b/app/modules/performance/credentials.py @@ -16,18 +16,21 @@ from .adapters.base import MarketplaceAdapter from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt -def aad_for(code: str, key: str) -> str: - """암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터.""" - return f"perf:{code}:{key}" +def aad_for(code: str, key: str, ns: str = "") -> str: + """암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터. ns = 이름 공간(광고 API 인증정보는 "ad:") — + 쇼핑몰 암호문과 광고 암호문을 서로 바꿔 넣어도 복호화되지 않는다.""" + return f"perf:{ns}{code}:{key}" class CredentialAccessor: """어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다.""" def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *, - overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None: + overrides: dict[str, str] | None = None, persist: bool = True, user: str = "", + aad_ns: str = "") -> None: self._store = store self._code = code + self._ns = aad_ns self._ring_loader = ring_loader self._rows = store.credential_rows(code) if store is not None else {} self._cache: dict[str, str] = {} @@ -46,7 +49,7 @@ class CredentialAccessor: row = self._rows.get(key) if not row: return "" - value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader()) + value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key, self._ns), ring=self._ring_loader()) self._cache[key] = value return value @@ -57,7 +60,7 @@ class CredentialAccessor: return ring = self._ring_loader() self._store.upsert_credential( - self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring), + self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key, self._ns), ring=ring), key_version=ring.current_version, user=self._user or "system", ) self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version} @@ -68,14 +71,17 @@ class CredentialAccessor: class CredentialService: - def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None: + """store = 인증정보 저장소(쇼핑몰: PerformanceStore, 광고 API: db.AdCredentialTable). aad_ns = 암호문 이름 공간.""" + + def __init__(self, store: Any, ring_loader: Callable[[], KeyRing], *, aad_ns: str = "") -> None: self._store = store self._ring_loader = ring_loader + self._ns = aad_ns def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> CredentialAccessor: return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides, - persist=persist, user=user) + persist=persist, user=user, aad_ns=self._ns) # ── 화면용 요약(비밀 원문 없음) ───────────────────────── def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]: @@ -87,11 +93,12 @@ class CredentialService: item: dict[str, Any] = { "key": f.key, "label": f.label, "secret": f.secret, "required": f.required, "help": f.help, "placeholder": f.placeholder, "has_value": row is not None, + "multiline": bool(getattr(f, "multiline", False)), "updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "", } if row is not None and not f.secret: try: - item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key), + item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key, self._ns), ring=self._ring_loader()) except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만 item["value"] = "" @@ -135,7 +142,7 @@ class CredentialService: if not v: continue self._store.upsert_credential( - adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key), ring=ring), + adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring), key_version=ring.current_version, user=user, ) saved.append(key) @@ -155,12 +162,12 @@ class CredentialService: continue code, key = row["marketplace_code"], row["credential_key"] try: - plain = decrypt(token, aad=aad_for(code, key), ring=ring) + plain = decrypt(token, aad=aad_for(code, key, self._ns), ring=ring) except Exception: # noqa: BLE001 failed += 1 continue self._store.upsert_credential( - code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring), + code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key, self._ns), ring=ring), key_version=ring.current_version, user="rekey", ) done += 1 diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py index f661a33..1fd9df0 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -560,3 +560,167 @@ class PerformanceDBStore: (STALE_RUN_AFTER,), ).fetchall() return [r["marketplace_code"] for r in rows] + + # ════════════════════════════════════════════════════════════ + # 광고 API 연동(마이그레이션 007) — 인증정보(암호문)·연결 상태·가져온 광고비 + # 읽기는 007 미적용이면 빈 값(설정 화면은 안내만), 쓰기는 AdMigrationNeeded("007"). + # ════════════════════════════════════════════════════════════ + def ad_api_ready(self) -> bool: + try: + with self._pool.connection() as conn: + conn.execute("SELECT 1 FROM perf_ad_credentials LIMIT 1").fetchall() + except pg_errors.UndefinedTable: + return False + return True + + def ad_credential_rows(self, code: str) -> dict[str, dict[str, Any]]: + try: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT credential_key, encrypted_value, key_version, updated_at, updated_by " + "FROM perf_ad_credentials WHERE channel_code = %s", (code,), + ).fetchall() + except pg_errors.UndefinedTable: + return {} + return {r["credential_key"]: r for r in rows} + + def ad_credential_keys_by_code(self) -> dict[str, set[str]]: + try: + with self._pool.connection() as conn: + rows = conn.execute("SELECT channel_code, credential_key FROM perf_ad_credentials").fetchall() + except pg_errors.UndefinedTable: + return {} + out: dict[str, set[str]] = {} + for r in rows: + out.setdefault(r["channel_code"], set()).add(r["credential_key"]) + return out + + def upsert_ad_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None: + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + try: + with self._pool.connection() as conn: + conn.execute( + """ + INSERT INTO perf_ad_credentials (channel_code, credential_key, encrypted_value, key_version, updated_by) + VALUES (%s, %s, %s, %s, %s) + ON CONFLICT (channel_code, credential_key) DO UPDATE + SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version, + updated_by = EXCLUDED.updated_by + """, + (code, key, encrypted_value, key_version, user), + ) + except pg_errors.UndefinedTable: + raise AdMigrationNeeded("007") from None + + def delete_ad_credential(self, code: str, key: str) -> None: + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + try: + with self._pool.connection() as conn: + conn.execute("DELETE FROM perf_ad_credentials WHERE channel_code = %s AND credential_key = %s", (code, key)) + except pg_errors.UndefinedTable: + raise AdMigrationNeeded("007") from None + + def all_ad_credential_rows(self) -> list[dict[str, Any]]: + try: + with self._pool.connection() as conn: + return conn.execute( + "SELECT channel_code AS marketplace_code, credential_key, encrypted_value, key_version " + "FROM perf_ad_credentials" + ).fetchall() + except pg_errors.UndefinedTable: + return [] + + def ad_source_statuses(self) -> dict[str, dict[str, Any]]: + try: + with self._pool.connection() as conn: + rows = conn.execute("SELECT * FROM perf_ad_source_status").fetchall() + except pg_errors.UndefinedTable: + return {} + return {r["channel_code"]: {k: _iso(v) for k, v in r.items()} for r in rows} + + def record_ad_status(self, code: str, *, status: str, ok: bool, error: str = "", kind: str = "test") -> None: + """연결 테스트(kind=test) 또는 가져오기(kind=sync) 결과. 오류가 없으면 예전 오류 문구는 그대로 둔다.""" + if kind == "sync": + sql = """ + INSERT INTO perf_ad_source_status (channel_code, status, last_sync_at, last_success_sync_at, last_error, last_error_at) + VALUES (%(c)s, %(s)s, now(), CASE WHEN %(ok)s THEN now() END, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END) + ON CONFLICT (channel_code) DO UPDATE + SET status = EXCLUDED.status, last_sync_at = now(), + last_success_sync_at = CASE WHEN %(ok)s THEN now() ELSE perf_ad_source_status.last_success_sync_at END, + last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END, + last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END + """ + else: + sql = """ + INSERT INTO perf_ad_source_status (channel_code, status, last_test_at, last_test_ok, last_error, last_error_at) + VALUES (%(c)s, %(s)s, now(), %(ok)s, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END) + ON CONFLICT (channel_code) DO UPDATE + SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = %(ok)s, + last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END, + last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END + """ + try: + with self._pool.connection() as conn: + conn.execute(sql, {"c": code, "s": status, "ok": ok, "e": error}) + except pg_errors.UndefinedTable: + return # 007 미적용 — 상태 기록만 못 함(가져오기 자체는 막지 않음) + + def replace_ad_api_range(self, code: str, start: date, end: date, + days: list[tuple[date, int, Any, dict[str, Any] | None]], *, user: str = "") -> int: + """광고 API 로 가져온 기간을 한 트랜잭션으로 반영 — days 의 날은 덮어쓰고(source='api', ROAS·보고서 항목 포함, + 직접 입력·업로드 값이 있던 날도 API 값으로), 기간 안에서 API 가 돌려주지 않은 날은 **예전 API 값만** 지운다 + (직접 입력·업로드 값은 그대로). days = [(날짜, 금액, ROAS, 항목)]. 반영한 날 수.""" + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + keep = {d for d, _, _, _ in days} + try: + with self._pool.connection() as conn: + with conn.transaction(): + with conn.cursor() as cur: + old = cur.execute( + "SELECT spend_date FROM perf_ad_spend WHERE channel_code = %s AND source = 'api' " + "AND spend_date BETWEEN %s AND %s", (code, start, end), + ).fetchall() + gone = [(code, r["spend_date"]) for r in old if r["spend_date"] not in keep] + if gone: + cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s " + "AND source = 'api'", gone) + rows = [(code, d, int(a), "api", user, r, Jsonb(m) if m is not None else None) for d, a, r, m in days] + if rows: + cur.executemany( + "INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) " + "VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE " + "SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, " + "roas = EXCLUDED.roas, metrics = EXCLUDED.metrics", + rows, + ) + except pg_errors.UndefinedTable: + raise AdMigrationNeeded("005") from None + except pg_errors.UndefinedColumn: + raise AdMigrationNeeded("006") from None + return len(days) + + +class AdCredentialTable: + """광고 API 인증정보 표(perf_ad_credentials)를 쇼핑몰 인증정보 저장소와 같은 이름으로 — credentials.CredentialService 가 + 그대로 쓴다(저장·요약·재암호화). 채널 코드가 쇼핑몰 코드 자리에 들어간다.""" + + def __init__(self, store: Any) -> None: + self._store = store + + def credential_rows(self, code: str) -> dict[str, dict[str, Any]]: + return self._store.ad_credential_rows(code) + + def credential_keys_by_code(self) -> dict[str, set[str]]: + return self._store.ad_credential_keys_by_code() + + def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None: + self._store.upsert_ad_credential(code, key, encrypted_value=encrypted_value, key_version=key_version, user=user) + + def delete_credential(self, code: str, key: str) -> None: + self._store.delete_ad_credential(code, key) + + def all_credential_rows(self) -> list[dict[str, Any]]: + return self._store.all_ad_credential_rows() diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 6e48b78..0bb3b26 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -17,8 +17,11 @@ JSON API — 모듈 권한 PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지) POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액, 네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목) - GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭) + GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글 머리글 클릭) + POST /performance/api/ad-sources/{code}/sync 광고 API(구글 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자 JSON API — 관리자 + GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음) + POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값) PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부 POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일) DELETE /performance/api/marketplaces/{code}/rates/{id} @@ -34,7 +37,7 @@ JSON API — 관리자 from __future__ import annotations -from datetime import date +from datetime import date, timedelta from decimal import Decimal, InvalidOperation from pathlib import Path from typing import Any @@ -59,10 +62,13 @@ AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 0 "먼저 적용해야 합니다.") AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006" "(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.") +AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007" + "(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.") def _ad_migration_help(exc: Exception) -> str: - return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP + text = str(exc) + return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 " "먼저 적용해야 합니다.") @@ -155,6 +161,11 @@ def ads_page( custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(), sales_codes=[m["code"] for m in _sales_marketplaces(store)], ) + # [구글 광고 불러오기] — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동만 + from .ad_sources.registry import get_source # noqa: WPS433 + + _, ad_sync = _ad_services(store) + ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in ad_sync.configured().items() if ok] return render_template(request, "performance/ads.html", {**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) @@ -171,14 +182,37 @@ def settings_page(request: Request): from .dashboard import build_settings # noqa: WPS433 creds, _ = common.services(request, store) + ad_creds, ad_sync = _ad_services(store) + versions = creds.key_versions_in_use() + for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키 + versions[v] = versions.get(v, 0) + n ctx = build_settings( store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(), - key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(), + key_versions_in_use=versions, sample_count=store.sample_count(), ) + ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured()) + ctx["ad_api_ready"] = store.ad_api_ready() return render_template(request, "performance/settings.html", {**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx}) +def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]: + """실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기.""" + from .ad_sources.registry import all_sources # noqa: WPS433 + from .adapters.base import STATUS_LABELS # noqa: WPS433 + + statuses = store.ad_source_statuses() + rows = [] + for s in all_sources(): + st = statuses.get(s.code, {}) + status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured") + rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status, + "status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"), + "last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"), + "last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")}) + return rows + + # ════════════════════════════════════════════════════════════ # JSON API — 모듈 권한 # ════════════════════════════════════════════════════════════ @@ -510,6 +544,113 @@ def api_ad_spend_upload( "from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None}) +# ════════════════════════════════════════════════════════════ +# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자) +# ════════════════════════════════════════════════════════════ +def _ad_services(store: Any): + """(광고 인증정보 서비스, 광고 가져오기 서비스).""" + from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433 + + creds = ad_credentials(store, common.key_ring) + return creds, AdSyncService(store, creds) + + +def _ad_source_or_404(code: str): + from .ad_sources.registry import get_source # noqa: WPS433 + + src = get_source(code) + if src is None: + raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.") + return src + + +@router.get("/api/ad-sources/{code}/credentials") +def api_ad_source_credentials(request: Request, code: str) -> JSONResponse: + """입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양.""" + store, _ = common.require_store(request, admin=True) + src = _ad_source_or_404(code) + creds, _ = _ad_services(store) + info = creds.describe(src) + if not store.ad_api_ready(): + info["decrypt_error"] = AD_MIGRATION_HELP_007 + return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url, + "key": common.key_status(), **info}) + + +@router.put("/api/ad-sources/{code}/credentials") +def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + store, user = common.require_store(request, admin=True) + src = _ad_source_or_404(code) + if not common.key_status()["ok"]: + raise HTTPException(status_code=503, detail=common.key_status()["message"]) + creds, _ = _ad_services(store) + values = _clean_values(src, payload) + clear = [str(k) for k in (payload.get("clear") or [])] + merged = creds.merged_values(src, values) + for k in clear: + if k in merged and not values.get(k): + merged[k] = "" + errors = src.validate_credentials(merged) + if errors: + raise HTTPException(status_code=400, detail=" ".join(errors)) + try: + saved = creds.save(src, values, clear=clear, user=user["email"]) + except AdMigrationNeeded as exc: + raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None + return JSONResponse({"saved": saved, **creds.describe(src)}) + + +@router.post("/api/ad-sources/{code}/test") +def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse: + """values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값).""" + store, user = common.require_store(request, admin=True) + src = _ad_source_or_404(code) + _, ad_sync = _ad_services(store) + values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()} + return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"])) + + +@router.post("/api/ad-sources/{code}/sync") +def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse: + """광고비 탭 [구글 광고 불러오기] — 기간(from·to, 없으면 최근 N일)을 가져와 저장. 오늘 뒤는 잘라낸다. + 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만.""" + from app.store import is_admin # noqa: WPS433 + + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + from .ad_sync import AdSyncBusy # noqa: WPS433 + from .auto_sync import sync_days # noqa: WPS433 + + store, user = common.require_store(request) + src = _ad_source_or_404(code) + today = today_kst() + end = _parse_date(payload.get("to"), field="종료일") or today + start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1)) + if end < start: + start, end = end, start + end = min(end, today) + if start > end: + raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.") + days = (end - start).days + 1 + if days > MAX_BACKFILL_DAYS: + raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.") + if days > MAX_USER_SYNC_DAYS and not is_admin(user): + raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.") + _, ad_sync = _ad_services(store) + if not ad_sync.configured().get(code): + raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.") + try: + res = ad_sync.sync(code, start, end, user=user["email"]) + except AdSyncBusy as exc: + raise HTTPException(status_code=409, detail=str(exc)) from None + except AdMigrationNeeded as exc: + raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None + if not res.get("ok"): + return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res}) + return JSONResponse(res) + + # ════════════════════════════════════════════════════════════ # JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자) # ════════════════════════════════════════════════════════════ @@ -678,4 +819,10 @@ def api_rekey(request: Request) -> JSONResponse: if not common.key_status()["ok"]: raise HTTPException(status_code=503, detail=common.key_status()["message"]) creds, _ = common.services(request, store) - return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()}) + ad_creds, _ = _ad_services(store) + shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키 + versions = creds.key_versions_in_use() + for v, n in ad_creds.key_versions_in_use().items(): + versions[v] = versions.get(v, 0) + n + return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"], + "versions_in_use": versions}) diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index f4ecff0..7b17ccd 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -72,17 +72,24 @@

{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}

+
+ {% for s in ad_sync_sources %} + + {% endfor %} {% if upload_channels %} {% endif %} +
- {% for c in codes %}{% if c in detail_channels %}{% else %}{% endif %}{% endfor %} + {% for c in codes %}{% if c in detail_channels %}{% else %}{% endif %}{% endfor %} @@ -96,9 +103,10 @@ {% set v = r.cells[c].gross %} {% if r.kind == 'day' and not r.future and not migration_needed %} {% set up = (r.date ~ '|' ~ c) in upload_cells %} - + title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}">{{ won(v) }}{{ roas(r.roas[c]) }} {% else %} {% endif %} @@ -111,9 +119,10 @@ {% if period_kind != 'year' %}

날짜 칸을 눌러 그날 광고비를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. - 칸은 광고비(ROAS%) — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고, - 네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목. - 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.

+ 칸은 광고비(ROAS%) — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고, + 네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목. + 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다. + 구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.

{% endif %} @@ -191,9 +200,10 @@

- 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값). + 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용(부가세 별도). + ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값). 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출. - 구글·메타는 지금은 직접 입력합니다. + 메타는 지금은 직접 입력합니다.

@@ -214,4 +224,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 964f878..32f0d5d 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -255,4 +255,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index b68c0de..dc706d7 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} @@ -103,6 +103,50 @@ {% if is_admin %} + {# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장. + 가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #} +
+
+

광고 API 연동

+ 광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다. + 설정이 끝나면 광고비 탭 [구글 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다. +
+ {% if not ad_api_ready %} +
광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007 + (scripts/sql/performance_db_007_ad_api.sql)을 적용해야 저장할 수 있습니다.
+ {% endif %} +
+
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{{ names[c] }} {{ names[c] }} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}
{{ won(v) }}{{ roas(r.roas[c]) }}{{ won(v) }}{{ roas(r.roas[c]) }}
+ + + + + {% for a in ad_sources %} + + + + + + + + {% endfor %} + +
광고API 설정연결 상태마지막 가져오기
{{ a.name }}{% if a.configured %}설정완료{% else %}미설정{% endif %} + + {{ a.status_label }} + {% if a.last_error and a.status not in ('ok',) %}
{{ a.last_error }}
{% endif %} +
{{ when(a.last_success_sync_at) }} + + +
+
+

+ 구글 광고: 비용은 구글 광고 화면의 "비용"(부가세 별도), ROAS = 전환 가치 ÷ 비용. 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다. + 가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다. +

+
+

인증정보 암호화

@@ -120,7 +164,7 @@

{% endif %}

- API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌 + API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌 서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.

@@ -204,4 +248,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_ad_spend.py b/app/modules/performance/tests/test_ad_spend.py index 4186110..4287834 100644 --- a/app/modules/performance/tests/test_ad_spend.py +++ b/app/modules/performance/tests/test_ad_spend.py @@ -126,7 +126,8 @@ def test_ad_dashboard_month(): assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000 assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"] assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"] - assert ctx["detail_channels"] == ["naver"] + assert ctx["detail_channels"] == ["google", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15) + assert ctx["api_cells"] == [] day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01") assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000 assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000 diff --git a/app/modules/performance/tests/test_auto_sync.py b/app/modules/performance/tests/test_auto_sync.py index f1116da..7d1b928 100644 --- a/app/modules/performance/tests/test_auto_sync.py +++ b/app/modules/performance/tests/test_auto_sync.py @@ -60,7 +60,9 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch): monkeypatch.setattr(jobs, "running_job", lambda: None) res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10) assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)] - assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": ""} + # 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로 + assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "", + "ads": []} monkeypatch.setattr(jobs, "running_job", lambda: object()) assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"] diff --git a/app/modules/performance/tests/test_google_ads.py b/app/modules/performance/tests/test_google_ads.py new file mode 100644 index 0000000..c833085 --- /dev/null +++ b/app/modules/performance/tests/test_google_ads.py @@ -0,0 +1,292 @@ +"""구글 광고 API 연동(2026-10-15) — 입력 검사·토큰·조회·변환·오류 안내·저장 서비스·라우터. 구글 서버는 가짜(httpx MockTransport).""" + +from __future__ import annotations + +import json +from datetime import date +from decimal import Decimal +from urllib.parse import parse_qs + +import httpx +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from app.modules.performance import ad_sync +from app.modules.performance.ad_sources import google_ads as ga +from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured +from app.modules.performance.credentials import CredentialService, aad_for +from app.modules.performance.security import crypto + +KEY1 = "11" * 32 + + +def _sa_json() -> str: + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, + serialization.NoEncryption()).decode() + return json.dumps({"type": "service_account", "client_email": "erp@proj.iam.gserviceaccount.com", + "private_key_id": "kid1", "private_key": pem, "token_uri": "https://oauth2.googleapis.com/token"}) + + +SA = _sa_json() + + +class Creds: + def __init__(self, values): + self.values = values + + def get(self, key): + return self.values.get(key, "") + + def has(self, key): + return bool(self.values.get(key)) + + def set(self, key, value): + self.values[key] = value + + def known_secrets(self): + return [v for v in self.values.values() if v] + + +def _ctx(**over): + values = {"developer_token": "DEVTOKEN", "customer_id": "123-456-7890", "service_account_json": SA} + values.update(over) + return AdapterContext(code="google", credentials=Creds(values)) + + +def _install(monkeypatch, handler): + """구글(토큰·광고 API) 가짜 서버 — handler(request) 가 searchStream 응답을 만든다. 보낸 요청을 돌려준다.""" + ga._token_cache.clear() + seen = [] + + def route(request: httpx.Request) -> httpx.Response: + seen.append(request) + if request.url.host == "oauth2.googleapis.com": + form = parse_qs(request.content.decode()) + assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] and form["assertion"][0].count(".") == 2 + return httpx.Response(200, json={"access_token": "ya29.TOKEN", "expires_in": 3600}) + return handler(request) + + monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route))) + return seen + + +ROWS = [{"results": [ + {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-01"}, + "metrics": {"costMicros": "123456500000", "impressions": "20000", "clicks": "400", "conversions": 12.5, + "conversionsValue": 617282.5}}, + {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-02"}, + "metrics": {"impressions": "50"}}, # 비용 0(값이 빠진 칸) +]}, {"results": [ + {"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-03"}, + "metrics": {"costMicros": "1000000", "clicks": "1", "impressions": "10", "conversionsValue": 3000}}, +]}] + + +def test_validate_credentials(): + src = ga.GoogleAdsSource() + ok = {"developer_token": "x", "customer_id": "123-456-7890", "service_account_json": SA} + assert src.validate_credentials(ok) == [] + assert src.validate_credentials({**ok, "service_account_json": "__stored__", "developer_token": "__stored__"}) == [] + errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26", + "service_account_json": '{"type": "authorized_user"}'}) + assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음 + assert "입력하세요" in " ".join(src.validate_credentials({})) + assert "JSON" in " ".join(src.validate_credentials({**ok, "service_account_json": "not json"})) + + +def test_fetch_days_converts_and_sends_headers(monkeypatch): + seen = _install(monkeypatch, lambda req: httpx.Response(200, json=ROWS)) + days = ga.GoogleAdsSource().fetch_days(_ctx(login_customer_id="999-888-7777", api_version="v27"), + date(2026, 10, 1), date(2026, 10, 3)) + api = seen[-1] + assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream" + assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and api.headers["developer-token"] == "DEVTOKEN" + assert api.headers["login-customer-id"] == "9998887777" + q = json.loads(api.content)["query"] + assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q + d1, d2, d3 = days + assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 123457, Decimal("500.00")) # 123,456.5원 → 반올림, 617,282.5 ÷ 123,456.5 + assert d1.metrics == {"비용": 123457, "노출수": 20000, "클릭수": 400, "클릭률(%)": 2.0, "전환수": 12.5, + "전환 가치": 617283, "ROAS(%)": 500.0} + assert (d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (0, None, 0.0) # 비용 0 → ROAS 없음 + assert (d3.amount, d3.roas) == (1, Decimal("300000.00")) + # 토큰은 한 번만 받아 두고 다시 쓴다 + ga.GoogleAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) + assert sum(1 for r in seen if r.url.host == "oauth2.googleapis.com") == 1 + assert "login-customer-id" not in seen[-1].headers and "/v26/" in str(seen[-1].url) # 비우면 MCC 없음·기본 버전 + + +def test_errors_are_explained(monkeypatch): + src = ga.GoogleAdsSource() + denied = [{"error": {"code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED", + "details": [{"errors": [{"errorCode": {"authorizationError": "USER_PERMISSION_DENIED"}, + "message": "User doesn't have permission to access customer."}]}]}}] + _install(monkeypatch, lambda req: httpx.Response(403, json=denied)) + with pytest.raises(AuthFailed) as e: + src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) + assert "USER_PERMISSION_DENIED" in e.value.message and "액세스 및 보안" in e.value.message + + _install(monkeypatch, lambda req: httpx.Response(404, text="Not Found")) + with pytest.raises(ApiError) as e: + src.fetch_days(_ctx(api_version="v19"), date(2026, 10, 1), date(2026, 10, 1)) + assert "v19" in e.value.message and "API 버전" in e.value.message + + usd = [{"results": [{"customer": {"currencyCode": "USD"}, "segments": {"date": "2026-10-01"}, "metrics": {}}]}] + _install(monkeypatch, lambda req: httpx.Response(200, json=usd)) + with pytest.raises(ApiError, match="USD"): + src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) + + with pytest.raises(NotConfigured): + src.fetch_days(_ctx(customer_id=""), date(2026, 10, 1), date(2026, 10, 1)) + + ga._token_cache.clear() + + def bad_token(request): + return httpx.Response(400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."}) + + monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(bad_token))) + with pytest.raises(AuthFailed, match="invalid_grant"): + src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1)) + + +def test_connection_message(monkeypatch): + body = [{"results": [{"customer": {"id": "1234567890", "descriptiveName": "미라네주방", "currencyCode": "KRW", + "timeZone": "Asia/Seoul"}}]}] + _install(monkeypatch, lambda req: httpx.Response(200, json=body)) + assert ga.GoogleAdsSource().test_connection(_ctx()) == "연결됨 — 미라네주방 · 통화 KRW · 시간대 Asia/Seoul" + + +def test_ad_credentials_use_own_namespace(): + """광고 인증정보 암호문은 "perf:ad:{채널}:{항목}" 에 묶인다 — 쇼핑몰 암호문과 바꿔 넣으면 복호화되지 않는다.""" + ring = crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY1}) + + class Table: + def __init__(self): + self.rows = {} + + def credential_rows(self, code): + return {k: {"encrypted_value": v, "key_version": 1} for (c, k), v in self.rows.items() if c == code} + + def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""): + self.rows[(code, key)] = encrypted_value + + t = Table() + svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS) + svc.save(ga.GoogleAdsSource(), {"developer_token": "DEV", "customer_id": "1234567890"}, user="king") + assert svc.accessor("google").get("developer_token") == "DEV" + assert aad_for("google", "developer_token", "ad:") == "perf:ad:google:developer_token" + with pytest.raises(Exception): + crypto.decrypt(t.rows[("google", "developer_token")], aad=aad_for("google", "developer_token"), ring=ring) + + +class FakeStore: + def __init__(self): + self.replaced, self.status = [], [] + + def ad_credential_keys_by_code(self): + return {"google": {"developer_token", "customer_id", "service_account_json"}} + + def ad_credential_rows(self, code): + return {} + + def replace_ad_api_range(self, code, start, end, days, *, user=""): + self.replaced.append((code, start, end, days, user)) + return len(days) + + def record_ad_status(self, code, *, status, ok, error="", kind="test"): + self.status.append((code, status, ok, error, kind)) + + +def _service(store, source): + svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None)) + svc.configured = lambda: {"google": True} + svc._ctx = lambda code, values=None, user="": _ctx() + return svc + + +def test_sync_service_saves_and_records(monkeypatch): + store = FakeStore() + from app.modules.performance.ad_sources.base import AdDay + + src = ga.GoogleAdsSource() + monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})]) + monkeypatch.setattr(ad_sync, "get_source", lambda code: src) + svc = _service(store, src) + res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 3), user="king@x") + assert res["ok"] and res["days"] == 1 and res["total"] == 1000 + assert store.replaced == [("google", date(2026, 10, 1), date(2026, 10, 3), + [(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})], "king@x")] + assert store.status[-1] == ("google", "ok", True, "", "sync") + + # 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림) + def boom(ctx, s, e): + raise AuthFailed("토큰 DEVTOKEN 거부") + + monkeypatch.setattr(src, "fetch_days", boom) + res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1)) + assert not res["ok"] and res["status"] == "auth_failed" and "DEVTOKEN" not in res["message"] + assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False) + + # 같은 채널 동시 실행 막기 + lock = ad_sync._lock("google") + lock.acquire() + try: + with pytest.raises(ad_sync.AdSyncBusy): + svc.sync("google", date(2026, 10, 1), date(2026, 10, 1)) + assert svc.sync_all(date(2026, 10, 1), date(2026, 10, 1))[0]["skipped"] + finally: + lock.release() + + +def test_sync_endpoint(monkeypatch): + import importlib + + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.modules.performance import common + + perf_router = importlib.import_module("app.modules.performance.router") + calls, admin = [], {"v": False} + + class Svc: + def __init__(self): + self.result = {"ok": True, "code": "google", "name": "구글 광고", "days": 3, "total": 9000} + self.conf = {"google": True} + + def configured(self): + return self.conf + + def sync(self, code, start, end, *, user=""): + calls.append((code, start, end, user)) + return {**self.result, "from": start.isoformat(), "to": end.isoformat()} + + svc = Svc() + monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"})) + monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15)) + monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, svc)) + import app.store as app_store + + monkeypatch.setattr(app_store, "is_admin", lambda user: admin["v"]) + app = FastAPI() + app.include_router(perf_router.router) + client = TestClient(app) + + r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-10-01", "to": "2026-10-31"}) + assert r.status_code == 200 and r.json()["to"] == "2026-10-15" # 오늘 뒤는 잘라냄 + assert calls[-1] == ("google", date(2026, 10, 1), date(2026, 10, 15), "king@x") + r = client.post("/performance/api/ad-sources/google/sync", json={}) + assert r.status_code == 200 and calls[-1][1] == date(2026, 10, 6) # 기본 = 최근 10일 + r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}) + assert r.status_code == 403 # 92일 넘으면 관리자만 + admin["v"] = True + assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200 + assert client.post("/performance/api/ad-sources/meta/sync", json={}).status_code == 404 + svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"} + r = client.post("/performance/api/ad-sources/google/sync", json={}) + assert r.status_code == 502 and "권한 없음" in r.json()["detail"] + svc.conf = {"google": False} + r = client.post("/performance/api/ad-sources/google/sync", json={}) + assert r.status_code == 400 and "설정" in r.json()["detail"] diff --git a/app/static/performance.css b/app/static/performance.css index d773ea9..372ecda 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -58,6 +58,13 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } .perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); } .perf-ads .perf-chart .bar { fill: var(--perf-ad); } .perf-ads td.is-upload .v-gross { color: var(--perf-ad); } +/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */ +.perf-ads td.is-api .v-gross { color: #1e8e3e; } +.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.perf-ad-sync-btn { display: inline-flex; align-items: center; gap: 4px; } +.perf-ad-sync-btn .material-symbols-outlined { font-size: 16px; color: #1e8e3e; } +/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */ +.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; } /* "광고비(ROAS%)" — ROAS 는 작게 옅게 붙인다. 입력 중엔 숫자처럼 자리만 남기고 숨김 */ .perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); } .perf-row-total .perf-roas { color: #bbb; } diff --git a/app/static/performance.js b/app/static/performance.js index b3d8cac..712d61d 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -383,7 +383,27 @@ }); }); - // 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계. + // [구글 광고 불러오기] — 광고 API 로 지금 보는 기간(오늘까지)을 가져와 저장(같은 날 덮어씀) → 새로고침. + root.addEventListener("click", async function (e) { + const btn = e.target.closest("[data-ad-sync]"); + if (!btn || btn.disabled) return; + const label = btn.textContent; + btn.disabled = true; + btn.textContent = "불러오는 중…"; + try { + const res = await api("POST", "/performance/api/ad-sources/" + encodeURIComponent(btn.dataset.adSync) + "/sync", + { from: data.period_start, to: data.period_end }); + await alertMsg(res.name + " — " + res.from + " ~ " + res.to + "\n" + (res.days ? res.days + "일, 광고비 ₩" + fmt(res.total) + " 반영" : "이 기간 광고비가 없습니다."), + { tone: "ok" }); + location.reload(); + } catch (err) { + alertMsg(err.message); + btn.disabled = false; + btn.textContent = label; + } + }); + + // 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계. root.addEventListener("click", async function (e) { const btn = e.target.closest("[data-detail-channel]"); if (!btn) return; @@ -394,7 +414,7 @@ try { const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" + encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end)); - if (!res.rows || !res.rows.length) { m.body.innerHTML = '

이 기간에 올린 보고서 자료가 없습니다.

'; return; } + if (!res.rows || !res.rows.length) { m.body.innerHTML = '

이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).

'; return; } const cols = res.columns || []; const cell = function (v) { if (v == null || v === "") return '–'; @@ -413,7 +433,7 @@ }).join("") + '합계' + cols.map(function (c) { return '' + cell((res.total || {})[c]) + ""; }).join("") + "
" + - '

합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.

'; + '

합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.

'; } catch (err) { m.body.innerHTML = '

' + esc(err.message) + "

"; } @@ -717,9 +737,11 @@ if (!btn) return; const tr = btn.closest("tr"); const code = tr.dataset.code, name = tr.dataset.name; + // 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰 + const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/"; if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1"); - else if (btn.dataset.act === "creds") openCreds(code, name); - else if (btn.dataset.act === "test") runTest(code, name, btn); + else if (btn.dataset.act === "creds") openCreds(code, name, base); + else if (btn.dataset.act === "test") runTest(code, name, btn, base); }); function today() { @@ -790,11 +812,12 @@ } // ── API 인증정보 ── - async function openCreds(code, name) { + async function openCreds(code, name, base) { + base = base || "/performance/api/marketplaces/"; const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } }); m.body.innerHTML = '

불러오는 중…

'; let info; - try { info = await api("GET", "/performance/api/marketplaces/" + code + "/credentials"); } + try { info = await api("GET", base + code + "/credentials"); } catch (err) { m.body.innerHTML = '

' + esc(err.message) + "

"; return; } const result = el("span", { class: "perf-test-result" }); @@ -818,10 +841,16 @@ ? '현재 값: •••••••• (저장됨' + (f.updated_at ? ", " + esc(f.updated_at.slice(0, 16).replace("T", " ")) : "") + ")" : '저장된 값 없음'; } + // 여러 줄 항목(서비스 계정 JSON 키 등)은 textarea — 비밀값이면 저장 후 내용은 다시 보이지 않는다 + const field = f.multiline + ? '" + : '"; return '
" + state + - '" + + field + (f.help ? '
' + esc(f.help) + "
" : "") + (f.secret && f.has_value && !f.required ? '' : "") + "
"; @@ -835,9 +864,9 @@ saveBtn.addEventListener("click", async function () { saveBtn.disabled = true; try { - await api("PUT", "/performance/api/marketplaces/" + code + "/credentials", { values: typed(), clear: cleared() }); + await api("PUT", base + code + "/credentials", { values: typed(), clear: cleared() }); m.changed = true; - m.body.querySelectorAll("input[type=password]").forEach(function (i) { i.value = ""; }); + m.body.querySelectorAll("input[type=password], textarea.perf-cred-multi").forEach(function (i) { i.value = ""; }); result.className = "perf-test-result"; result.textContent = "저장했습니다. 연결 확인 중…"; await test(false); @@ -850,7 +879,7 @@ function typed() { const out = {}; - m.body.querySelectorAll("input[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); }); + m.body.querySelectorAll("input[data-key], textarea[data-key]").forEach(function (i) { if (i.value.trim()) out[i.dataset.key] = i.value.trim(); }); return out; } function cleared() { @@ -862,7 +891,7 @@ result.className = "perf-test-result"; result.textContent = "연결 확인 중…"; try { - const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", withTyped ? { values: typed() } : {}); + const res = await api("POST", base + code + "/test", withTyped ? { values: typed() } : {}); result.className = "perf-test-result " + (res.ok ? "is-ok" : "is-bad"); result.textContent = (res.ok ? "● " : "● " + res.label + " — ") + res.message + (res.unsaved ? " (저장 안 한 값으로 시험)" : ""); if (!res.unsaved) m.changed = true; @@ -874,12 +903,12 @@ testBtn.addEventListener("click", function () { test(true); }); } - async function runTest(code, name, btn) { + async function runTest(code, name, btn, base) { btn.disabled = true; const label = btn.textContent; btn.textContent = "확인 중…"; try { - const res = await api("POST", "/performance/api/marketplaces/" + code + "/test", {}); + const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {}); await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined); location.reload(); } catch (err) { diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 0927286..3fbf417 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -211,6 +211,22 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend" 되돌리기(보고서 ROAS·상세만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas;"` +## 실적 광고 API 연동 마이그레이션 (performance_db 007) + +007은 광고 API(구글 광고) 인증정보 표 `perf_ad_credentials`·연결 상태 표 `perf_ad_source_status` 두 개만 만든다(기존 표·데이터 그대로, +다시 실행 가능). 005·006 다음에 적용한다. 미적용이면 실적 설정 → 광고 API 연동 카드에 안내가 나오고 저장이 503, 광고비 탭은 그대로. +새 환경변수 없음 — 인증정보는 설정 화면에서 입력하고 기존 `APP_ENCRYPTION_KEY` 로 암호화된다. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_007_$(date +%Y%m%d%H%M).sql +docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_007_ad_api.sql +docker exec postgres-db psql -U postgres -d performance_db -c "\dt perf_ad_*" +``` + +되돌리기(광고 API 인증정보·상태만 사라짐, 가져온 광고비는 perf_ad_spend 에 남음): +`docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_source_status, perf_ad_credentials;"` + ## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) 026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index df3754f..79ecaa1 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -365,14 +365,34 @@ 머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로. - **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`): 열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`. - - 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력. + - **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력. +- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양, + 돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단). + - **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로 + `perf_ad_credentials`(쇼핑몰 표는 `perf_marketplaces` 에 FK 로 묶여 있음), 암호문 AAD 이름 공간 `perf:ad:{채널}:{항목}` + (`credentials.aad_for(…, ns)` — 쇼핑몰 암호문과 바꿔 넣어도 복호화 안 됨). 비밀 원문은 화면으로 다시 보내지 않음. + [현재 키로 다시 암호화]·저장된 항목 수에 광고 인증정보도 포함. 연결 상태·마지막 가져오기는 `perf_ad_source_status`. + - **구글 광고**(`ad_sources/google_ads.py`): 입력 = 개발자 토큰(Explorer 이상, 비밀) · 고객 ID(광고 계정 10자리) · + 로그인 고객 ID(MCC 를 거칠 때만) · 서비스 계정 키 JSON(비밀, 여러 줄) · API 버전(기본 `v26`, 구글이 종료 알리면 설정에서 올림). + 서비스 계정 이메일을 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다(도메인 위임 불필요, 2024-11~). + 토큰 = 서비스 계정 JWT(google-auth 서명) → `oauth2.googleapis.com/token`(httpx), 프로세스 안 캐시(만료 2분 전까지). + 조회 = REST `googleAds:searchStream` GAQL `FROM customer` + `segments.date BETWEEN`(계정 시간대), 요청 1번. + 금액 = `cost_micros ÷ 10⁶` 원 반올림(**부가세 별도** — 쿠팡은 부가세 포함이라 기준이 다름), ROAS = 전환 가치 ÷ 비용 × 100(소수 둘째), + 항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`). + 통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내. + - **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도), + 기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값. + - **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일, + `POST /api/ad-sources/{code}/sync`) + **매출 자동 업데이트 회차**(같은 최근 N일, 매출 다음에, 실패해도 매출과 무관 — `auto_sync.run_once`). + - API: `GET|PUT /api/ad-sources/{code}/credentials`·`POST /api/ad-sources/{code}/test`(관리자), `POST /api/ad-sources/{code}/sync`(모듈 권한). + - 007 미적용: 설정 카드에 안내, 저장은 503(안내 문구), 광고비 탭은 그대로(불러오기 버튼만 안 보임). - **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…` 기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행), [총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG), 월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내). - **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태 - (정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), 마스터 키 상태·재암호화, - 테스트 데이터 생성/삭제(`is_sample`). + (정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 — + 설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`). ## 8. 테스트 @@ -382,3 +402,5 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest 암호화(왕복·AAD·변조·키 교체), 가리기, 수수료 반올림·요율 이력, 기간/주 계산, 표·누적 합계, 인증정보 비노출·재암호화, 동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다. +`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키), +광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증. diff --git a/scripts/sql/performance_db_007_ad_api.sql b/scripts/sql/performance_db_007_ad_api.sql new file mode 100644 index 0000000..ae8189c --- /dev/null +++ b/scripts/sql/performance_db_007_ad_api.sql @@ -0,0 +1,53 @@ +-- ===================================================================== +-- performance_db 마이그레이션 007 — 광고 API 연동(구글 광고) 인증정보·연결 상태 +-- ===================================================================== +-- 멱등(idempotent). 새 표 두 개만 만든다(기존 표·데이터 그대로). 005·006 다음에 적용. +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \ +-- < scripts/sql/performance_db_007_ad_api.sql +-- +-- 왜(2026-10-15 사용자 요청): 광고비 탭에 구글 광고비·ROAS 를 Google Ads API 로 가져온다. +-- 인증정보(개발자 토큰·서비스 계정 키 등)는 실적 설정 화면에서 입력 → 쇼핑몰 인증정보와 같은 마스터 키 +-- (APP_ENCRYPTION_KEY, AES-256-GCM)로 암호화해 저장한다. 쇼핑몰 인증정보 표(perf_credentials)는 +-- 쇼핑몰 목록(perf_marketplaces)에 묶여 있어 광고 채널용 표를 따로 둔다. +-- 가져온 광고비·ROAS 는 기존 perf_ad_spend 에 source='api' 로 들어간다(005 에 이미 허용된 값). +-- 되돌리기: DROP TABLE perf_ad_source_status, perf_ad_credentials; (광고 API 인증정보·상태만 사라짐 — 실행 전 백업) +-- ===================================================================== +BEGIN; + +CREATE TABLE IF NOT EXISTS perf_ad_credentials ( + channel_code TEXT NOT NULL, + credential_key TEXT NOT NULL, + encrypted_value TEXT NOT NULL, + key_version INTEGER NOT NULL, + updated_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (channel_code, credential_key) +); +COMMENT ON TABLE perf_ad_credentials IS '광고 API 인증정보(암호문만) — 채널(google 등) × 항목. 원문은 서버 안에서만 복호화'; +DROP TRIGGER IF EXISTS trg_perf_ad_credentials_updated ON perf_ad_credentials; +CREATE TRIGGER trg_perf_ad_credentials_updated + BEFORE UPDATE ON perf_ad_credentials + FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at(); + +CREATE TABLE IF NOT EXISTS perf_ad_source_status ( + channel_code TEXT PRIMARY KEY, + status TEXT NOT NULL DEFAULT 'unknown', + last_test_at TIMESTAMPTZ, + last_test_ok BOOLEAN, + last_sync_at TIMESTAMPTZ, + last_success_sync_at TIMESTAMPTZ, + last_error TEXT NOT NULL DEFAULT '', + last_error_at TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +COMMENT ON TABLE perf_ad_source_status IS '광고 API 연결 상태 — 마지막 연결 테스트·가져오기·오류(비밀값 가린 문구)'; +DROP TRIGGER IF EXISTS trg_perf_ad_source_status_updated ON perf_ad_source_status; +CREATE TRIGGER trg_perf_ad_source_status_updated + BEFORE UPDATE ON perf_ad_source_status + FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at(); + +GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_credentials, perf_ad_source_status TO performance_app; + +COMMIT; +SELECT 'performance_db 007 ad api ready' AS status; diff --git a/tests/js/render_performance.py b/tests/js/render_performance.py index 6db2c64..4819a7d 100644 --- a/tests/js/render_performance.py +++ b/tests/js/render_performance.py @@ -59,12 +59,13 @@ class FakeStore: def ad_amounts(self, start, end): rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual"), - (date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")} + (date(2026, 10, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload"), + (date(2026, 10, 4), "google"): (123457, "api")} # 구글 광고 API 값(초록 숫자) rows = {k: v for k, v in rows.items() if start <= k[0] <= end} return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()} def ad_roas(self, start, end): - rows = {(date(2026, 10, 3), "naver"): Decimal("250.5")} + rows = {(date(2026, 10, 3), "naver"): Decimal("250.5"), (date(2026, 10, 4), "google"): Decimal("500")} return {k: v for k, v in rows.items() if start <= k[0] <= end} @@ -86,10 +87,15 @@ def main() -> None: f.write(html) actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=["cafe24", "coupang"]) + actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기] html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx) with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f: f.write(html) sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0) + sctx["ad_api_ready"] = True # 광고 API 연동 표(마이그레이션 007) + sctx["ad_sources"] = [{"code": "google", "name": "구글 광고", "configured": True, "status": "ok", "status_label": "정상 연결", + "last_test_at": "2026-10-15T10:00:00+09:00", "last_error": "", "last_error_at": None, + "last_sync_at": "2026-10-15T10:30:02+09:00", "last_success_sync_at": "2026-10-15T10:30:02+09:00"}] html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx) with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f: f.write(html)