From ef38140673225ccc4a16e9944095e78322088ba1 Mon Sep 17 00:00:00 2001 From: king Date: Tue, 13 Oct 2026 18:20:44 +0900 Subject: [PATCH] =?UTF-8?q?feat(performance):=20=EA=B4=91=EA=B3=A0?= =?UTF-8?q?=EB=B9=84=20=ED=83=AD(=EA=B5=AC=EA=B8=80=C2=B7=EB=A9=94?= =?UTF-8?q?=ED=83=80=C2=B7=EC=BF=A0=ED=8C=A1=20=EC=9C=99/=EB=A1=9C?= =?UTF-8?q?=EC=BC=93)=20+=20=ED=83=AD=20=EA=B0=9C=ED=8E=B8=C2=B7=EC=84=A4?= =?UTF-8?q?=EC=A0=95=20=ED=86=B1=EB=8B=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 탭: [매출 실적](검정) · [광고비](주황) 큰 탭 + 맨 오른쪽 설정 톱니(Material Symbols settings) - /performance/ads: 연·월·일 표(채널 × 날짜)·추이·비중·월/연 누적, 매출 대비 광고비 KPI - 날짜 칸 직접 입력(PUT /api/ad-spend/{channel}/{day}), 쿠팡(로켓) 광고 보고서 업로드 (CSV/엑셀, 1열 날짜·19열 청구금액(+부가가치세), 잘못된 줄 있으면 전부 거절) - performance_db 마이그레이션 005 perf_ad_spend - 설정 화면 쇼핑몰 순서 jsdom 기대값을 003 열 순서로 갱신(기존 실패) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- app/modules/performance/ad_spend.py | 235 ++++++++++++++++++ app/modules/performance/db.py | 48 ++++ app/modules/performance/router.py | 103 ++++++++ .../templates/performance/_tabs.html | 17 +- .../templates/performance/ads.html | 204 +++++++++++++++ .../templates/performance/index.html | 4 +- .../templates/performance/settings.html | 4 +- .../performance/tests/test_ad_spend.py | 164 ++++++++++++ app/static/performance.css | 43 +++- app/static/performance.js | 84 ++++++- docs/DEPLOYMENT.md | 13 + docs/PERFORMANCE_MODULE.md | 11 + scripts/sql/performance_db_005_ad_spend.sql | 36 +++ tests/js/perf_manual.test.js | 69 ++++- tests/js/render_performance.py | 15 +- 16 files changed, 1026 insertions(+), 26 deletions(-) create mode 100644 app/modules/performance/ad_spend.py create mode 100644 app/modules/performance/templates/performance/ads.html create mode 100644 app/modules/performance/tests/test_ad_spend.py create mode 100644 scripts/sql/performance_db_005_ad_spend.sql diff --git a/CLAUDE.md b/CLAUDE.md index c89c281..352a46b 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). 패널(`/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` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐). 상세는 `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`) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 일 광고비를 연·월·일로, 날짜 칸 직접 입력 + 쿠팡(로켓) 광고 보고서 업로드(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 new file mode 100644 index 0000000..56a264e --- /dev/null +++ b/app/modules/performance/ad_spend.py @@ -0,0 +1,235 @@ +"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립. + +저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수). + - 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀). + - 구글·메타는 지금은 직접 입력만(API 연동은 다음 단계). + +쿠팡(로켓) 업로드 양식(2026-10-13 사용자 제공 — 쿠팡 광고 보고서 CSV/엑셀): + 1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비. + 날짜 줄 아래 캠페인 줄(1열 빈 칸)과 맨 위 "전체" 합계 줄은 건너뛴다. + +HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다. +""" + +from __future__ import annotations + +import csv +import io +from dataclasses import dataclass, field +from datetime import date +from typing import Any, Callable, Mapping, Sequence + +from . import calc +from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date + +# 채널 — 표 열 순서. upload = 업로드 양식이 정해진 채널(파일 읽기 함수가 있는 채널). +CHANNELS: tuple[tuple[str, str], ...] = ( + ("google", "구글"), + ("meta", "메타"), + ("coupang_wing", "쿠팡(윙)"), + ("coupang_rocket", "쿠팡(로켓)"), +) +CHANNEL_NAMES = dict(CHANNELS) +CHANNEL_CODES = tuple(c for c, _ in CHANNELS) + +ROCKET_DATE_COL = 0 # 1열 날짜 +ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세) +SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"}) + + +class AdMigrationNeeded(Exception): + """광고비 표(마이그레이션 005: perf_ad_spend)가 아직 없음.""" + + +@dataclass +class ParseResult: + entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액) + errors: list[str] = field(default_factory=list) + skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄) + + +# ════════════════════════════════════════════════════════════ +# 파일 읽기 +# ════════════════════════════════════════════════════════════ +def _decode_csv(content: bytes) -> str: + for enc in ("utf-8-sig", "cp949"): + try: + return content.decode(enc) + except UnicodeDecodeError: + continue + raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).") + + +def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]: + """CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로).""" + if not content: + raise UploadError("빈 파일입니다.") + if len(content) > MAX_FILE_BYTES: + raise UploadError("파일이 너무 큽니다(5MB 이하).") + is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx") + if not is_xlsx: + return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))] + try: + import openpyxl # noqa: WPS433 + + wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True) + except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내 + raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None + try: + return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)] + finally: + wb.close() + + +def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult: + """쿠팡(로켓) 광고 보고서 → (날짜, 청구금액(+부가가치세)). 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음).""" + rows = read_rows(content, filename) + res = ParseResult() + seen: dict[date, int] = {} + for r, row in enumerate(rows, start=1): + raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_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 r == 1: # 머리글 + res.skipped += 1 + continue + res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).") + continue + if day is None: + res.skipped += 1 + continue + raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None + try: + amt = parse_amount(raw_amt) + except ValueError: + res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).") + continue + if amt is None: + res.errors.append(f"{r}행 19열: {day.isoformat()} 청구금액이 비어 있습니다.") + elif abs(amt) > MAX_AMOUNT: + res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.") + 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 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("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.") + return res + + +# 업로드 양식이 정해진 채널 → 파일 읽기 함수 +PARSERS: dict[str, Callable[..., ParseResult]] = {"coupang_rocket": parse_coupang_rocket} +UPLOAD_HELP = { + "coupang_rocket": "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다.", +} + + +# ════════════════════════════════════════════════════════════ +# 화면 데이터 +# ════════════════════════════════════════════════════════════ +def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date, + custom_from: date | None = None, custom_to: date | None = None, + holidays: Mapping[str, str] | None = None, + sales_codes: Sequence[str] = ()) -> dict[str, Any]: + """광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적. + sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다.""" + codes = list(CHANNEL_CODES) + period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to) + cmp_start, cmp_end, cmp_label = period.compare_range(today) + ref = period.end if period.end < today else today if period.start <= today else period.start + month_period = calc.resolve_period("month", ref) + year_period = calc.resolve_period("year", ref) + m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today) + y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today) + q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start) + q_end = max(period.end, year_period.end) + + migration_needed = False + try: + amounts, sources = store.ad_amounts(q_start, q_end) + except AdMigrationNeeded: + amounts, sources, migration_needed = {}, {}, True + cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()} + + cur = calc.sum_range(cells, codes, period.start, period.end) + prev = calc.sum_range(cells, codes, cmp_start, cmp_end) + mtd = calc.sum_range(cells, codes, month_period.start, month_period.end) + m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end) + ytd = calc.sum_range(cells, codes, year_period.start, year_period.end) + y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end) + + sales_total = None + if sales_codes: + daily = store.daily_amounts(period.start, period.end, list(sales_codes)) + sales_total = sum(int(v) for v in daily.values()) + ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None + + word = {"day": "오늘" if period.start == today else "해당일", + "week": "이번주" if period.start <= today <= period.end else "해당 주", + "month": "이번달" if period.start <= today <= period.end else "해당 월", + "year": "올해" if period.start <= today <= period.end else "해당 연도", + "custom": "선택 기간"}[period.kind] + kpis = [ + {"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True, + "delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True}, + {"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio, + "note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"}, + {"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross, + "delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True}, + {"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross, + "delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True}, + ] + + def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str: + if k == "custom": + return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}" + return f"?period={k}&d={anchor_d.isoformat()}" + + if period.kind == "custom": + from datetime import timedelta # noqa: WPS433 + + length = timedelta(days=period.days) + prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1)) + next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length) + else: + prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor) + nav = {"prev": prev_url, "next": next_url, "quick": [ + {"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today}, + {"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end}, + {"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end}, + {"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end}, + ]} + + share = calc.by_code(cells, codes, period.start, period.end) + month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells) + return { + "nav": nav, + "period": period, + "period_kind": period.kind, + "today": today.isoformat(), + "codes": codes, + "names": dict(CHANNEL_NAMES), + "kpis": kpis, + "table": calc.main_table(period, codes, cells, today=today, holidays=holidays), + "month": month, + "year": calc.year_months(year_period.start.year, codes, cells, today=today), + "chart_daily": calc.daily_series(period, codes, cells), + "chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes], + # 업로드로 들어온 칸(표시용) — "날짜|채널" + "upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items() + if s == "upload" 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/db.py b/app/modules/performance/db.py index 88eb0aa..80b8f2b 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -373,6 +373,54 @@ class PerformanceDBStore: raise ManualMigrationNeeded() from None return len(entries) + # ════════════════════════════════════════════════════════════ + # 광고비(마이그레이션 005) + # ════════════════════════════════════════════════════════════ + def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]: + """(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded.""" + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + try: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT spend_date, channel_code, amount, source FROM perf_ad_spend " + "WHERE spend_date BETWEEN %s AND %s", (start, end), + ).fetchall() + except pg_errors.UndefinedTable: + raise AdMigrationNeeded() from None + return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows}, + {(r["spend_date"], r["channel_code"]): r["source"] for r in rows}) + + def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None: + """광고비 한 칸 저장(amount None = 지움).""" + 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 은 지움). 하나라도 실패하면 모두 취소.""" + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + if not entries: + return 0 + 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, + ) + except pg_errors.UndefinedTable: + raise AdMigrationNeeded() from None + return len(entries) + 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 6d566da..65c1c1a 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -2,6 +2,7 @@ 화면 GET /performance/ 대시보드(모듈 권한) + GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일 GET /performance/settings 실적 설정(관리자) JSON API — 모듈 권한 POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리) @@ -13,6 +14,8 @@ JSON API — 모듈 권한 PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지) 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열 청구금액) JSON API — 관리자 PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부 POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일) @@ -50,6 +53,8 @@ MAX_BACKFILL_DAYS = 366 MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간) 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)를 " + "먼저 적용해야 합니다.") MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 " "먼저 적용해야 합니다.") @@ -119,6 +124,33 @@ def dashboard_page( return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) +@router.get("/ads", response_class=HTMLResponse) +def ads_page( + request: Request, + period: str = "month", + d: str | None = None, + from_: str | None = Query(None, alias="from"), + to: str | None = None, +): + from app.main import render_template # noqa: WPS433 + + g = common.guard(request) + if not isinstance(g, tuple): + return g + store, user = g + from .ad_spend import build_ad_dashboard # noqa: WPS433 + from .dashboard import _sales_marketplaces # noqa: WPS433 + + today = today_kst() + ctx = build_ad_dashboard( + store, kind=period, anchor=_parse_date(d) or today, today=today, + custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(), + sales_codes=[m["code"] for m in _sales_marketplaces(store)], + ) + return render_template(request, "performance/ads.html", + {**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) + + @router.get("/settings", response_class=HTMLResponse) def settings_page(request: Request): from app.main import render_template # noqa: WPS433 @@ -358,6 +390,77 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes }) +# ════════════════════════════════════════════════════════════ +# JSON API — 광고비(모듈 권한자 누구나) +# ════════════════════════════════════════════════════════════ +def _ad_channel(channel: str) -> str: + from .ad_spend import CHANNEL_NAMES # noqa: WPS433 + + if channel not in CHANNEL_NAMES: + raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.") + return channel + + +@router.put("/api/ad-spend/{channel}/{day}") +def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: + from .ad_spend import AdMigrationNeeded # noqa: WPS433 + + store, user = common.require_store(request) + _ad_channel(channel) + d = _parse_date(day) + if d is None: + raise HTTPException(status_code=400, detail="날짜가 필요합니다.") + if d > today_kst(): + raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.") + raw = payload.get("amount") + amount: int | None + if raw in (None, ""): + amount = None + else: + try: + amount = int(Decimal(str(raw).replace(",", "").strip())) + except (InvalidOperation, ValueError): + raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None + if abs(amount) > MAX_MANUAL_AMOUNT: + 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 + return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, + "amount": amount or 0}) + + +@router.post("/api/ad-spend/upload") +def api_ad_spend_upload(request: Request, channel: str = Query(...), file: UploadFile = File(...)) -> JSONResponse: + """광고비 파일 업로드 — 파일에 있는 날만 덮어쓴다. 잘못된 줄이 있으면 아무것도 저장하지 않는다.""" + from . import ad_spend # noqa: WPS433 + from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433 + + store, user = common.require_store(request) + _ad_channel(channel) + parser = ad_spend.PARSERS.get(channel) + if parser is None: + raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.") + content = file.file.read(MAX_FILE_BYTES + 1) + try: + res = parser(content, today=today_kst(), filename=file.filename or "") + except UploadError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from None + if res.errors: + return JSONResponse(status_code=400, content={ + "detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.", + "errors": res.errors}) + 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 + 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, + "from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None}) + + # ════════════════════════════════════════════════════════════ # JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자) # ════════════════════════════════════════════════════════════ diff --git a/app/modules/performance/templates/performance/_tabs.html b/app/modules/performance/templates/performance/_tabs.html index eb98526..9fc886e 100644 --- a/app/modules/performance/templates/performance/_tabs.html +++ b/app/modules/performance/templates/performance/_tabs.html @@ -1,5 +1,16 @@ -{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #} +{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘). + 설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #} + diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html new file mode 100644 index 0000000..99f9df9 --- /dev/null +++ b/app/modules/performance/templates/performance/ads.html @@ -0,0 +1,204 @@ +{% extends "erp_base.html" %} + +{% block head_extra %}{% endblock %} + +{%- macro won(v) -%} + {%- if v is none -%} + {%- elif v == 0 -%}– + {%- else -%}{{ "{:,}".format(v) }}{%- endif -%} +{%- endmacro -%} + +{% block content %} +{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#} +
+ {% include "performance/_tabs.html" %} + +
+
+ {% for q in nav.quick %} + {{ q.label }} + {% endfor %} + +
+ + + +
+ + + ~ + + +
+
+ + {% if migration_needed %} +
광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005 + (scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.
+ {% endif %} + + +
+ {% for k in kpis %} +
+
{{ k.label }}
+ {% if k.key == 'ratio' %} +
{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}
+
{{ k.note }}
+ {% else %} +
₩{{ "{:,}".format(k.value) }}
+
+ {% if k.delta is none %}{{ k.cmp }} 비교 없음 + {% else %} + {% set up = k.delta > 0 %} + + {% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}% + {{ k.cmp }} 대비 + {% endif %} +
+ {% endif %} +
+ {% endfor %} +
+ + +
+
+

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

+ {% if upload_channels %} + + {% endif %} +
+
+ + + + + {% for c in codes %}{% endfor %} + + + + + {% for r in table %} + + + {% for c in codes %} + {% set v = r.cells[c].gross %} + {% if r.kind == 'day' and not r.future and not migration_needed %} + {% set up = (r.date ~ '|' ~ c) in upload_cells %} + + {% else %} + + {% endif %} + {% endfor %} + + + {% endfor %} + +
{% if period_kind == 'year' %}월{% else %}날짜{% endif %}{{ names[c] }} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}
+ {{ r.label }}{% if r.holiday %}{{ r.holiday }}{% endif %} + {{ won(v) }}{{ won(v) }}{{ won(r.total.gross) }}
+
+ {% if period_kind != 'year' %} +

날짜 칸을 눌러 그날 광고비를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. + 파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값. 쿠팡(로켓)은 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.

+ {% endif %} +
+ + +
+
+

{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이

+
+
+
+

채널별 비중

+ {{ period.label }}
+
+
+
+ + +
+
+

{{ month.label }} 채널별 광고비

+
+ + + + {% for r in month.rows %} + + + + + + {% endfor %} + + + + + + + + +
채널광고비비중
{{ names[r.code] }}{{ won(r.gross) }} + {% if r.share is not none %}{{ "%.1f" | format(r.share) }}%{% else %}–{% endif %} +
합계{{ won(month.total.gross) }}{% if month.total.share is not none %}100%{% else %}–{% endif %}
+
+
+ +
+

{{ year.year }}년 누적 광고비

+
+
광고비₩{{ "{:,}".format(year.total.gross) }}
+
+
+ + + + {% for r in year.rows %} + + + + + {% endfor %} + + + + + + + +
월광고비
{{ r.label }}{{ won(r.gross) }}
합계{{ won(year.total.gross) }}
+
+
+
+ +

+ 광고비 기준: 쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세). 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출. + 구글·메타·쿠팡(윙)은 지금은 직접 입력합니다. +

+
+ + +{% endblock %} + +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 41b9d2b..3baca86 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 9735a75..a84a151 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 new file mode 100644 index 0000000..6f37eb5 --- /dev/null +++ b/app/modules/performance/tests/test_ad_spend.py @@ -0,0 +1,164 @@ +"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립.""" + +from __future__ import annotations + +import io +from datetime import date + +import openpyxl +import pytest + +from app.modules.performance import ad_spend as ads +from app.modules.performance.manual_upload import UploadError + +TODAY = date(2026, 10, 13) + +# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄 +ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세) +전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494 +2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000 +,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,, +2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697 +,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,, +2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231 +,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,, +""" + + +def _xlsx(text: str) -> bytes: + wb = openpyxl.Workbook() + ws = wb.active + for line in text.strip().splitlines(): + ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")]) + buf = io.BytesIO() + wb.save(buf) + return buf.getvalue() + + +@pytest.mark.parametrize("content,name", [ + (ROCKET_CSV.encode("utf-8-sig"), "report.csv"), + (ROCKET_CSV.encode("cp949"), "report.csv"), + (_xlsx(ROCKET_CSV), "report.xlsx"), +]) +def test_rocket_report_reads_date_and_col19(content, name): + res = ads.parse_coupang_rocket(content, today=TODAY, filename=name) + assert not res.errors + assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)] + assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개 + + +def test_rocket_report_errors_block_everything(): + bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,9\n" # 같은 날 두 번 + bad += "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류 + bad += "2026년 10월 07일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,\n" # 금액 빈 칸 + bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜 + res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY) + joined = " / ".join(res.errors) + assert len(res.errors) == 4, res.errors + assert "겹칩니다" in joined and "날짜를 읽을 수 없습니다" in joined and "비어 있습니다" in joined and "앞으로의 날짜" in joined + + +def test_rocket_report_wrong_file(): + with pytest.raises(UploadError): + ads.parse_coupang_rocket(b"", today=TODAY) + with pytest.raises(UploadError): # 날짜 줄이 하나도 없음 + ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY) + other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류 + assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0] + with pytest.raises(UploadError): + ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx") + + +class _Store: + def __init__(self, missing=False): + self.missing = missing + + def ad_amounts(self, start, end): + if self.missing: + raise ads.AdMigrationNeeded() + rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), + (date(2026, 10, 2), "google"): (50000, "manual"), + (date(2026, 9, 1), "meta"): (100000, "manual")} + 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 daily_amounts(self, start, end, codes): + return {(date(2026, 10, 5), "cafe24"): 2_700_000} + + +def test_ad_dashboard_month(): + ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), + sales_codes=["cafe24"]) + assert ctx["codes"] == ["google", "meta", "coupang_wing", "coupang_rocket"] + k = {x["key"]: x for x in ctx["kpis"]} + 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_rocket"] + 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 + assert ctx["nav"]["quick"][2]["active"] # 이번달 + + +def test_ad_dashboard_year_and_missing_table(): + ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) + rows = {r["label"]: r for r in ctx["table"]} + assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000 + assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음 + miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) + assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0 + + +def test_ad_spend_endpoints(monkeypatch): + """라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400, + 칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503.""" + 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.missing = [], False + + def set_ad_spend_bulk(self, code, entries, *, source="manual", user=""): + if self.missing: + raise ads.AdMigrationNeeded() + self.saved.extend((code, d, a, source) for d, a in entries) + return len(entries) + + def set_ad_spend(self, code, day, amount, *, source="manual", user=""): + self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user) + + 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=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))}) + assert r.status_code == 200, r.text + assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12" + assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload") + store.saved.clear() + bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,9\n" + r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))}) + assert r.status_code == 400 and r.json()["errors"] and store.saved == [] + r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")}) + assert r.status_code == 400 and "양식" in r.json()["detail"] + + assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000 + assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200 + assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")] + assert client.put("/performance/api/ad-spend/naver/2026-10-12", json={"amount": 1}).status_code == 404 + assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400 + assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400 + 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"] diff --git a/app/static/performance.css b/app/static/performance.css index fa9666c..608e28e 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -25,13 +25,41 @@ .perf-center { text-align: center; } /* 탭 */ -.perf-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--perf-line); } -.perf-tab { - padding: 8px 14px; font-size: 13px; font-weight: 500; color: var(--color-midtone-gray); - border-bottom: 2px solid transparent; margin-bottom: -1px; +/* [매출 실적] [광고비] — 큰 알약 탭 둘, 고른 탭은 채운 색(매출 = 검정, 광고비 = 주황)으로 한눈에 구분. + 설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols "settings"). */ +.perf-tabs { + display: flex; align-items: center; gap: 8px; padding-bottom: 10px; border-bottom: 1px solid var(--perf-line); } -.perf-tab:hover { color: var(--color-rich-black); } -.perf-tab.is-active { color: var(--color-rich-black); border-bottom-color: var(--color-rich-black); } +.perf-tabs-main { + display: inline-flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--color-ghost-gray, #f3f3f3); +} +.perf-tab { + display: inline-flex; align-items: center; gap: 6px; padding: 7px 16px; border-radius: 9px; + font-size: 14px; font-weight: 600; color: var(--color-midtone-gray); text-decoration: none; + transition: background .15s, color .15s, box-shadow .15s; +} +.perf-tab .material-symbols-outlined { font-size: 19px; } +.perf-tab:hover { color: var(--color-rich-black); background: rgba(255, 255, 255, .7); } +.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); } +.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); } +.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); } +a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } +.perf-tab-gear { + margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; + border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none; +} +.perf-tab-gear .material-symbols-outlined { font-size: 22px; } +.perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); } +.perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); } + +/* 광고비 화면 — 주황 강조(매출 실적과 구분) */ +.perf, .perf-modal { --perf-ad: #d9480f; } +.perf-ads .perf-kpi.is-primary { border-color: var(--perf-ad); box-shadow: inset 4px 0 0 var(--perf-ad); } +.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); } +.perf-ads .perf-chart .bar { fill: var(--perf-ad); } +.perf-ads td.is-upload .v-gross { color: var(--perf-ad); } +.perf-ad-upload-btn { margin-left: auto; } +.perf-kpi-pct { font-size: 26px; font-weight: 700; } /* 도구 막대 */ .perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; } @@ -229,6 +257,9 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } .perf-test-result.is-ok { color: #0f8a3a; } .perf-test-result.is-bad { color: var(--perf-down); } +@media (min-width: 1281px) { + .perf-ads .perf-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* 광고비 KPI 4개 */ +} @media (max-width: 1280px) { .perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); } } diff --git a/app/static/performance.js b/app/static/performance.js index f8b8986..99f23cc 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -236,15 +236,20 @@ const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}"); const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" }; const KEY = "perf_metric"; + const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐 + const MANUAL_API = data.manual_api || "/performance/api/manual-sales/"; + const MANUAL_WORD = data.manual_word || "총매출"; + const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다."; // 표시 기준 전환 — 서버가 세 값을 다 그려 두었고 CSS 가 하나만 보인다. function setMetric(m) { + if (FIXED_METRIC) m = FIXED_METRIC; if (!METRIC_NAMES[m]) m = "gross"; root.dataset.metric = m; root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) { b.classList.toggle("is-active", b.dataset.metric === m); }); - try { localStorage.setItem(KEY, m); } catch (_) {} + if (!FIXED_METRIC) { try { localStorage.setItem(KEY, m); } catch (_) {} } drawDaily(m); drawShare(m); root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; }); @@ -311,6 +316,69 @@ }); }); + // 광고비 파일 업로드 — 채널(양식이 정해진 채널만)을 고르고 파일을 올리면 파일에 있는 날만 덮어쓴다. + // 잘못된 줄이 있으면 서버가 아무것도 저장하지 않고 줄 위치 목록을 돌려준다. + const adUploadBtn = document.getElementById("perf-ad-upload"); + if (adUploadBtn) adUploadBtn.addEventListener("click", function () { + let saved = false; + const chans = data.upload_channels || []; + const m = openModal("광고비 파일 업로드", { narrow: true, onClose: function () { if (saved) location.reload(); } }); + m.body.innerHTML = + '' + + '" + + '

' + + '' + + '
'; + const sel = m.body.querySelector(".perf-ad-channel"); + const help = m.body.querySelector(".perf-ad-help"); + function showHelp() { + const c = chans.filter(function (x) { return x.code === sel.value; })[0]; + help.textContent = c ? c.help : ""; + } + sel.addEventListener("change", showHelp); + showHelp(); + const fileInput = m.body.querySelector(".perf-upload-file"); + const out = m.body.querySelector(".perf-upload-result"); + const go = el("button", { type: "button", class: "erp-btn erp-btn-primary" }, "업로드"); + const cancel = el("button", { type: "button", class: "erp-btn erp-btn-ghost" }, "닫기"); + m.foot.appendChild(cancel); + m.foot.appendChild(go); + cancel.addEventListener("click", m.close); + go.addEventListener("click", async function () { + const f = fileInput.files && fileInput.files[0]; + if (!f) { out.innerHTML = '

파일을 고르세요.

'; return; } + go.disabled = true; + out.innerHTML = '

올리는 중…

'; + const fd = new FormData(); + fd.append("file", f); + let res, body = null; + try { + res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value), + { method: "POST", credentials: "same-origin", body: fd }); + try { body = await res.json(); } catch (_) { body = null; } + } catch (err) { + out.innerHTML = '

업로드 실패: ' + esc(err.message) + "

"; + go.disabled = false; + return; + } + go.disabled = false; + if (!res.ok) { + const detail = body && typeof body.detail === "string" ? body.detail : "업로드 실패 (" + res.status + ")"; + const errs = body && body.errors && body.errors.length + ? '" : ""; + out.innerHTML = '

' + esc(detail) + "

" + errs; + return; + } + saved = body.saved > 0; + out.innerHTML = '

' + esc(body.name) + " " + fmt(body.saved) + "일 반영 (" + + esc(body.from === body.to ? body.from : body.from + " ~ " + body.to) + ") · 합계 " + fmt(body.total) + "원

" + + '

창을 닫으면 표·합계·그래프가 다시 계산됩니다.

'; + fileInput.value = ""; + }); + }); + // 직접선택 / 쇼핑몰 필터 const customBtn = document.getElementById("perf-custom-btn"); const customForm = document.getElementById("perf-custom"); @@ -413,13 +481,15 @@ if (raw !== "" && !/^-?\d+$/.test(raw)) return Promise.reject(new Error("숫자(원)만 입력하세요.")); if (raw === was) return Promise.resolve(false); // 바뀐 것 없음(빈 칸 그대로 포함) const job = manualChain.then(function () { - return api("PUT", "/performance/api/manual-sales/" + encodeURIComponent(td.dataset.manualCode) + "/" + + return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" + encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : Number(raw) }); }).then(function (res) { const manual = res.manual == null ? "" : String(res.manual); td.dataset.manualValue = manual; td.classList.toggle("is-manual", manual !== ""); - td.title = manual !== "" ? "수동 입력값 — 눌러 고치기(비우고 저장하면 API 값)" : "눌러 총매출 직접 입력"; + td.classList.remove("is-upload"); + td.title = manual !== "" ? "직접 입력값 — 눌러 고치기(비우고 저장하면 " + (FIXED_METRIC ? "지움" : "API 값") + ")" + : "눌러 " + MANUAL_WORD + " 직접 입력"; const g = td.querySelector(".v-gross"); if (g) g.innerHTML = won(res.amount); td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산 @@ -432,10 +502,10 @@ function editManual(td) { if (td.querySelector(".perf-manual-input")) return; const input = el("input", { type: "text", inputmode: "numeric", class: "perf-manual-input", - "aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " 총매출" }); + "aria-label": ((data.names || {})[td.dataset.manualCode] || "") + " " + td.dataset.date + " " + MANUAL_WORD }); input.value = digitsOf(td); const g = td.querySelector(".v-gross"); - input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || "총매출"; + input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || MANUAL_WORD; td.classList.add("is-editing"); td.appendChild(input); input.focus(); @@ -529,7 +599,7 @@ const pts = data.daily || []; const vals = pts.map(function (p) { return p[metric] || 0; }); if (!pts.length || vals.every(function (v) { return !v; })) { - box.innerHTML = '
기간 내 매출이 없습니다.
'; + box.innerHTML = '
' + esc(EMPTY_TEXT) + "
"; return; } const W = 640, H = 230, L = 48, R = 8, T = 10, B = 26; @@ -560,7 +630,7 @@ if (!box) return; const rows = (data.share || []).slice().sort(function (a, b) { return (b[metric] || 0) - (a[metric] || 0); }); const total = rows.reduce(function (s, r) { return s + Math.max(0, r[metric] || 0); }, 0); - if (!rows.length || total <= 0) { box.innerHTML = '
기간 내 매출이 없습니다.
'; return; } + if (!rows.length || total <= 0) { box.innerHTML = '
' + esc(EMPTY_TEXT) + "
"; return; } const W = 640, rowH = 22, L = 120, R = 150, H = rows.length * rowH + 6; const maxV = Math.max.apply(null, rows.map(function (r) { return Math.max(0, r[metric] || 0); })) || 1; let g = ""; diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index e7bb026..c0427e5 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -184,6 +184,19 @@ cd /opt/www/main docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_004_naver_name.sql ``` +## 실적 광고비 마이그레이션 (performance_db 005) + +005는 광고비 표 `perf_ad_spend` 하나만 만든다(기존 표·데이터 그대로, 다시 실행 가능). 미적용이면 광고비 탭에 안내가 나오고 입력·업로드가 503. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_005_$(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_005_ad_spend.sql +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;"` + ## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) 026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index bc1e38b..a19aecb 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -339,6 +339,17 @@ ## 7. 화면 +- **탭**(2026-10-13): 왼쪽 위 큰 탭 둘 — [매출 실적](검정, `/performance/`) · [광고비](주황, `/performance/ads`) — 아이콘 + 고른 탭 색으로 구분, + 설정은 맨 오른쪽 톱니 아이콘(프로젝트 모듈과 같은 Material Symbols `settings`, `/performance/settings`). `_tabs.html`. +- **광고비** `/performance/ads?period=…`(기본 이번달) — 매출 실적과 같은 기간 이동(오늘/이번주/이번달/올해/직접선택)·표(일자 × 채널, + 연간은 월)·일별 추이·채널 비중·월/연 누적. 채널 = 구글·메타·쿠팡(윙)·쿠팡(로켓)(`ad_spend.CHANNELS`, 앱이 정함). + KPI: 기간 광고비(전기간 대비), 매출 대비 광고비(같은 기간 광고비 ÷ 매출 실적 총매출), 월·연 누적. + 저장 `perf_ad_spend`(마이그레이션 005 — 채널 × 날짜 하나에 금액, `source` manual/upload/api), 미적용이면 화면에 안내·API 503. + - 날짜 칸을 눌러 직접 입력(`PUT /api/ad-spend/{channel}/{day}`, 비우면 지움, 오늘까지) — 파란 숫자. 매출 수동 입력과 같은 JS(`MANUAL_API`). + - [파일 업로드](`POST /api/ad-spend/upload?channel=`) — 양식이 정해진 채널만(`ad_spend.PARSERS`). 파일에 있는 날만 덮어쓰고(주황 숫자), + 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다. **쿠팡(로켓)** = 쿠팡 광고 보고서 CSV(UTF-8/CP949)·엑셀: + 1열 날짜(`2026년 10월 01일`), 19열 청구금액(+부가가치세). "전체" 합계 줄·머리글·캠페인 줄(1열 빈 칸)은 건너뜀. + - 쿠팡(윙)·구글·메타 업로드 양식/API 는 아직 — 지금은 직접 입력. - **대시보드** `/performance/?period=day|week|month|year|custom&d=&from=&to=&m=<쇼핑몰>…` 기간 버튼(오늘/이번주/이번달/올해/직접선택) + 이전/다음, 쇼핑몰 필터, KPI 5개, 일자×쇼핑몰 표(주간합계·기간합계, 연간은 월 행), [총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG), diff --git a/scripts/sql/performance_db_005_ad_spend.sql b/scripts/sql/performance_db_005_ad_spend.sql new file mode 100644 index 0000000..6f83921 --- /dev/null +++ b/scripts/sql/performance_db_005_ad_spend.sql @@ -0,0 +1,36 @@ +-- ===================================================================== +-- performance_db 마이그레이션 005 — 광고비(채널 × 날짜) +-- ===================================================================== +-- 멱등(idempotent). 새 표 하나만 만든다(기존 표·데이터 그대로). 운영: /opt/www/main 에서 superuser 로 적용. +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \ +-- < scripts/sql/performance_db_005_ad_spend.sql +-- +-- 왜(2026-10-13 사용자 요청): 실적 모듈 "광고비" 탭 — 구글·메타·쿠팡(윙)·쿠팡(로켓) 광고비를 연·월·일로. +-- 쿠팡(로켓)은 광고 보고서 파일 업로드(1열 날짜, 19열 청구금액(+부가가치세)), 나머지는 날짜 칸 직접 입력. +-- 채널 목록은 앱(app/modules/performance/ad_spend.py CHANNELS)이 정한다 — 채널을 늘려도 이 표는 그대로. +-- 되돌리기: DROP TABLE perf_ad_spend; (광고비 데이터만 사라짐 — 실행 전 백업) +-- ===================================================================== +BEGIN; + +CREATE TABLE IF NOT EXISTS perf_ad_spend ( + channel_code TEXT NOT NULL, + spend_date DATE NOT NULL, + amount BIGINT NOT NULL, + source TEXT NOT NULL DEFAULT 'manual' CHECK (source IN ('manual', 'upload', 'api')), + updated_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (channel_code, spend_date) +); +COMMENT ON TABLE perf_ad_spend IS '광고비 — 채널(google·meta·coupang_wing·coupang_rocket) × 날짜 하나에 금액 하나(원)'; +COMMENT ON COLUMN perf_ad_spend.source IS 'manual=화면 직접 입력, upload=파일 업로드, api=광고 API 수집'; +CREATE INDEX IF NOT EXISTS idx_perf_ad_spend_date ON perf_ad_spend (spend_date); +DROP TRIGGER IF EXISTS trg_perf_ad_spend_updated ON perf_ad_spend; +CREATE TRIGGER trg_perf_ad_spend_updated + BEFORE UPDATE ON perf_ad_spend + FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at(); + +GRANT SELECT, INSERT, UPDATE, DELETE ON perf_ad_spend TO performance_app; + +COMMIT; +SELECT 'performance_db 005 ad spend ready' AS status; diff --git a/tests/js/perf_manual.test.js b/tests/js/perf_manual.test.js index 6970553..1039a2c 100644 --- a/tests/js/perf_manual.test.js +++ b/tests/js/perf_manual.test.js @@ -20,8 +20,17 @@ async function env(file) { w.erpAlert = function (m) { e.alerts.push(m); return Promise.resolve(); }; w.fetch = async function (url, o) { const method = (o && o.method) || "GET"; - const body = o && o.body ? JSON.parse(o.body) : null; - e.calls.push({ method: method, url: url, body: body }); + 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\/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" }; } }; + } + const ad = /^\/performance\/api\/ad-spend\/([^/]+)\/([\d-]+)$/.exec(url); + if (ad) { + return { ok: true, status: 200, json: async function () { return { ok: true, manual: body.amount, amount: body.amount || 0 }; } }; + } if (e.status >= 400) return { ok: false, status: e.status, json: async function () { return { detail: "수동 입력을 쓰려면 마이그레이션 002" }; } }; const m = /^\/performance\/api\/manual-sales\/([^/]+)\/([\d-]+)$/.exec(url); if (m) { @@ -119,13 +128,67 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); } key(e, td, "Enter"); check("[키보드] 칸에 포커스 후 Enter → 입력칸", !!td.querySelector(".perf-manual-input")); } + // ── 탭: [매출 실적] [광고비] + 맨 오른쪽 설정 톱니 ── + { + const e = await env("perf_dash.html"); + const tabs = Array.from(e.d.querySelectorAll(".perf-tabs-main .perf-tab")).map(function (a) { return a.textContent.replace(/monitoring|campaign/, "").trim(); }); + check("[탭] 매출 실적 · 광고비", tabs.join(",") === "매출 실적,광고비", tabs); + check("[탭] 매출 실적이 고른 탭", e.d.querySelector(".perf-tab-sales").classList.contains("is-active") && + !e.d.querySelector(".perf-tab-ads").classList.contains("is-active")); + const gear = e.d.querySelector(".perf-tabs > .perf-tab-gear"); + check("[탭] 설정 = 맨 오른쪽 톱니 아이콘(settings)", gear && gear === e.d.querySelector(".perf-tabs").lastElementChild && + gear.getAttribute("href") === "/performance/settings" && gear.textContent.trim() === "settings" && !!gear.title); + } + // ── 광고비 화면 ── + { + 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(); }); + check("[광고비] 열 = 구글·메타·쿠팡(윙)·쿠팡(로켓)", heads.join(",") === "날짜,구글,메타,쿠팡(윙),쿠팡(로켓),일 합계", heads); + const up = cell(e, "coupang_rocket", "2026-10-01"), man = cell(e, "google", "2026-10-02"); + check("[광고비] 업로드 값 = 주황(is-upload), 직접 입력 = 파랑(is-manual)", up.classList.contains("is-upload") && + !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 — 이번달 광고비 270,000 · 매출 대비 비율", kpi[0] === "₩270,000" && /%$/.test(kpi[1]), kpi); + check("[광고비] 매출 실적의 수수료 전환 없음", !e.d.querySelector(".perf-metric") && e.d.getElementById("perf-dash").dataset.metric === "gross"); + const td = cell(e, "meta", "2026-10-03"); + td.click(); + const inp = td.querySelector(".perf-manual-input"); + check("[광고비] 칸을 누르면 입력칸(광고비)", !!inp && /광고비/.test(inp.getAttribute("aria-label"))); + inp.value = "33,000"; + key(e, inp, "Escape"); + td.click(); + const inp2 = td.querySelector(".perf-manual-input"); + inp2.value = "33,000"; + inp2.dispatchEvent(new e.w.FocusEvent("blur")); + await settle(); + const put = e.calls.find(function (c) { return c.method === "PUT"; }); + check("[광고비] 저장 → /api/ad-spend/meta/2026-10-03 (33000)", put && put.url === "/performance/api/ad-spend/meta/2026-10-03" && + put.body.amount === 33000, e.calls); + check("[광고비] 저장 후 파란 표시", gross(td) === "33,000" && td.classList.contains("is-manual")); + // 파일 업로드 창 + 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_rocket", opts); + check("[업로드] 양식 안내(19열 청구금액)", /19열/.test(modal.querySelector(".perf-ad-help").textContent)); + const fileInput = modal.querySelector(".perf-upload-file"); + const f = new e.w.File(["날짜"], "rocket.csv", { type: "text/csv" }); + Object.defineProperty(fileInput, "files", { value: [f] }); + Array.from(modal.querySelectorAll(".perf-modal-foot button, button")).filter(function (b) { return b.textContent === "업로드"; })[0].click(); + await settle(); + const post = e.calls.find(function (c) { return c.method === "POST"; }); + 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)); + } // ── 설정: 수동 입력 토글 ── { const e = await env("perf_settings.html"); const heads = Array.from(e.d.querySelectorAll(".perf-set-table thead th")).map(function (th) { return th.textContent.trim(); }); check("[설정] '수동 입력' 열(매출 집계 다음)", heads.indexOf("수동 입력") === heads.indexOf("매출 집계") + 1, heads); const rows = Array.from(e.d.querySelectorAll(".perf-set-table tbody tr")).map(function (tr) { return tr.dataset.code; }); - check("[설정] 쇼핑몰 순서 = 표 순서", rows.join(",") === "cafe24,naver,coupang,toss,gsshop,elevenst,ohouse,gmarket,kakao,lotteon", rows); + check("[설정] 쇼핑몰 순서 = 어댑터 등록 순서(003 열 순서)", rows.join(",") === "cafe24,naver,coupang,ohouse,gmarket,kakao,gsshop,elevenst,lotteon,toss", rows); const box = e.d.querySelector('tr[data-code="coupang"] input[data-field="manual_input"]'); check("[설정] 켜진 쇼핑몰은 체크", box && box.checked && !e.d.querySelector('tr[data-code="cafe24"] input[data-field="manual_input"]').checked); box.checked = false; diff --git a/tests/js/render_performance.py b/tests/js/render_performance.py index dfff232..3f7355f 100644 --- a/tests/js/render_performance.py +++ b/tests/js/render_performance.py @@ -1,6 +1,6 @@ -"""실적 대시보드(index.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터). +"""실적 대시보드(index.html)·광고비(ads.html)·설정(settings.html)을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터). - python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_settings.html + python tests/js/render_performance.py # → tests/js/.out/perf_dash.html · perf_ads.html · perf_settings.html 화면 데이터는 실제 build_dashboard·build_settings 로 만든다(저장소만 가짜). DB·쇼핑몰 API 는 쓰지 않는다. 쿠팡은 수동 입력 켬(10/5 수동 값 87,000, 10/6 은 API 값만), 카카오도 켬(값 없음), 나머지는 끔. @@ -19,6 +19,7 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__) sys.path.insert(0, ROOT) OUT_DIR = os.path.join(ROOT, "tests", "js", ".out") +from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402 from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402 BASE_STUB = ("{% block head_extra %}{% endblock %}
{% block content %}{% endblock %}
" @@ -56,6 +57,11 @@ class FakeStore: def running_codes(self): return [] + def ad_amounts(self, start, end): + rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"), (date(2026, 10, 2), "google"): (50000, "manual")} + 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 env() -> jinja2.Environment: e = jinja2.Environment(loader=jinja2.ChoiceLoader([ @@ -73,6 +79,11 @@ def main() -> None: html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx) with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f: f.write(html) + actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), + sales_codes=["cafe24", "coupang"]) + html = e.get_template("performance/ads.html").render(**base, active_tab="ads", **actx) + with open(os.path.join(OUT_DIR, "perf_ads.html"), "w", encoding="utf-8") as f: + f.write(html) sctx = build_settings(FakeStore(), configured={}, key_info={}, key_versions_in_use={}, sample_count=0) html = e.get_template("performance/settings.html").render(**base, active_tab="settings", **sctx) with open(os.path.join(OUT_DIR, "perf_settings.html"), "w", encoding="utf-8") as f: