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 c in codes %}{% if c in detail_channels %}{% else %} | {{ names[c] }} | {% endif %}{% endfor %} + {% for c in codes %}{% if c in detail_channels %}{% else %} | {{ names[c] }} | {% endif %}{% endfor %}{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %} | {{ won(v) }}{{ roas(r.roas[c]) }} | + title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}">{{ won(v) }}{{ roas(r.roas[c]) }} {% else %}{{ won(v) }}{{ roas(r.roas[c]) }} | {% endif %} @@ -111,9 +119,10 @@ {% if period_kind != 'year' %}
|---|
| 광고 | 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) 계정만 가져옵니다. + 가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다. +
+- API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌 + API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌 서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
이 기간에 올린 보고서 자료가 없습니다.
'; 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("") + '합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.
'; + '합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·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 '