diff --git a/CLAUDE.md b/CLAUDE.md
index 74da5e5..d64fa62 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 계산 안 함 — 따로 입력 예정), 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓) 광고 보고서 업로드(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. 상세는 `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_spend.py b/app/modules/performance/ad_spend.py
index 3a6bbc8..9e79e59 100644
--- a/app/modules/performance/ad_spend.py
+++ b/app/modules/performance/ad_spend.py
@@ -7,6 +7,10 @@
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
날짜 줄 아래 캠페인 줄(1열 빈 칸)과 맨 위 "전체" 합계 줄은 건너뛴다.
+네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
+ 1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
+ 나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
+ 화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
"""
@@ -17,7 +21,7 @@ import csv
import io
from dataclasses import dataclass, field
from datetime import date
-from decimal import ROUND_HALF_UP, Decimal
+from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
from . import calc
@@ -42,9 +46,11 @@ CHANNELS: tuple[tuple[str, str], ...] = (
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
-# 구글·메타는 ROAS 를 계산하지 않는다 — ROAS 값을 따로 넣는다(2026-10-14 사용자 요청).
-NO_ROAS = frozenset({"google", "meta"})
-ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in NO_ROAS}
+# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
+# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
+FILE_ROAS = frozenset({"google", "meta", "naver"})
+NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
+ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
@@ -56,12 +62,32 @@ def roas(sales: int, spend: int) -> int | None:
def roas_basis(code: str) -> str:
- """머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타는 빈 값 = 계산 안 함)."""
+ """머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
-def channel_roas(code: str, sales_of: Callable[[str], int], spend: int) -> int | None:
- """채널 칸의 ROAS — 구글·메타는 늘 None(계산 안 함)."""
+def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
+ s: date, e: date) -> int | None:
+ """보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
+ rev = Decimal(0)
+ spend = 0
+ for (d, c), r in file_roas_map.items():
+ if c != code or not s <= d <= e or r is None:
+ continue
+ amt = int(spends.get((d, c)) or 0)
+ if amt > 0:
+ rev += Decimal(str(r)) * amt
+ spend += amt
+ if spend <= 0:
+ return None
+ return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
+
+
+def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
+ file_of: Callable[[str], int | None] | None = None) -> int | None:
+ """채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
+ if code in FILE_ROAS:
+ return file_of(code) if file_of else None
mcode = ROAS_SALES_CODE.get(code)
return None if mcode is None else roas(sales_of(mcode), spend)
@@ -70,8 +96,14 @@ ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
+NAVER_DATE_COL = 2 # 3열 기간(날짜)
+NAVER_AMOUNT_COL = 3 # 4열 총비용
+NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
+NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
+
+
class AdMigrationNeeded(Exception):
- """광고비 표(마이그레이션 005: perf_ad_spend)가 아직 없음."""
+ """광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
@dataclass
@@ -79,6 +111,10 @@ class ParseResult:
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
errors: list[str] = field(default_factory=list)
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
+ # 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
+ roas: dict[date, Decimal] = field(default_factory=dict)
+ metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
+ columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
# ════════════════════════════════════════════════════════════
@@ -162,10 +198,133 @@ def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") ->
return res
+def _number(value: Any) -> Decimal | None:
+ """숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
+ if value is None or (isinstance(value, str) and not value.strip()):
+ return None
+ if isinstance(value, bool):
+ raise ValueError
+ text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
+ try:
+ num = Decimal(text)
+ except InvalidOperation:
+ raise ValueError from None
+ if not num.is_finite():
+ raise ValueError
+ return num
+
+
+def _json_num(num: Decimal | None) -> Any:
+ if num is None:
+ return None
+ return int(num) if num == num.to_integral_value() else float(round(num, 2))
+
+
+def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
+ """네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(12열) + 나머지 항목. 잘못된 줄이 있으면 errors."""
+ rows = read_rows(content, filename)
+ res = ParseResult()
+ header: tuple[Any, ...] = ()
+ seen: dict[date, int] = {}
+ for r, row in enumerate(rows, start=1):
+ raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_DATE_COL else None
+ text = str(raw_day or "").strip()
+ if not text or text.replace(" ", "") in SKIP_LABELS:
+ res.skipped += 1
+ continue
+ try:
+ day = parse_date(raw_day)
+ except ValueError:
+ if not header: # 머리글(1행 "기간")
+ header = tuple(str(h or "").strip() for h in row)
+ res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
+ res.skipped += 1
+ continue
+ res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
+ continue
+ if day is None:
+ res.skipped += 1
+ continue
+ try:
+ amt = parse_amount(row[NAVER_AMOUNT_COL] if len(row) > NAVER_AMOUNT_COL else None)
+ except ValueError:
+ res.errors.append(f"{r}행 4열: 총비용이 숫자가 아닙니다.")
+ continue
+ try:
+ ro = _number(row[NAVER_ROAS_COL] if len(row) > NAVER_ROAS_COL else None)
+ except ValueError:
+ res.errors.append(f"{r}행 12열: 광고수익률(ROAS)이 숫자가 아닙니다.")
+ continue
+ if amt is None:
+ res.errors.append(f"{r}행 4열: {day.isoformat()} 총비용이 비어 있습니다.")
+ elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
+ res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
+ elif day > today:
+ res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
+ elif day in seen:
+ res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
+ else:
+ seen[day] = r
+ res.entries.append((day, amt))
+ if ro is not None:
+ res.roas[day] = ro
+ m: dict[str, Any] = {}
+ for i, v in enumerate(row):
+ name = header[i] if i < len(header) else f"{i + 1}열"
+ if i in NAVER_SKIP_COLS or not name:
+ continue
+ try:
+ m[name] = _json_num(_number(v))
+ except ValueError:
+ m[name] = str(v)[:100]
+ res.metrics[day] = m
+ if len(res.entries) > MAX_DATA_ROWS:
+ raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
+ if len(res.errors) > MAX_ERRORS:
+ break
+ if not res.entries and not res.errors:
+ raise UploadError("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
+ return res
+
+
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
-PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
+PARSERS: dict[str, Callable[..., ParseResult]] = {
+ "naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
-UPLOAD_HELP = {"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
+UPLOAD_HELP = {
+ "naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
+ "나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
+ "coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
+# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널)
+DETAIL_CHANNELS = frozenset({"naver"})
+
+
+def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
+ """일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
+ 열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
+ cols: list[str] = []
+ for r in rows:
+ for k in (r.get("metrics") or {}):
+ if k not in cols:
+ cols.append(k)
+ sums: dict[str, Decimal] = {}
+ for r in rows:
+ for k, v in (r.get("metrics") or {}).items():
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
+ total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
+ for k in cols:
+ if "클릭률" in k and sums.get("노출수"):
+ total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
+ elif ("수익률" in k or "ROAS" in k.upper()):
+ spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
+ rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
+ if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
+ total[k] = float(round(rev / spend, 2)) if spend else None
+ out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
+ "roas": float(r["roas"]) if r.get("roas") is not None else None,
+ "values": r.get("metrics") or {}} for r in rows]
+ return {"columns": cols, "rows": out_rows, "total": total}
# ════════════════════════════════════════════════════════════
@@ -194,6 +353,11 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
except AdMigrationNeeded:
amounts, sources, migration_needed = {}, {}, True
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
+ roas_reader = getattr(store, "ad_roas", None)
+ try:
+ roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
+ except AdMigrationNeeded:
+ roas_map = {}
cur = calc.sum_range(cells, codes, period.start, period.end)
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
@@ -257,11 +421,13 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
for row in table:
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
- row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"]) for c in codes}
+ row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
+ lambda f: file_roas(f, roas_map, amounts, s, e)) for c in codes}
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
m_s, m_e = month_period.start, month_period.end
for r in month["rows"]:
- r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"])
+ r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
+ lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
year = calc.year_months(year_period.start.year, codes, cells, today=today)
for i, r in enumerate(year["rows"], start=1):
@@ -280,6 +446,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"month": month,
"year": year,
"roas_basis": {c: roas_basis(c) for c in codes},
+ "detail_channels": sorted(DETAIL_CHANNELS),
"chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
# 업로드로 들어온 칸(표시용) — "날짜|채널"
diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py
index 80b8f2b..f661a33 100644
--- a/app/modules/performance/db.py
+++ b/app/modules/performance/db.py
@@ -396,31 +396,79 @@ class PerformanceDBStore:
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
- user: str = "") -> int:
- """여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소."""
+ user: str = "", roas: dict[date, Any] | None = None,
+ metrics: dict[date, dict[str, Any]] | None = None) -> int:
+ """여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
+ roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
if not entries:
return 0
+ report = roas is not None or metrics is not None
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
gone = [(code, d) for d, a in entries if a is None]
- keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
if gone:
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
- if keep:
- cur.executemany(
- "INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
- "VALUES (%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",
- keep,
- )
+ if report:
+ keep6 = [(code, d, int(a), source, user, (roas or {}).get(d),
+ Jsonb((metrics or {}).get(d)) if (metrics or {}).get(d) is not None else None)
+ for d, a in entries if a is not None]
+ if keep6:
+ 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",
+ keep6,
+ )
+ else:
+ keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
+ if keep:
+ cur.executemany(
+ "INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
+ "VALUES (%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",
+ keep,
+ )
except pg_errors.UndefinedTable:
- raise AdMigrationNeeded() from None
+ raise AdMigrationNeeded("005") from None
+ except pg_errors.UndefinedColumn:
+ raise AdMigrationNeeded("006") from None
return len(entries)
+ def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
+ """(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이)."""
+ try:
+ with self._pool.connection() as conn:
+ rows = conn.execute(
+ "SELECT spend_date, channel_code, roas FROM perf_ad_spend "
+ "WHERE spend_date BETWEEN %s AND %s AND roas IS NOT NULL", (start, end),
+ ).fetchall()
+ except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
+ return {}
+ return {(r["spend_date"], r["channel_code"]): r["roas"] for r in rows}
+
+ def ad_details(self, code: str, start: date, end: date) -> list[dict[str, Any]]:
+ """한 채널의 일자별 광고비·ROAS·보고서 항목(날짜 순). 006 미적용이면 AdMigrationNeeded."""
+ from .ad_spend import AdMigrationNeeded # noqa: WPS433
+
+ try:
+ with self._pool.connection() as conn:
+ rows = conn.execute(
+ "SELECT spend_date, amount, roas, metrics, source FROM perf_ad_spend "
+ "WHERE channel_code = %s AND spend_date BETWEEN %s AND %s ORDER BY spend_date",
+ (code, start, end),
+ ).fetchall()
+ except pg_errors.UndefinedTable:
+ raise AdMigrationNeeded("005") from None
+ except pg_errors.UndefinedColumn:
+ raise AdMigrationNeeded("006") from None
+ return [{"date": r["spend_date"].isoformat(), "amount": int(r["amount"]), "roas": r["roas"],
+ "metrics": r["metrics"] or {}, "source": r["source"]} for r in rows]
+
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
id_prefix 가 있으면 이 어댑터가 다른 쇼핑몰 열로 보낸 사건까지 합친다(카페24 화면 합계와 같은 범위)."""
diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py
index 65c1c1a..f1f928d 100644
--- a/app/modules/performance/router.py
+++ b/app/modules/performance/router.py
@@ -15,7 +15,9 @@ JSON API — 모듈 권한
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
- POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡(로켓) 광고 보고서 — 1열 날짜, 19열 청구금액)
+ POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
+ 네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
+ GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버 머리글 클릭)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
@@ -55,6 +57,12 @@ MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
"먼저 적용해야 합니다.")
+AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
+ "(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
+
+
+def _ad_migration_help(exc: Exception) -> str:
+ return AD_MIGRATION_HELP_006 if "006" in str(exc) else AD_MIGRATION_HELP
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
@@ -425,12 +433,32 @@ def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, An
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
try:
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
- except AdMigrationNeeded:
- raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
+ except AdMigrationNeeded as exc:
+ raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
"amount": amount or 0})
+@router.get("/api/ad-spend/{channel}/details")
+def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
+ """일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
+ from . import ad_spend # noqa: WPS433
+
+ store, _ = common.require_store(request)
+ _ad_channel(channel)
+ if channel not in ad_spend.DETAIL_CHANNELS:
+ raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
+ start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
+ if start is None or end is None or end < start or (end - start).days > 365:
+ raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
+ try:
+ rows = store.ad_details(channel, start, end)
+ except ad_spend.AdMigrationNeeded as exc:
+ raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
+ return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
+ "to": end.isoformat(), **ad_spend.detail_table(rows)})
+
+
@router.post("/api/ad-spend/upload")
def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse:
"""광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다."""
@@ -451,10 +479,11 @@ def api_ad_spend_upload(request: Request, channel: str = Query(...), file: Uploa
return JSONResponse(status_code=400, content={
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
"errors": res.errors})
+ report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
try:
- saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""))
- except ad_spend.AdMigrationNeeded:
- raise HTTPException(status_code=503, detail=AD_MIGRATION_HELP) from None
+ saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
+ except ad_spend.AdMigrationNeeded as exc:
+ raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
days = sorted(d for d, _ in res.entries)
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
"total": sum(a for _, a in res.entries), "skipped": res.skipped,
diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html
index 4849e57..28dedf6 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 -%}
@@ -82,7 +82,7 @@
@@ -111,7 +111,8 @@
{% if period_kind != 'year' %}
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}
- {% for c in codes %}{{ names[c] }} {% endfor %}
+ {% for c in codes %}{% if c in detail_channels %}{% else %} {{ names[c] }} {% endif %}{% endfor %}
{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}
날짜 칸을 눌러 그날 광고비를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. - 칸은 광고비(ROAS%) — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않습니다. + 칸은 광고비(ROAS%) — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 구글·메타는 ROAS 를 계산하지 않고, + 네이버는 광고 보고서의 ROAS(구매완료 광고수익률)를 씁니다 — 네이버 머리글을 누르면 일자별 보고서 항목. 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(윙)·쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
{% endif %} @@ -190,7 +191,7 @@- 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함). + 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(구글·메타는 계산 안 함, 네이버는 보고서 값). 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출. 구글·메타는 지금은 직접 입력합니다.
@@ -205,9 +206,12 @@ "today": today, "manual_api": "/performance/api/ad-spend/", "manual_word": "광고비", + "period_start": period.start.isoformat(), + "period_end": period.end.isoformat(), + "period_label": period.label, "empty_text": "기간 내 광고비가 없습니다.", "upload_channels": upload_channels } | 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 fb5a454..3c5cfd1 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 fbde476..bf92ffe 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 -%} @@ -204,4 +204,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 6187cac..8502444 100644 --- a/app/modules/performance/tests/test_ad_spend.py +++ b/app/modules/performance/tests/test_ad_spend.py @@ -4,6 +4,7 @@ from __future__ import annotations import io from datetime import date +from decimal import Decimal import openpyxl import pytest @@ -97,7 +98,8 @@ def test_ad_dashboard_month(): assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000 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"]] == ["coupang_wing", "coupang_rocket"] + assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"] + assert ctx["detail_channels"] == ["naver"] 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 @@ -142,7 +144,8 @@ def test_ad_spend_endpoints(monkeypatch): def __init__(self): self.saved, self.missing = [], False - def set_ad_spend_bulk(self, code, entries, *, source="manual", user=""): + def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None): + self.report = (roas, metrics) if self.missing: raise ads.AdMigrationNeeded() self.saved.extend((code, d, a, source) for d, a in entries) @@ -182,3 +185,121 @@ def test_ad_spend_endpoints(monkeypatch): store.missing = True r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1}) assert r.status_code == 503 and "005" in r.json()["detail"] + +# 사용자 제공 네이버 광고 보고서(2026-10-14) — 앞 9줄 + 머리글 +NAVER_CSV = """광고 계정 이름,광고 계정 ID,기간,총비용,노출수,클릭수,클릭률(%),총 전환수,구매완료 수,장바구니 담기 수,총 전환매출액,구매완료 광고수익률(%) +0_미라네주방,38461,2026.09.30.,0,0,0,0.00,46,6,40,8218000,0.00 +0_미라네주방,38461,2026.09.24.,0,0,0,0.00,36,6,30,6331500,0.00 +0_미라네주방,38461,2026.09.23.,300672,30043,461,1.53,71,13,58,7830100,67.58 +0_미라네주방,38461,2026.09.22.,299817,31061,441,1.42,125,20,105,15040200,198.79 +0_미라네주방,38461,2026.09.21.,299199,25641,416,1.62,159,44,115,19878020,501.11 +""" + + +def test_naver_report_reads_date_cost_roas_and_metrics(): + for content, name in ((NAVER_CSV.encode("utf-8-sig"), "n.csv"), (NAVER_CSV.encode("cp949"), "n.csv"), (_xlsx(NAVER_CSV), "n.xlsx")): + res = ads.parse_naver(content, today=TODAY, filename=name) + assert not res.errors, res.errors + assert res.entries[:3] == [(date(2026, 9, 30), 0), (date(2026, 9, 24), 0), (date(2026, 9, 23), 300672)] + assert str(res.roas[date(2026, 9, 23)]) == "67.58" and res.roas[date(2026, 9, 30)] == 0 + m = res.metrics[date(2026, 9, 21)] + assert m["노출수"] == 25641 and m["클릭률(%)"] == 1.62 and m["총 전환매출액"] == 19878020 + assert m["구매완료 광고수익률(%)"] == 501.11 and "광고 계정 이름" not in m and "기간" not in m + assert res.columns[0] == "총비용" and res.columns[-1] == "구매완료 광고수익률(%)" + bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n" + bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n" + errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors) + assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs + + +def test_naver_roas_from_report_weighted(): + """네이버 칸 ROAS = 보고서 값(계산 안 함), 여러 날 = Σ(ROAS×광고비)÷Σ광고비, 광고비 0 인 날은 빼고.""" + class S(_Store): + def ad_amounts(self, start, end): + rows = {(date(2026, 9, 22), "naver"): 299817, (date(2026, 9, 23), "naver"): 300672, + (date(2026, 9, 24), "naver"): 0} + rows = {k: v for k, v in rows.items() if start <= k[0] <= end} + return rows, {k: "upload" for k in rows} + + def ad_roas(self, start, end): + rows = {(date(2026, 9, 22), "naver"): Decimal("198.79"), (date(2026, 9, 23), "naver"): Decimal("67.58"), + (date(2026, 9, 24), "naver"): Decimal("0")} + return {k: v for k, v in rows.items() if start <= k[0] <= end} + + def daily_amounts(self, start, end, codes): + return {(date(2026, 9, 22), "naver"): 9_999_999} if "naver" in codes else {} + + ctx = ads.build_ad_dashboard(S(), kind="week", anchor=date(2026, 9, 23), today=TODAY, sales_codes=["naver"]) + by = {r.get("date"): r for r in ctx["table"]} + assert by["2026-09-22"]["roas"]["naver"] == 199 and by["2026-09-23"]["roas"]["naver"] == 68 + assert by["2026-09-24"]["roas"]["naver"] is None # 광고비 0 + week = next(r for r in ctx["table"] if r["kind"] == "week") + want = round((Decimal("198.79") * 299817 + Decimal("67.58") * 300672) / (299817 + 300672)) + assert week["roas"]["naver"] == want == 133 # 매출 실적(9,999,999)으로 계산하지 않음 + assert ctx["roas_basis"]["naver"] == "" + assert {r["code"]: r for r in ctx["month"]["rows"]}["naver"]["roas"] == 133 + + +def test_naver_detail_table_totals(): + rows = [{"date": "2026-09-22", "amount": 299817, "roas": Decimal("198.79"), + "metrics": {"총비용": 299817, "노출수": 31061, "클릭수": 441, "클릭률(%)": 1.42, "구매완료 광고수익률(%)": 198.79}}, + {"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), + "metrics": {"총비용": 300672, "노출수": 30043, "클릭수": 461, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 67.58}}, + {"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0, + "클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}] + t = ads.detail_table(rows) + assert t["columns"] == ["총비용", "노출수", "클릭수", "클릭률(%)", "구매완료 광고수익률(%)"] + assert t["total"]["총비용"] == 600489 and t["total"]["노출수"] == 61104 and t["total"]["클릭수"] == 902 + assert t["total"]["클릭률(%)"] == round(902 * 100 / 61104, 2) # 가중: 클릭수 ÷ 노출수 + assert t["total"]["구매완료 광고수익률(%)"] == 133.09 # 광고비 가중 평균 (198.79×299,817 + 67.58×300,672) ÷ 600,489 + assert t["rows"][0]["values"]["노출수"] == 31061 and t["rows"][1]["roas"] == 67.58 + + +def test_naver_upload_and_details_endpoints(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") + + class Store: + def __init__(self): + self.saved, self.kw, self.missing = [], {}, "" + + def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None): + if self.missing: + raise ads.AdMigrationNeeded(self.missing) + self.saved.extend((code, d, a, source) for d, a in entries) + self.kw = {"roas": roas, "metrics": metrics} + return len(entries) + + def ad_details(self, code, start, end): + if self.missing: + raise ads.AdMigrationNeeded(self.missing) + return [{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), "metrics": {"노출수": 30043}}] + + store = Store() + monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"})) + monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY) + app = FastAPI() + app.include_router(perf_router.router) + client = TestClient(app) + r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8-sig"))}) + assert r.status_code == 200, r.text + assert r.json()["saved"] == 5 and r.json()["total"] == 300672 + 299817 + 299199 + assert store.saved[2] == ("naver", date(2026, 9, 23), 300672, "upload") + assert str(store.kw["roas"][date(2026, 9, 23)]) == "67.58" and store.kw["metrics"][date(2026, 9, 21)]["클릭수"] == 416 + store.saved.clear() + r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))}) + assert r.status_code == 200 and store.kw == {"roas": None, "metrics": None} # 쿠팡은 금액만 + d = client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json() + assert d["name"] == "네이버" and d["columns"] == ["노출수"] and d["rows"][0]["roas"] == 67.58 + assert client.get("/performance/api/ad-spend/coupang_rocket/details?from=2026-09-01&to=2026-09-30").status_code == 400 + assert client.get("/performance/api/ad-spend/naver/details?from=2026-09-30&to=2026-09-01").status_code == 400 + store.missing = "006" + r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8"))}) + assert r.status_code == 503 and "006" in r.json()["detail"] + assert "006" in client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()["detail"] diff --git a/app/static/performance.css b/app/static/performance.css index d4b89b9..d773ea9 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -62,6 +62,12 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } .perf-roas { margin-left: 2px; font-size: 11px; font-weight: 500; color: var(--color-midtone-gray); } .perf-row-total .perf-roas { color: #bbb; } .perf .perf-main td.is-editing .perf-roas { visibility: hidden; } +/* 네이버 머리글 = 일자별 보고서 항목 보기 버튼 */ +.perf-detail-btn { display: inline-flex; align-items: center; gap: 3px; border: 0; background: transparent; font: inherit; + font-weight: 600; color: var(--perf-ad); cursor: pointer; padding: 2px 4px; border-radius: 6px; } +.perf-detail-btn .material-symbols-outlined { font-size: 16px; } +.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; } +.perf-detail-table th, .perf-detail-table td { white-space: nowrap; } .perf-ad-upload-btn { margin-left: auto; } .perf-kpi-pct { font-size: 26px; font-weight: 700; } diff --git a/app/static/performance.js b/app/static/performance.js index 3a6cc7b..32426dc 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -379,6 +379,42 @@ }); }); + // 광고 보고서 일자별 상세(네이버 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계. + root.addEventListener("click", async function (e) { + const btn = e.target.closest("[data-detail-channel]"); + if (!btn) return; + const code = btn.dataset.detailChannel; + const name = (data.names || {})[code] || code; + const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true }); + m.body.innerHTML = '불러오는 중…
'; + 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; } + const cols = res.columns || []; + const cell = function (v) { + if (v == null || v === "") return '–'; + return typeof v === "number" ? (Number.isInteger(v) ? fmt(v) : v.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })) : esc(v); + }; + const WD = ["일", "월", "화", "수", "목", "금", "토"]; + const day = function (iso) { + const d = new Date(iso + "T00:00:00"); + return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")"; + }; + m.body.innerHTML = '| 날짜 | ' + + cols.map(function (c) { return "" + esc(c) + " | "; }).join("") + "
|---|---|
| ' + esc(day(r.date)) + " | " + + cols.map(function (c) { return '' + cell((r.values || {})[c]) + " | "; }).join("") + "
| 합계 | ' + + cols.map(function (c) { return '' + cell((res.total || {})[c]) + " | "; }).join("") + + "
합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 날짜별 광고수익률을 총비용으로 가중 평균.
'; + } catch (err) { + m.body.innerHTML = '' + esc(err.message) + "
"; + } + }); + // 직접선택 / 쇼핑몰 필터 const customBtn = document.getElementById("perf-custom-btn"); const customForm = document.getElementById("perf-custom"); diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index c0427e5..0927286 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -197,6 +197,20 @@ docker exec postgres-db psql -U postgres -d performance_db -c "\d perf_ad_spend" 되돌리기(광고비 데이터만 사라짐): `docker exec postgres-db psql -U postgres -d performance_db -c "DROP TABLE perf_ad_spend;"` +## 실적 광고비 ROAS·보고서 항목 마이그레이션 (performance_db 006) + +006은 `perf_ad_spend` 에 `roas`·`metrics` 열 두 개만 더한다(기존 값 그대로, 다시 실행 가능). 005 다음에 적용한다. +미적용이면 네이버 보고서 업로드·네이버 일자별 상세만 503 안내, 나머지 광고비 화면은 그대로. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_006_$(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_006_ad_roas_metrics.sql +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;"` + ## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) 026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 2ecb6f7..eab520b 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -345,7 +345,8 @@ 연간은 월)·일별 추이·채널 비중·월/연 누적. 채널(2026-10-14) = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 (`ad_spend.CHANNELS`, 앱이 정함 — 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같고 쿠팡(윙)만 `coupang_wing`). 모든 칸 직접 입력 가능, 칸 표시 = **광고비(ROAS%)** — ROAS = 그 칸 기간의 매출 실적 총매출 ÷ 광고비 × 100(정수 반올림, - `ad_spend.roas`). 매출 쇼핑몰 = `ROAS_SALES_CODE`(같은 쇼핑몰, 쿠팡(윙) = `coupang`). **구글·메타는 ROAS 계산 안 함**(`NO_ROAS` — ROAS 값을 따로 넣을 예정, 2026-10-14), + `ad_spend.roas`). 매출 쇼핑몰 = `ROAS_SALES_CODE`(같은 쇼핑몰, 쿠팡(윙) = `coupang`). **구글·메타·네이버는 ROAS 계산 안 함**(`FILE_ROAS` — 광고 보고서의 ROAS 값, `perf_ad_spend.roas`, 마이그레이션 006; + 여러 날 = Σ(그날 ROAS × 광고비) ÷ Σ광고비, 광고비 0 인 날 제외 — `file_roas`), 합계 열·월/연 누적 = 매출 실적에 들어가는 쇼핑몰 전체 매출. 광고비가 없는 칸은 ROAS 없음. 광고비를 고치면 옛 ROAS 는 지우고 새로고침 때 다시 계산. KPI: 기간 광고비(전기간 대비), 매출 대비 광고비(같은 기간 광고비 ÷ 매출 실적 총매출), 월·연 누적. 저장 `perf_ad_spend`(마이그레이션 005 — 채널 × 날짜 하나에 금액, `source` manual/upload/api), 미적용이면 화면에 안내·API 503. @@ -353,6 +354,11 @@ - [파일 업로드](`POST /api/ad-spend/upload?channel=`) — 양식이 정해진 채널만(`ad_spend.PARSERS`). 파일에 있는 날만 덮어쓰고(주황 숫자), 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다. **쿠팡(윙)·쿠팡(로켓)**(같은 양식, 윙은 2026-10-14) = 쿠팡 광고 보고서 CSV(UTF-8/CP949)·엑셀: 1열 날짜(`2026년 10월 01일`), 19열 청구금액(+부가가치세). "전체" 합계 줄·머리글·캠페인 줄(1열 빈 칸)은 건너뜀. + - **네이버**(2026-10-14) = 네이버 광고 보고서 CSV·엑셀(하루 한 줄): 3열 기간(`2026.09.30.`), 4열 총비용 = 광고비, + 12열 구매완료 광고수익률(%) = 그날 ROAS(`roas`), 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 + 머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로. + - **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`): + 열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`. - 구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력. - **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…` 기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행), diff --git a/scripts/sql/performance_db_006_ad_roas_metrics.sql b/scripts/sql/performance_db_006_ad_roas_metrics.sql new file mode 100644 index 0000000..3ba3809 --- /dev/null +++ b/scripts/sql/performance_db_006_ad_roas_metrics.sql @@ -0,0 +1,21 @@ +-- ===================================================================== +-- performance_db 마이그레이션 006 — 광고비 ROAS·보고서 상세 항목 +-- ===================================================================== +-- 멱등(idempotent). perf_ad_spend 에 열 두 개만 추가(기존 행·값 그대로). 005 다음에 적용. +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \ +-- < scripts/sql/performance_db_006_ad_roas_metrics.sql +-- +-- 왜(2026-10-14 사용자 요청): 네이버 광고 보고서 업로드 — 12열 구매완료 광고수익률(%)을 그날 ROAS 로(roas), +-- 나머지 항목(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로(metrics) +-- 보관해 네이버 머리글을 누르면 일자별 표로 본다. 구글·메타도 나중에 같은 칸에 ROAS 를 넣는다. +-- 되돌리기: ALTER TABLE perf_ad_spend DROP COLUMN metrics, DROP COLUMN roas; (보고서 ROAS·상세만 사라짐 — 실행 전 백업) +-- ===================================================================== +BEGIN; + +ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS roas NUMERIC(14, 2); +ALTER TABLE perf_ad_spend ADD COLUMN IF NOT EXISTS metrics JSONB; +COMMENT ON COLUMN perf_ad_spend.roas IS '광고 보고서의 ROAS(%) — 구글·메타·네이버(계산하지 않고 보고서 값). NULL = 없음'; +COMMENT ON COLUMN perf_ad_spend.metrics IS '광고 보고서 그날 나머지 항목 {머리글: 값} — 네이버 노출수·클릭수·전환수 등'; + +COMMIT; +SELECT 'performance_db 006 ad roas/metrics ready' AS status; diff --git a/tests/js/perf_manual.test.js b/tests/js/perf_manual.test.js index 784d482..78af6b2 100644 --- a/tests/js/perf_manual.test.js +++ b/tests/js/perf_manual.test.js @@ -23,6 +23,11 @@ async function env(file) { const isForm = o && o.body && typeof o.body !== "string"; const body = o && o.body && !isForm ? JSON.parse(o.body) : null; e.calls.push({ method: method, url: url, body: body, form: isForm ? o.body : null }); + if (/^\/performance\/api\/ad-spend\/naver\/details/.test(url)) { + return { ok: true, status: 200, json: async function () { + return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 }, + rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } }; + } if (/^\/performance\/api\/ad-spend\/upload/.test(url)) { return { ok: true, status: 200, json: async function () { return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12" }; } }; @@ -143,7 +148,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } { const e = await env("perf_ads.html"); check("[광고비] 광고비 탭이 고른 탭", e.d.querySelector(".perf-tab-ads").classList.contains("is-active")); - const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").trim(); }); + const heads = Array.from(e.d.querySelectorAll(".perf-main thead th")).map(function (th) { return th.textContent.replace("✎", "").replace("table_view", "").trim(); }); check("[광고비] 열 = 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰", heads.join(",") === "날짜,구글,메타,네이버,쿠팡(윙),쿠팡(로켓),오늘의집,G마켓,카카오,GS샵,11번가,롯데ON,토스,애터미아자몰,일 합계", heads); const wing = cell(e, "coupang_wing", "2026-10-05"); @@ -154,7 +159,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } !up.classList.contains("is-manual") && man.classList.contains("is-manual") && gross(up) === "220,000"); check("[광고비] 앞으로의 날은 입력 칸 아님", !cell(e, "google", "2026-10-08") && !!cell(e, "google", "2026-10-07")); const kpi = Array.from(e.d.querySelectorAll(".perf-kpi-value")).map(function (n) { return n.textContent.trim(); }); - check("[광고비] KPI — 이번달 광고비 299,000 · 매출 대비 비율", kpi[0] === "₩299,000" && /%$/.test(kpi[1]), kpi); + check("[광고비] KPI — 이번달 광고비 599,000(네이버 300,000 포함) · 매출 대비 비율", kpi[0] === "₩599,000" && /%$/.test(kpi[1]), kpi); wing.click(); const wi = wing.querySelector(".perf-manual-input"); wi.value = "30000"; @@ -182,7 +187,8 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } e.d.getElementById("perf-ad-upload").click(); const modal = e.d.querySelector(".perf-modal"); const opts = Array.from(modal.querySelectorAll(".perf-ad-channel option")).map(function (o) { return o.value; }); - check("[업로드] 채널 선택 = 양식이 정해진 쿠팡(윙)·쿠팡(로켓)", opts.join(",") === "coupang_wing,coupang_rocket", opts); + check("[업로드] 채널 선택 = 양식이 정해진 네이버·쿠팡(윙)·쿠팡(로켓)", opts.join(",") === "naver,coupang_wing,coupang_rocket", opts); + check("[업로드] 네이버 안내 = 3열 기간·4열 총비용·12열 ROAS", /3열 기간.*4열 총비용.*12열/.test(modal.querySelector(".perf-ad-help").textContent)); modal.querySelector(".perf-ad-channel").value = "coupang_rocket"; modal.querySelector(".perf-ad-channel").dispatchEvent(new e.w.Event("change")); check("[업로드] 양식 안내(19열 청구금액)", /19열/.test(modal.querySelector(".perf-ad-help").textContent)); @@ -195,6 +201,23 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } check("[업로드] POST /api/ad-spend/upload?channel=coupang_rocket (파일)", post && post.url === "/performance/api/ad-spend/upload?channel=coupang_rocket" && !!post.form, e.calls); check("[업로드] 결과 안내(12일 반영)", /12일 반영/.test(modal.querySelector(".perf-upload-result").textContent)); } + // ── 네이버 — 보고서 ROAS 표시 · 머리글 → 일자별 보고서 항목 ── + { + const e = await env("perf_ads.html"); + const nv = cell(e, "naver", "2026-10-03"); + check("[네이버] 칸 = 광고비(보고서 ROAS 반올림)", nv.textContent.trim() === "300,000(251%)", nv.textContent); + const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]'); + check("[네이버] 머리글 = 상세 보기 버튼(다른 채널은 아님)", !!hb && e.d.querySelectorAll(".perf-main thead [data-detail-channel]").length === 1); + hb.click(); await settle(); + const call = e.calls.find(function (c) { return /\/details/.test(c.url); }); + check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls); + const modal = e.d.querySelector(".perf-modal"); + const ths = Array.from(modal.querySelectorAll("thead th")).map(function (t) { return t.textContent; }); + const row = Array.from(modal.querySelectorAll("tbody tr")[0].children).map(function (t) { return t.textContent; }); + check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" && + row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]); + check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent)); + } // ── 설정: 수동 입력 토글 ── { const e = await env("perf_settings.html"); diff --git a/tests/js/render_performance.py b/tests/js/render_performance.py index d0cbaf9..6db2c64 100644 --- a/tests/js/render_performance.py +++ b/tests/js/render_performance.py @@ -59,10 +59,14 @@ 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, 5), "coupang_wing"): (29000, "manual"), (date(2026, 10, 3), "naver"): (300000, "upload")} 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")} + return {k: v for k, v in rows.items() if start <= k[0] <= end} + def env() -> jinja2.Environment: e = jinja2.Environment(loader=jinja2.ChoiceLoader([