From 454b3cc700d7db0f069b425dbc61b4f54e6c2cf1 Mon Sep 17 00:00:00 2001 From: king Date: Mon, 12 Oct 2026 17:26:57 +0900 Subject: [PATCH] feat(performance): per-shop manual sales input, column order, bold centered table headers (migration 002) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- app/modules/performance/adapters/registry.py | 7 +- app/modules/performance/dashboard.py | 9 +- app/modules/performance/db.py | 75 ++++++++- app/modules/performance/router.py | 55 ++++++- .../templates/performance/index.html | 17 +- .../templates/performance/settings.html | 15 +- .../performance/tests/test_performance.py | 109 +++++++++++++ app/static/performance.css | 17 +- app/static/performance.js | 83 ++++++++++ docs/DEPLOYMENT.md | 13 ++ docs/PERFORMANCE_MODULE.md | 13 ++ .../sql/performance_db_002_manual_sales.sql | 44 ++++++ scripts/sql/performance_db_init.sql | 36 ++++- tests/js/perf_manual.test.js | 145 ++++++++++++++++++ tests/js/render_performance.py | 84 ++++++++++ 16 files changed, 690 insertions(+), 34 deletions(-) create mode 100644 scripts/sql/performance_db_002_manual_sales.sql create mode 100644 tests/js/perf_manual.test.js create mode 100644 tests/js/render_performance.py diff --git a/CLAUDE.md b/CLAUDE.md index 6b120bd..e47ec82 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`), 세로 스크롤 틀 고정은 머리 줄+매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제, 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`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 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐. 용어는 "세부 작업"(예전 하위 작업)·"메인 작업 추가". 패널(`/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`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 상세는 `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`. 매출 업데이트 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로). 카페24 어댑터는 기존 `app/integrations/cafe24` 토큰 재사용. 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현. 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로). 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳). 열 순서 카페24·네이버·쿠팡·토스·GS샵·11번가·나머지. 상세는 `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/adapters/registry.py b/app/modules/performance/adapters/registry.py index 8bf78de..ea95bd2 100644 --- a/app/modules/performance/adapters/registry.py +++ b/app/modules/performance/adapters/registry.py @@ -19,16 +19,17 @@ from .ohouse import OhouseAdapter from .toss import TossAdapter _ADAPTERS: tuple[MarketplaceAdapter, ...] = ( + # 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 002) Cafe24Adapter(), NaverAdapter(), CoupangAdapter(), + TossAdapter(), + GsshopAdapter(), + ElevenstAdapter(), OhouseAdapter(), GmarketAdapter(), KakaoAdapter(), - GsshopAdapter(), - ElevenstAdapter(), LotteonAdapter(), - TossAdapter(), ) _BY_CODE = {a.code: a for a in _ADAPTERS} diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index 23bc798..654c390 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -58,6 +58,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start) q_end = max(period.end, year_period.end) cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table()) + # 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중) + manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes] + manual_amounts = getattr(store, "manual_amounts", None) + manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in + (manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {})) cur = calc.sum_range(cells, codes, period.start, period.end) prev = calc.sum_range(cells, codes, cmp_start, cmp_end) @@ -143,6 +148,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, "chart_daily": calc.daily_series(period, codes, cells), "chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes], "problems": problems, + "manual_codes": manual_codes, + "manual_cells": manual_cells, "last_update_at": store.last_update_at(), "running": store.running_codes(), "no_marketplaces": not all_codes, @@ -175,7 +182,7 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp has_rate = bool(rates.get(adapter.code)) rows.append({ "code": adapter.code, "name": m["name"], "enabled": m["enabled"], - "include_in_sales": m["include_in_sales"], + "include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")), "rate": _fmt_rate(cur_rate) if has_rate else "", "rate_history": len(rates.get(adapter.code, ())), "auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration, diff --git a/app/modules/performance/db.py b/app/modules/performance/db.py index 5ae6763..7aa942a 100644 --- a/app/modules/performance/db.py +++ b/app/modules/performance/db.py @@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta from decimal import Decimal from typing import Any, Iterable +from psycopg import errors as pg_errors from psycopg.rows import dict_row from psycopg.types.json import Jsonb from psycopg_pool import ConnectionPool @@ -25,6 +26,10 @@ from app.timezone import to_kst_iso STALE_RUN_AFTER = timedelta(minutes=30) +class ManualMigrationNeeded(Exception): + """수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음.""" + + def _iso(v: Any) -> Any: if isinstance(v, datetime): return to_kst_iso(v) @@ -56,8 +61,12 @@ class PerformanceDBStore: return [{k: _iso(v) for k, v in r.items()} for r in rows] def update_marketplace(self, code: str, *, enabled: bool | None = None, - include_in_sales: bool | None = None) -> dict[str, Any] | None: + include_in_sales: bool | None = None, + manual_input: bool | None = None) -> dict[str, Any] | None: sets, params = [], [] + if manual_input is not None: + sets.append("manual_input = %s") + params.append(bool(manual_input)) if enabled is not None: sets.append("enabled = %s") params.append(bool(enabled)) @@ -67,10 +76,13 @@ class PerformanceDBStore: if not sets: return None params.append(code) - with self._pool.connection() as conn: - row = conn.execute( - f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params - ).fetchone() + try: + with self._pool.connection() as conn: + row = conn.execute( + f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params + ).fetchone() + except pg_errors.UndefinedColumn: + raise ManualMigrationNeeded() from None return {k: _iso(v) for k, v in row.items()} if row else None # ════════════════════════════════════════════════════════════ @@ -281,6 +293,8 @@ class PerformanceDBStore: """ def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]: + """날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다 + (실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다).""" if not codes: return {} with self._pool.connection() as conn: @@ -290,7 +304,56 @@ class PerformanceDBStore: "GROUP BY sales_date, marketplace_code", (start, end, codes), ).fetchall() - return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows} + out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows} + out.update(self.manual_amounts(start, end, codes)) + return out + + # ════════════════════════════════════════════════════════════ + # 수동 입력 매출(마이그레이션 002) + # ════════════════════════════════════════════════════════════ + def manual_amounts(self, start: date, end: date, codes: list[str], *, + active_only: bool = True) -> dict[tuple[date, str], int]: + """수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음.""" + if not codes: + return {} + try: + with self._pool.connection() as conn: + rows = conn.execute( + "SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s " + "JOIN perf_marketplaces m ON m.code = s.marketplace_code " + "WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)" + + (" AND m.manual_input" if active_only else ""), + (start, end, codes), + ).fetchall() + except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn): + return {} + return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows} + + def api_amount(self, code: str, day: date) -> int: + """그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다.""" + with self._pool.connection() as conn: + row = conn.execute( + "SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events " + "WHERE marketplace_code = %s AND sales_date = %s", (code, day), + ).fetchone() + return int(row["amount"] or 0) + + def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None: + """수동 값 저장(amount None = 지움 → 그날은 다시 API 값).""" + try: + with self._pool.connection() as conn: + if amount is None: + conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s", + (code, day)) + else: + conn.execute( + "INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) " + "VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE " + "SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by", + (code, day, int(amount), user), + ) + except pg_errors.UndefinedTable: + raise ManualMigrationNeeded() from None def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]: """쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각. diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 51a0277..a1cfc85 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -10,8 +10,9 @@ JSON API — 모듈 권한 GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null) POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자) GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간) + PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지) JSON API — 관리자 - PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부 + PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부 POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일) DELETE /performance/api/marketplaces/{code}/rates/{id} GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음) @@ -44,6 +45,9 @@ MAX_EVENT_DAYS = 31 MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기) MAX_BACKFILL_DAYS = 366 MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간) +MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원) +MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 " + "먼저 적용해야 합니다.") def _parse_date(value: Any, *, field: str = "날짜") -> date | None: @@ -270,6 +274,39 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from" return JSONResponse({"rows": rows, "truncated": len(rows) >= 500}) +@router.put("/api/manual-sales/{code}/{day}") +def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: + """수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값).""" + from .db import ManualMigrationNeeded # noqa: WPS433 + + store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정) + _code_or_404(store, code) + d = _parse_date(day) + if d > today_kst(): + raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.") + m = next((x for x in store.list_marketplaces() if x["code"] == code), {}) + if not m.get("manual_input"): + 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_manual_sale(code, d, amount, user=user.get("email", "")) + except ManualMigrationNeeded: + raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None + api_amount = store.api_amount(code, d) + return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount, + "amount": api_amount if amount is None else amount, "api_amount": api_amount}) + + # ════════════════════════════════════════════════════════════ # JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자) # ════════════════════════════════════════════════════════════ @@ -277,11 +314,17 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from" def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: store, _ = common.require_store(request, admin=True) _code_or_404(store, code) - row = store.update_marketplace( - code, - enabled=bool(payload["enabled"]) if "enabled" in payload else None, - include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None, - ) + from .db import ManualMigrationNeeded # noqa: WPS433 + + try: + row = store.update_marketplace( + code, + enabled=bool(payload["enabled"]) if "enabled" in payload else None, + include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None, + manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None, + ) + except ManualMigrationNeeded: + raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None return JSONResponse({"marketplace": row}) diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 38b1568..c2c756b 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 -%} @@ -118,7 +118,7 @@ {% if period_kind == 'year' %}월{% else %}날짜{% endif %} - {% for c in codes %}{{ short_names[c] }}{% endfor %} + {% for c in codes %}{{ short_names[c] }}{% if c in manual_codes %} ✎{% endif %}{% endfor %} {% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %} @@ -130,8 +130,15 @@ {% for c in codes %} {% set m = r.cells[c] %} + {% if r.kind == 'day' and c in manual_codes and not r.future %} + {% set is_manual = (r.date ~ '|' ~ c) in manual_cells %} + {{ m3(m) }} + {% else %} {{ m3(m) }} + {% endif %} {% endfor %} {{ m3(r.total) }} @@ -139,6 +146,10 @@ + {% if manual_codes and period_kind != 'year' %} +

✎ 표시 쇼핑몰은 날짜 칸을 눌러 총매출을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, + 비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.

+ {% endif %} @@ -239,4 +250,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 e4be202..05f5c59 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 -%} @@ -20,7 +20,8 @@

쇼핑몰 설정

{% if is_admin %} - 사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다. + 사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다. + 수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다. {% else %} 쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다. {% endif %} @@ -31,7 +32,8 @@ 쇼핑몰 {% if is_admin %}사용 - 매출 집계{% endif %} + 매출 집계 + 수동 입력{% endif %} 수수료율 {% if is_admin %}API 설정 연결 상태{% endif %} @@ -54,6 +56,11 @@ + + + {% endif %} {% if r.rate %}{{ r.rate }}%{% else %}미설정{% endif %} @@ -194,4 +201,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 93723ae..188fb6d 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -1883,3 +1883,112 @@ if __name__ == "__main__": n += 1 print("ok", name) print(f"{n} tests passed") + + +def test_manual_sale_api_rules(): + """수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503. + 켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다.""" + from fastapi import HTTPException + + import importlib + + from app.modules.performance import common + from app.modules.performance.db import ManualMigrationNeeded + + router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체 + + class St: + def __init__(self): + self.saved, self.updated, self.missing = [], [], False + + def list_marketplaces(self): + return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}] + + def set_manual_sale(self, code, day, amount, *, user=""): + if self.missing: + raise ManualMigrationNeeded() + self.saved.append((code, day, amount, user)) + + def api_amount(self, code, day): + return 50000 + + def update_marketplace(self, code, **kw): + if self.missing and kw.get("manual_input") is not None: + raise ManualMigrationNeeded() + self.updated.append((code, kw)) + return {"code": code} + + st = St() + seen = {} + + def fake_require(request, *, admin=False): + seen["admin"] = admin + return st, {"email": "me@test.local"} + + def status_of(fn): + try: + fn() + except HTTPException as exc: + return exc.status_code, exc.detail + return 200, "" + + orig = (common.require_store, router.today_kst) + common.require_store, router.today_kst = fake_require, (lambda: date(2026, 10, 12)) + try: + r = router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "87,000"}) + body = __import__("json").loads(r.body) + assert st.saved[-1] == ("coupang", date(2026, 10, 12), 87000, "me@test.local") and seen["admin"] is False + assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000 + body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body) + assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값 + assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날 + code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1})) + assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰 + assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400 + assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 10 ** 13}))[0] == 400 + assert status_of(lambda: router.api_manual_sale(None, "nope", "2026-10-12", {"amount": 1}))[0] == 404 + router.api_update_marketplace(None, "coupang", {"manual_input": True}) + assert seen["admin"] is True and st.updated[-1] == ("coupang", {"enabled": None, "include_in_sales": None, "manual_input": True}) + st.missing = True + code, msg = status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 1})) + assert code == 503 and "002" in msg + assert status_of(lambda: router.api_update_marketplace(None, "coupang", {"manual_input": False}))[0] == 503 + finally: + common.require_store, router.today_kst = orig + + +def test_dashboard_manual_cells_and_order(): + """대시보드 — 수동 입력 켠 쇼핑몰만 manual_codes, 값이 있는 칸만 manual_cells, 수동 값이 그날 금액(수수료도 그 값으로).""" + from decimal import Decimal + + from app.modules.performance.dashboard import build_dashboard + + class St: + def list_marketplaces(self): + return [{"code": c, "name": c, "enabled": True, "include_in_sales": True, "manual_input": c == "coupang"} + for c in ("cafe24", "naver", "coupang", "toss")] + + def daily_amounts(self, start, end, codes): + return {(date(2026, 10, 5), "coupang"): 87000} # 저장소가 이미 수동 값으로 바꿔 돌려준다 + + def manual_amounts(self, start, end, codes, *, active_only=True): + assert codes == ["coupang"] + return {(date(2026, 10, 5), "coupang"): 87000} if start <= date(2026, 10, 5) <= end else {} + + def rate_table(self): + return {"coupang": [(date(2026, 1, 1), Decimal("10"))]} + + def statuses(self): + return {} + + def last_update_at(self): + return None + + def running_codes(self): + return [] + + ctx = build_dashboard(St(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) + assert ctx["codes"] == ["cafe24", "naver", "coupang", "toss"] + assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"] + day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05") + assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700 diff --git a/app/static/performance.css b/app/static/performance.css index 76057f7..2d57cd8 100644 --- a/app/static/performance.css +++ b/app/static/performance.css @@ -102,11 +102,12 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { .perf-table-wrap { overflow-x: auto; } .perf-table { width: 100%; border-collapse: collapse; font-size: 12.5px; } .perf-table th, .perf-table td { padding: 6px 8px; border-bottom: 1px solid #efefef; white-space: nowrap; } +/* 열 제목 — 가운데·굵게·검정(2026-10-12) */ .perf-table thead th { - font-size: 12px; font-weight: 500; color: var(--color-midtone-gray); text-align: right; + font-size: 12px; font-weight: 700; color: #000; text-align: center; background: var(--perf-soft); border-bottom: 1px solid var(--perf-line); position: sticky; top: 0; } -.perf-table thead th.perf-th-label { text-align: left; } +.perf-table thead th.perf-th-label { text-align: center; } .perf-td-label { text-align: left; font-weight: 500; } .perf-num { text-align: right; } .perf-zero { color: #c9c9c9; } @@ -128,6 +129,18 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; } /* 표시 기준 전환 — 한 칸에 3값, data-metric 으로 하나만 보인다 */ .perf .v { display: none; } +/* 수동 입력 칸 — 설정에서 켠 쇼핑몰의 날짜 칸. 파란 숫자 = 수동 입력값, 입력 중엔 숫자 대신 입력칸 */ +.perf-manual-mark { font-size: 11px; color: #1a56db; font-weight: 400; } +.perf-main td.is-manual-cell { cursor: text; position: relative; } +.perf-main td.is-manual-cell:hover { background: #eef3ff; box-shadow: inset 0 0 0 1px #c7d6fb; } +.perf-main td.is-manual-cell:focus { outline: 2px solid #1a56db; outline-offset: -2px; } +.perf-main td.is-manual .v-gross { color: #1a56db; font-weight: 600; } +.perf-main td.is-stale .v-commission, .perf-main td.is-stale .v-net { opacity: .4; } +.perf-main td.is-editing { padding: 2px 4px; } +.perf .perf-main td.is-editing .v { display: none; } +.perf-manual-input { width: 100%; min-width: 90px; box-sizing: border-box; padding: 3px 6px; border: 1px solid #1a56db; border-radius: 4px; + font: inherit; text-align: right; background: #fff; outline: none; } +.perf-manual-help { margin: 8px 2px 0; font-size: 12px; } .perf[data-metric="gross"] .v-gross, .perf[data-metric="commission"] .v-commission, .perf[data-metric="net"] .v-net { display: inline; } diff --git a/app/static/performance.js b/app/static/performance.js index d02bbf6..5da5bde 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -333,6 +333,89 @@ if (!td) return; openEvents(td.dataset.code, td.dataset.from, td.dataset.to); }); + + // ── 수동 입력(설정에서 켠 쇼핑몰) — 날짜 칸을 눌러 총매출 입력. Enter 저장 후 아래 칸 · Shift+Enter 위 칸 · Esc 취소. + // 비우고 저장하면 그날은 다시 API 값. 저장은 칸마다 차례로, 입력을 마치면(다른 칸으로 안 넘어가면) 새로고침해 + // 합계·수수료·그래프를 서버 계산으로 다시 그린다. + let manualDirty = false; + let manualChain = Promise.resolve(); + function manualCells(code) { + return Array.prototype.slice.call(root.querySelectorAll('td.is-manual-cell[data-manual-code="' + code + '"]')); + } + function digitsOf(td) { return td.dataset.manualValue || ""; } + function finishManual() { + setTimeout(function () { + if (root.querySelector(".perf-manual-input")) return; // 다른 칸으로 넘어감 + manualChain.then(function () { if (manualDirty) location.reload(); }); + }, 120); + } + function saveManual(td, text) { + const raw = String(text || "").replace(/[,\s원]/g, ""); + const was = digitsOf(td); + 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) + "/" + + 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 값)" : "눌러 총매출 직접 입력"; + const g = td.querySelector(".v-gross"); + if (g) g.innerHTML = won(res.amount); + td.classList.add("is-stale"); // 수수료·차감 매출은 새로고침 때 다시 계산 + manualDirty = true; + return true; + }); + manualChain = job.catch(function () {}); + return job; + } + 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 + " 총매출" }); + input.value = digitsOf(td); + const g = td.querySelector(".v-gross"); + input.placeholder = digitsOf(td) ? "" : (g ? g.textContent.trim().replace(/[–-]/, "") : "") || "총매출"; + td.classList.add("is-editing"); + td.appendChild(input); + input.focus(); + input.select(); + let done = false; + function close() { + if (done) return; + done = true; + input.remove(); + td.classList.remove("is-editing"); + } + function commit(step) { + if (done) return; + const val = input.value; + close(); + const cells = manualCells(td.dataset.manualCode); + const next = step ? cells[cells.indexOf(td) + step] : null; + if (next) editManual(next); + saveManual(td, val).catch(function (err) { + alertMsg("저장 실패(" + td.dataset.date + "): " + err.message); + }).then(finishManual); + } + input.addEventListener("keydown", function (e) { + if (e.isComposing) return; + if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); commit(e.shiftKey ? -1 : 1); } + else if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); commit(e.key === "ArrowUp" ? -1 : 1); } + else if (e.key === "Escape") { e.preventDefault(); close(); td.focus(); finishManual(); } + }); + input.addEventListener("blur", function () { commit(0); }); + } + root.addEventListener("click", function (e) { + const td = e.target.closest("td.is-manual-cell"); + if (td && !e.target.closest(".perf-manual-input")) editManual(td); + }); + root.addEventListener("keydown", function (e) { + const td = e.target.closest && e.target.closest("td.is-manual-cell"); + if (td && e.target === td && (e.key === "Enter" || e.key === "F2")) { e.preventDefault(); editManual(td); } + }); async function openEvents(code, from, to) { const name = (data.names || {})[code] || code; const title = name + " · " + (from === to ? from : from + " ~ " + to) + " 주문 내역"; diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index f0ce11c..c445944 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -125,6 +125,19 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g 설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다. +## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002) + +002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를 +카페24·네이버·쿠팡·토스·GS샵·11번가·오늘의집·G마켓·카카오·롯데ON 으로 바꾼다(기존 매출·인증정보 그대로, 다시 실행 가능). +미적용이면 수동 입력 토글·저장만 503 안내, 나머지 실적 화면은 그대로 동작한다. + +```bash +cd /opt/www/main +docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_002_$(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_002_manual_sales.sql +docker exec postgres-db psql -U postgres -d performance_db -c "SELECT code, sort_order, manual_input FROM perf_marketplaces ORDER BY sort_order;" +``` + ## 회의록 작업 등록 표 — 작업 칸 마이그레이션 (026) 026은 `goal_meeting_tasks.parent_task_id` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 025 뒤에 적용한다. 미적용이면 작업 칸을 고를 때만 503 안내. diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 4add24f..4c63ae8 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -200,6 +200,19 @@ ④ 취소분 뺀 값 ⑤ 로켓그로스 + 판매량 — 를 WING 판매분석의 같은 날 "매출(원)"·"판매량" 과 비교해 규칙을 확정한다(`candidates_title`). 로켓그로스만 거부돼도 판매자배송 결과는 보인다. +### 수동 입력(마이그레이션 002, 2026-10-12) + +- 설정 → 쇼핑몰 표 **수동 입력** 토글(관리자, `perf_marketplaces.manual_input`, 기본 꺼짐). 켜면 실적 일자별 표에서 그 쇼핑몰의 + **오늘까지 날짜 칸**을 눌러 총매출을 입력한다(제목 ✎, 수동 값은 파란 숫자). Enter·Tab·↓ 저장 후 아래 칸, Shift+Enter·↑ 위 칸, Esc 취소, + 칸을 벗어나면 저장. 입력을 마치면 새로고침해 합계·수수료·그래프를 서버 계산으로 다시 그린다. 입력은 모듈 권한자 누구나 + (`PUT /performance/api/manual-sales/{code}/{day}`, `{amount}` — 비우면 지움, 쉼표·"원" 허용, ±1조 이내, 앞날·꺼진 쇼핑몰은 400). +- 값은 `perf_manual_sales`(쇼핑몰 × 날짜 하나, `updated_by`). **넣은 날은 그 값이 API 수집값을 대신**하고(합산 아님), 넣지 않은 날은 + API 값. 대체는 `PerformanceDBStore.daily_amounts` 한 곳에서 해 실적 화면·회의록 머리 카드가 같은 숫자를 본다. 수수료는 그날 요율로 계산. + 토글을 끄면 값은 남지만 집계에 쓰지 않는다. 매출 업데이트(동기화)는 수동 값을 지우지 않는다. +- 002 미적용: 읽기는 수동 값 없음으로 조용히 동작, 토글·저장은 503 안내. +- 열 순서(002 + `registry.py`): 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON. +- 표 열 제목은 가운데·굵게·검정(`.perf-table thead th`). + ### 연동 단계 체크리스트(쇼핑몰마다) - 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인 diff --git a/scripts/sql/performance_db_002_manual_sales.sql b/scripts/sql/performance_db_002_manual_sales.sql new file mode 100644 index 0000000..836860d --- /dev/null +++ b/scripts/sql/performance_db_002_manual_sales.sql @@ -0,0 +1,44 @@ +-- ===================================================================== +-- performance_db 마이그레이션 002 — 쇼핑몰별 수동 입력 + 열 순서 +-- ===================================================================== +-- 멱등(idempotent). 기존 데이터 삭제 없음. 운영: /opt/www/main 에서 기존 performance_db 에 superuser 로 적용. +-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db \ +-- < scripts/sql/performance_db_002_manual_sales.sql +-- +-- 왜(2026-10-12 사용자 요청): +-- 1) 설정 → 쇼핑몰마다 "수동 입력" 사용 여부(perf_marketplaces.manual_input). 켜면 실적 일자별 표의 그 쇼핑몰 +-- 날짜 칸에 매출(총매출)을 직접 넣는다 — 넣은 날은 그 값이 API 수집값을 대신한다(비우면 다시 API 값). +-- 끄면 넣어 둔 값은 남지만 집계에 쓰지 않는다. +-- 2) 열 순서: 카페24 · 네이버 · 쿠팡 · 토스 · GS샵 · 11번가 · 오늘의집 · G마켓 · 카카오 · 롯데ON (sort_order 만 바꿈). +-- ===================================================================== +BEGIN; + +ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE; +COMMENT ON COLUMN perf_marketplaces.manual_input IS '수동 입력 사용 — 켜면 perf_manual_sales 값이 그날 API 수집값을 대신한다'; + +-- 수동 입력 매출 — 쇼핑몰 × 날짜 하나에 값 하나(원 단위 정수, 총매출). 수수료는 다른 매출처럼 요율로 계산. +CREATE TABLE IF NOT EXISTS perf_manual_sales ( + marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code), + sales_date DATE NOT NULL, + amount BIGINT NOT NULL, + updated_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (marketplace_code, sales_date) +); +CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date); +DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales; +CREATE TRIGGER trg_perf_manual_sales_updated + BEFORE UPDATE ON perf_manual_sales + FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at(); + +GRANT SELECT, INSERT, UPDATE, DELETE ON perf_manual_sales TO performance_app; + +-- 열 순서(설정·실적 표 공통) +UPDATE perf_marketplaces AS m SET sort_order = v.sort_order + FROM (VALUES ('cafe24', 10), ('naver', 20), ('coupang', 30), ('toss', 40), ('gsshop', 50), ('elevenst', 60), + ('ohouse', 70), ('gmarket', 80), ('kakao', 90), ('lotteon', 100)) AS v(code, sort_order) + WHERE m.code = v.code AND m.sort_order <> v.sort_order; + +COMMIT; +SELECT 'performance_db 002 manual sales ready' AS status; diff --git a/scripts/sql/performance_db_init.sql b/scripts/sql/performance_db_init.sql index 175ad01..fac50aa 100644 --- a/scripts/sql/performance_db_init.sql +++ b/scripts/sql/performance_db_init.sql @@ -62,9 +62,11 @@ CREATE TABLE IF NOT EXISTS perf_marketplaces ( enabled BOOLEAN NOT NULL DEFAULT TRUE, include_in_sales BOOLEAN NOT NULL DEFAULT TRUE, sort_order INTEGER NOT NULL DEFAULT 0, + manual_input BOOLEAN NOT NULL DEFAULT FALSE, -- 수동 입력 사용(002) — perf_manual_sales 값이 그날 API 값을 대신 created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now() ); +ALTER TABLE perf_marketplaces ADD COLUMN IF NOT EXISTS manual_input BOOLEAN NOT NULL DEFAULT FALSE; DROP TRIGGER IF EXISTS trg_perf_marketplaces_updated ON perf_marketplaces; CREATE TRIGGER trg_perf_marketplaces_updated BEFORE UPDATE ON perf_marketplaces @@ -74,13 +76,13 @@ INSERT INTO perf_marketplaces (code, name, sort_order) VALUES ('cafe24', '카페24', 10), ('naver', '네이버 스마트스토어', 20), ('coupang', '쿠팡', 30), - ('ohouse', '오늘의집', 40), - ('gmarket', 'G마켓', 50), - ('kakao', '카카오', 60), - ('gsshop', 'GS샵', 70), - ('elevenst', '11번가', 80), - ('lotteon', '롯데ON', 90), - ('toss', '토스쇼핑', 100) + ('toss', '토스쇼핑', 40), + ('gsshop', 'GS샵', 50), + ('elevenst', '11번가', 60), + ('ohouse', '오늘의집', 70), + ('gmarket', 'G마켓', 80), + ('kakao', '카카오', 90), + ('lotteon', '롯데ON', 100) ON CONFLICT (code) DO NOTHING; -- ════════════════════════════════════════════════════════════ @@ -208,13 +210,31 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_perf_sync_running ON perf_sync_runs (marketplace_code) WHERE status = 'running'; CREATE INDEX IF NOT EXISTS idx_perf_sync_runs_code ON perf_sync_runs (marketplace_code, started_at DESC); +-- ════════════════════════════════════════════════════════════ +-- 7) 수동 입력 매출(002) — 쇼핑몰 × 날짜 하나에 총매출 하나. 그 쇼핑몰 수동 입력이 켜져 있을 때만 집계에 쓴다. +-- ════════════════════════════════════════════════════════════ +CREATE TABLE IF NOT EXISTS perf_manual_sales ( + marketplace_code TEXT NOT NULL REFERENCES perf_marketplaces(code), + sales_date DATE NOT NULL, + amount BIGINT NOT NULL, + updated_by TEXT NOT NULL DEFAULT '', + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (marketplace_code, sales_date) +); +CREATE INDEX IF NOT EXISTS idx_perf_manual_sales_date ON perf_manual_sales (sales_date); +DROP TRIGGER IF EXISTS trg_perf_manual_sales_updated ON perf_manual_sales; +CREATE TRIGGER trg_perf_manual_sales_updated + BEFORE UPDATE ON perf_manual_sales + FOR EACH ROW EXECUTE FUNCTION perf_set_updated_at(); + -- ════════════════════════════════════════════════════════════ -- 권한 — 앱 계정은 DML 만 -- ════════════════════════════════════════════════════════════ GRANT USAGE ON SCHEMA public TO performance_app; GRANT SELECT, INSERT, UPDATE, DELETE ON perf_marketplaces, perf_commission_rates, perf_credentials, - perf_connection_status, perf_sales_events, perf_sync_runs + perf_connection_status, perf_sales_events, perf_sync_runs, perf_manual_sales TO performance_app; GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO performance_app; ALTER DEFAULT PRIVILEGES IN SCHEMA public diff --git a/tests/js/perf_manual.test.js b/tests/js/perf_manual.test.js new file mode 100644 index 0000000..6970553 --- /dev/null +++ b/tests/js/perf_manual.test.js @@ -0,0 +1,145 @@ +// 실적 — 수동 입력(static/performance.js) · 열 순서 · 설정 토글 — jsdom. +// python tests/js/render_performance.py && NODE_PATH= node tests/js/perf_manual.test.js +const fs = require("fs"), path = require("path"); +const { JSDOM } = require("jsdom"); +const OUT = path.join(__dirname, ".out"); +const JS = fs.readFileSync(path.join(__dirname, "..", "..", "app", "static", "performance.js"), "utf8"); +const fails = []; +function check(name, cond, extra) { + if (cond) console.log("PASS " + name); + else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); } +} +const settle = function () { return new Promise(function (r) { let i = 0; (function s() { if (i++ > 40) return r(); setImmediate(s); })(); }); }; +const wait = function (ms) { return new Promise(function (r) { setTimeout(r, ms); }); }; + +async function env(file) { + const html = fs.readFileSync(path.join(OUT, file), "utf8").replace(/