22 Commits

Author SHA1 Message Date
king 81b1204693 fix(project): 권한 우회·작업 혼선·저장 유실 등 16개 항목 수정 — 지금 권한 기준·읽기 전용 연결 작업·원자적 파일 댓글
권한(서버)
- 공통 권한 모듈 access.py: 모든 판단을 "지금" 권한으로 — 내 작업·수신함·알림·멘션·검색·상세·공유 링크·
  댓글·첨부·알림/메일 수신자에서 권한을 잃은 사람 제외(기록은 이력으로 보존)
- 소유자 변경·남을 소유자로 지정한 생성은 관리자만, 새 소유자는 권한 있는 등록 사용자
- 삭제는 생성자 규칙 + 지금 권한(멤버에서 빠진 생성자 거절), 댓글 수정·삭제도 지금 권한
- @태그는 볼 수 있는 사람만(mention_skipped), 태그 후보 all-users?task_id=, 새 담당자 권한 검사
- 연결(멀티호밍) 작업은 연결된 프로젝트 멤버에게 읽기 전용(task_link_scope), 볼 수 없는 연결 프로젝트 숨김

저장·동기화(화면)
- 작업 창 세대(taskGen)·블록 ctxSeq 로 늦은 A 응답이 B 를 덮지 않게(A→B, A→B→A, 이미지 업로드 중 전환)
- 자동 저장 성공/실패 반환, 실패 칸 재시도, 닫기·전환 전 저장 확인(버리기/계속 편집), 미저장 이탈 경고
- 실시간 동기화 observed/applied 분리·실패 재시도·겹침 방지, snapshot?scope=all 로 전체 범위 반영·권한 회수 안내
- 한국시간 기준 오늘(kstTodayIso), 한글 조합 중 Enter 는 제출하지 않음, 댓글 연타·재전송 중복 방지(client_token)

기타
- 파일 댓글은 본문+파일 한 트랜잭션(POST /comments/files), 실패 파일 표시·유지, 작업 창 댓글에 첨부 표시
- 날짜 범위 검증(부분 수정은 최종 상태), 완료 섹션에 바로 만든 작업 완료 처리·알림
- 마감 알림 발송 기록+수신함 알림 원자적(실패 시 재시도), 권한 없는 수신자 제외
- 테스트: tests/test_project_module.py(로컬 PostgreSQL 11개), tests/js/project_ui.test.js(jsdom 51개)
- 문서(PROJECT_MODULE 6-10·도움말·CLAUDE.md), project.js/css 캐시 버전 20260930g, 새 마이그레이션·환경변수 없음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 16:46:11 +09:00
king ae2e3eb943 Merge branch 'feat/performance' into feat/project — 매출 업데이트 취소 2026-09-30 15:06:47 +09:00
king da63b93302 feat(performance): 매출 업데이트 취소 버튼
- 진행 창 [업데이트 취소](시작한 사람·관리자) → POST /api/sync/jobs/{id}/cancel
- 어댑터가 API 호출 직전마다 ctx.progress.check() — 취소면 Cancelled 로 멈추고 저장하지 않음(기존 매출 그대로),
  차례가 안 온 쇼핑몰은 취소됨으로 건너뜀, 이미 끝난 쇼핑몰 결과는 유지
- 취소 실행은 perf_sync_runs failed + 업데이트 취소, 연결 상태는 바꾸지 않음
- 테스트 1개 추가(30개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:06:25 +09:00
king a2d2382d71 Merge branch 'feat/performance' into feat/project — GS샵 매출 = 협력사 지급액 2026-09-30 15:01:42 +09:00
king 8b3e6dffc5 fix(performance): GS샵 매출 = supGiveAmt(협력사 지급액) — 협력사 포털 주문 통계 금액과 같은 항목
- 9월 실데이터: 6호세트 포털 176,715 ÷ 9 = 19,635 = API supGiveAmt(판매가 23,100·고객 결제 20,330),
  7호세트 45,900 × 85%, 주부체험 9,900 × 90% — 상품마다 GS 수수료율이 달라 판매가로는 못 맞춤
- 9/1~9/29 지급액 4,972,689 vs 포털 순주문 4,823,074(주문일↔매출인식일 차이)
- 이미 GS 수수료를 뺀 금액이라 GS샵 수수료율은 0% 로 둔다(문서·어댑터 설명)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:01:27 +09:00
king 898dc1153c Merge branch 'feat/performance' into feat/project — GS샵 매출 수집 2026-09-30 14:53:29 +09:00
king b765fb8fb8 feat(performance): GS샵 매출 수집 — 매출 내역 custChrAmt(할인 후 고객 결제금액), 매출인식일 기준
- 9/3 실데이터로 항목 확인: salePrice − dcTotAmt = custChrAmt, supGiveAmt = 협력사 지급액
- 매출 내역 한 줄 = 사건, SALE 이 아닌 줄은 RETURN 음수, 배송비 제외, replace_range
- GS API 에는 주문일 기준 조회가 없어 포털 주문 통계(총주문금액)와 날짜 기준이 다름 — 문서에 기록
- 원본 데이터 확인에 날짜별 현재 규칙 매출(열 이름은 쇼핑몰별 day_cols)
- 테스트 1개 추가(29개 통과), performance.js 캐시 버전

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:53:13 +09:00
king 7c283312b4 Merge branch 'feat/performance' into feat/project — GS샵 운영 KEY 변형 2026-09-30 14:36:51 +09:00
king f4fadec0a4 fix(performance): GS샵 운영 KEY — 16진수 키 변형(글자 그대로·16진수 풀기·앞 32자)도 시도
- 포털 운영 KEY 가 16진수 글자라 키를 바이트로 쓰는 법을 모드와 함께 차례로 시도, 통과한 조합 기억
- 입력칸·안내 문구를 "운영 KEY"로(개발 KEY 아님), 연결 성공 문구에 통과한 방식 표시

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:36:36 +09:00
king 74f59c0a94 Merge branch 'feat/performance' into feat/project — GS샵 연결·원본 확인 2026-09-30 14:28:04 +09:00
king e56c5685ca feat(performance): GS샵 연결 테스트·원본 데이터 확인 — 제휴 API AES256 토큰
- 인증: 헤더 supCd + token = base64(AES256(yyyyMMddHHmmss + 협력사코드)), 암호화 모드는 문서에 없어
  CBC(IV=키 앞 16) → ECB → CBC(IV=0) 순서로 시도하고 통과한 모드 기억, HTTP 200 + result=fail 401 도 인증 실패로
- 운영 주소 withgs-api.gsshop.com, 매출 내역(매출인식일, 10일씩·쪽 넘김)·배송비 내역
- 설정 "쇼핑몰 원본 데이터 확인"에 GS샵 — 응답 항목 이름이 문서에 없어 실데이터로 매출 규칙 확정 예정
  (그 전까지 매출 수집은 연동 준비 중)
- 입력칸 라벨: 협력사코드(supCd)·AES256 암복호화 키(저장된 값 그대로 사용)
- 테스트 1개 추가(28개 통과), 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:27:49 +09:00
king 67cd73b963 Merge branch 'feat/performance' into feat/project — 매출 업데이트 진행 창 2026-09-30 13:57:11 +09:00
king 3203ff87a4 feat(performance): 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대
- POST /api/sync background=true 로 수집을 백그라운드 스레드에서 돌리고 작업 번호를 바로 돌려줌,
  GET /api/sync/jobs/{id}·/api/sync/current 로 진행 상황 조회(jobs.py, 메모리 보관)
- 어댑터 진행 알림(ctx.progress plan/step/add): 네이버 = 일, 11번가·카페24 = 조회 구간, 받은 자료 건수
- 창: 쇼핑몰마다 막대(대기·수집 중 n/전체·저장 중·완료 n건·실패·건너뜀·경과), 전체 막대(평균),
  수집 없는/인증정보 없는 쇼핑몰은 건너뜀 한 줄, 창을 닫아도 서버에서 계속
- [매출 업데이트]·[과거 매출 가져오기] 모두 진행 창 사용, 이미 진행 중이면 그 진행 상황을 보여 줌
- 테스트 1개 추가(27개 통과), performance.js/css 캐시 버전, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:56:57 +09:00
king e398e9d906 Merge branch 'feat/performance' into feat/project — 네이버 매출 = 판매금액(총) 2026-09-30 13:47:06 +09:00
king 077c92fa32 fix(performance): 네이버 매출 = 판매분석 "판매금액(총)" — 결제 뒤 취소·반품 포함, 배송비 제외
- 9/1 판매분석 매출 4,455,600원(판매금액(총)): 할인 뒤 금액, 배송비 별도, 환불은 환불일에 따로 빠짐
- 처음 규칙(취소·반품 빼고 배송비 더함)은 4,245,300원으로 달랐음
- 입금대기·미입금 취소만 제외, 결제 뒤 취소·반품도 결제일 매출에 포함
- 원본 데이터 확인 표에 결제 뒤 취소·반품분·배송비(참고) 열 추가
- performance.js 캐시 버전 20260930x, 테스트·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:46:57 +09:00
king e845f47043 Merge branch 'feat/performance' into feat/project — 네이버 스마트스토어 매출 수집 2026-09-30 13:34:03 +09:00
king a5f90a0343 feat(performance): 네이버 스마트스토어 매출 수집 — 커머스API 토큰·결제일 기준 주문 조회
- 인증: bcrypt 전자서명(client_secret_sign) → OAuth2 client_credentials 토큰, 암호화 저장·만료 5분 전 재발급,
  401 이면 한 번 새로 받아 재호출, 연결 테스트는 항상 새 토큰
- 수집: 조건형 상품 주문 상세 조회(rangeType=PAYED_DATETIME) 하루씩·페이지, 호출 간격·429 재시도
- 1차 매출 규칙: 주문 단위, 결제일, totalPaymentAmount 합 + 배송비(한 번, 배송비 할인 뺌),
  취소·반품 완료·미입금 취소 제외, replace_range
- 설정 화면 "쇼핑몰 원본 데이터 확인"을 네이버·11번가 공용으로 — 네이버는 항목·상태별 합계와
  날짜별 현재 규칙 매출(개인정보는 값 숨김)
- requirements: bcrypt, 테스트 3개 추가(26개 통과), 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:33:53 +09:00
king 21019ac5f1 style(project): 연간 목표 — 관리자 도구 버튼 33px → 30px
- project.js/css 캐시 버전 20260930f

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:00:43 +09:00
king 7a9f55c804 style(project): 연간 목표 — 관리자 도구 막대 1.5배 크기, 파스텔 주황 배경
- 도구 버튼 22px → 33px(글자·아이콘도 1.5배)
- 막대 배경 #ffe3c7, 버튼 올림 #ffc98f
- project.js/css 캐시 버전 20260930e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:10:41 +09:00
king ac2615805b fix(project): 연간 목표 — 왼쪽 이름 세로 가운데 정렬
- 구분·항목 이름 칸 vertical-align: middle
- 관리자 도구(✎ 색 ↑ ↓ + ×)는 칸 아래에 떠 있는 막대로 — 숨은 도구가 자리를 차지해 이름이 위로 치우치던 문제
- project.js/css 캐시 버전 20260930d

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 12:04:46 +09:00
king 220fb6e7d1 feat(project): 연간 목표 — 연간 열 90px, 머리·이름 가운데 정렬, 이름 칸 너비 조절·기억
- 연간 열 너비 90px 고정
- 맨 위 머리 줄과 왼쪽 이름 두 칸(구분·항목) 가운데 정렬
- 이름 두 칸은 머리 칸 오른쪽 끝을 끌어 너비 조절(48~320px, 더블클릭 = 기본 72px),
  브라우저에 기억(localStorage pj_goal_col_w)
- project.js/css 캐시 버전 20260930c

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:54:55 +09:00
king 7de93e78d7 fix(project): 연간 목표 — 월 칸 너비 85px, 영역 색에 색 없음 + 연한 16색
- 표 칸 너비를 여백 포함(border-box)으로 — 150px 이 padding 만큼 171px 로 늘던 문제, 월 칸 85px
- 좁아진 칸에 맞춰 숫자·글 칸 안쪽 여백 6px
- 색 바꾸기 팝업: 맨 위 색 없음(흰 배경) + 연한 16색(8칸×2줄, 기존 8색 포함)
- project.js/css 캐시 버전 20260930b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 11:32:25 +09:00
33 changed files with 4464 additions and 432 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1상자=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
- 카페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색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`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` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 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/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·프로젝트 색상(32색 — 아사나 16색 + 진한 16색)·아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011)·작업(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed, 섹션 기본 담당자 `default_assignee_email` — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정, 마이그레이션 009)·멤버 배정(`project_members`)·활동이력(`project_activity`). 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. 좌측 사이드바에 수신함·내 작업(접이식) 메뉴. 설명란은 주소 붙여넣기 시 자동 링크, 설명란·댓글에서 @로 멤버를 태그하면 (`task_mentions`, 마이그레이션 006) 수신함에 그 작업이 쌓인다. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성은 `project` 권한자 누구나(만든 사람이 owner), 삭제는 만든 사람만(슈퍼관리자 예외), 사용자 배정은 `is_admin` 만. 배정 멤버(또는 owner/admin)만 그 프로젝트를 조회(화면·API 모두, 비멤버 403)하고 서브프로젝트/작업/단계 CRUD — URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증. 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백). 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터). 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만. 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, 관리자만 보기·복구(`/project/trash`). 권한은 **지금 기준 공통 모듈 `access.py`**(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음), 소유자 변경은 관리자만, 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(docs/PROJECT_MODULE.md 6-10). 연간 목표(마이그레이션 013, `goal_*` 테이블) — 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}` 에 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글, 조회는 전원·입력은 `is_admin` 만. 마감 알림(`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` 비동기). 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성). 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503), 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외), 댓글 `@아이디` 는 아이콘+이름 칩. 수신함 "확인"은 페이지 이동 없이 오른쪽 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`
+28
View File
@@ -32,6 +32,7 @@ STATUS_LABELS: dict[str, str] = {
"not_implemented": "연동 준비 중",
"unknown": "확인 전",
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
}
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
@@ -68,6 +69,11 @@ class NotImplementedYet(AdapterError):
status = "not_implemented"
class Cancelled(AdapterError):
"""사용자가 매출 업데이트를 취소함 — 어댑터가 ctx.progress.check() 에서 받는다. 연결 오류가 아니다."""
status = "cancelled"
# ════════════════════════════════════════════════════════════
# 설정 입력칸 · 공통 매출 사건
# ════════════════════════════════════════════════════════════
@@ -130,12 +136,34 @@ class CredentialAccessor(Protocol):
def has(self, key: str) -> bool: ...
class Progress:
"""수집 진행 알림(매출 업데이트 창의 진행 막대용). 기본은 아무것도 하지 않는다 — sync 가 진행 상황을 모으는
객체(jobs.ShopProgress)로 바꿔 넣는다.
어댑터: 조회를 시작하기 전에 plan(전체 단계 수, 단위) → 단계 하나(하루·조회 구간)를 끝낼 때마다
step(items=그 단계에서 받은 건수). 하다가 할 일이 늘면 add(늘어난 단계 수).
API 를 부르기 직전마다 check() — 사용자가 [업데이트 취소]를 눌렀으면 Cancelled 를 던져 거기서 멈춘다."""
def plan(self, total: int, unit: str = "단계") -> None:
return None
def add(self, n: int) -> None:
return None
def step(self, n: int = 1, *, items: int = 0) -> None:
return None
def check(self) -> None:
return None
@dataclass
class AdapterContext:
code: str
credentials: CredentialAccessor
app_state: Any = None # 공통 연동 계층 재사용(예: 카페24 토큰 저장소)
timeout_sec: float = 20.0
progress: Progress = field(default_factory=Progress)
# ════════════════════════════════════════════════════════════
+22 -6
View File
@@ -291,6 +291,7 @@ class Cafe24Adapter(MarketplaceAdapter):
if offset > MAX_OFFSET:
raise ApiError(f"카페24 조회 건수가 너무 많습니다({params.get('start_date')}~{params.get('end_date')}). "
"기간을 줄여 다시 시도하세요.")
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
rows = self._get(ctx, path, {**params, "limit": limit, "offset": offset}).get(key) or []
yield from rows
if len(rows) < limit:
@@ -299,17 +300,25 @@ class Cafe24Adapter(MarketplaceAdapter):
def paid_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
for s, e in _chunks(start, end):
yield from self._paged(ctx, "/admin/orders", "orders",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": "pay_date", "embed": "items"}, ORDER_LIMIT)
n = 0
for o in self._paged(ctx, "/admin/orders", "orders",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": "pay_date", "embed": "items"}, ORDER_LIMIT):
n += 1
yield o
ctx.progress.step(items=n)
def refunds(self, ctx: AdapterContext, start: date, end: date,
date_type: str = "refund_date") -> Iterable[dict[str, Any]]:
"""환불 목록. date_type: refund_date(환불완료일, 기본) / accepted_refund_date(환불접수일)."""
for s, e in _chunks(start, end):
yield from self._paged(ctx, "/admin/refunds", "refunds",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": date_type}, REFUND_LIMIT)
n = 0
for r in self._paged(ctx, "/admin/refunds", "refunds",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": date_type}, REFUND_LIMIT):
n += 1
yield r
ctx.progress.step(items=n)
def claim_items(self, ctx: AdapterContext, day: date) -> dict[str, Any]:
"""그날 취소완료·반품완료·교환완료된 주문의 클레임 품목(대조 전용). 환불 API 에 안 잡히는 건
@@ -372,9 +381,11 @@ class Cafe24Adapter(MarketplaceAdapter):
found: dict[str, dict[str, Any]] = {}
for date_type in NO_RECORD_DATE_TYPES:
for s, e in _chunks(start, end):
scanned = 0
for o in self._paged(ctx, "/admin/orders", "orders",
{"start_date": s.isoformat(), "end_date": e.isoformat(),
"date_type": date_type, "embed": "items"}, ORDER_LIMIT):
scanned += 1
if NO_RECORD_CHANNEL not in (_key(o.get("market_id")), _key(o.get("order_place_id"))):
continue
oid = str(o.get("order_id") or "")
@@ -416,10 +427,12 @@ class Cafe24Adapter(MarketplaceAdapter):
"item_payment_amount": _won(i.get("payment_amount")),
"coupon": _won(i.get("coupon_discount_price")),
}
ctx.progress.step(items=scanned)
if not found:
return []
lo = start - timedelta(days=REFUND_LOOKAROUND_DAYS)
hi = max(end, min(end + timedelta(days=REFUND_LOOKAROUND_DAYS), today_kst()))
ctx.progress.add(2 * len(list(_chunks(lo, hi)))) # 환불 목록 대조(완료일·접수일) — 찾은 게 있을 때만
refunded = {str(r.get("order_id") or "") for dt in ("refund_date", "accepted_refund_date")
for r in self.refunds(ctx, lo, hi, dt)}
return [c for c in found.values() if c["order_id"] not in refunded]
@@ -445,6 +458,9 @@ class Cafe24Adapter(MarketplaceAdapter):
# ── 수집(어댑터 공통 흐름) ──────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
# 진행 막대: 60일 구간마다 결제 주문 1 + 환불 1 + 환불 없는 취소·반품(취소일·반품완료일) 2
c = len(list(_chunks(start, end)))
ctx.progress.plan(c * (2 + len(NO_RECORD_DATE_TYPES)), "구간")
yield from self.paid_orders(ctx, start, end)
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
+11 -2
View File
@@ -160,6 +160,10 @@ def _day(value: Any) -> date | None:
return None
def _n_chunks(lo: date, hi: date) -> int:
return max(0, ((hi - lo).days + PROBE_CHUNK_DAYS) // PROBE_CHUNK_DAYS)
class ElevenstAdapter(MarketplaceAdapter):
code = "elevenst"
name = "11번가"
@@ -183,7 +187,9 @@ class ElevenstAdapter(MarketplaceAdapter):
while s <= hi:
e = min(hi, s + timedelta(days=PROBE_CHUNK_DAYS - 1))
ds, de = s.strftime("%Y%m%d"), e.strftime("%Y%m%d")
yield from xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
rows = xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
ctx.progress.step(items=len(rows))
yield from rows
s = e + timedelta(days=1)
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
@@ -202,6 +208,9 @@ class ElevenstAdapter(MarketplaceAdapter):
"discount": 0, "ship": 0, "names": [], "opt": "", "raw": {}})
settle_hi = max(end, min(end + timedelta(days=SETTLE_LOOKAHEAD_DAYS), today))
hi = max(end, min(end + timedelta(days=LOOKAHEAD_DAYS), today))
# 진행 막대: 7일 구간마다 한 번 — 정산 내역 + 주문 상태 목록 4개
ctx.progress.plan(_n_chunks(start, settle_hi) + len(ORDER_PATHS) * _n_chunks(start, hi), "구간")
for r in self._pages(ctx, SETTLEMENT_PATH, start, settle_hi):
oid, day = str(r.get("ordNo") or ""), _day(r.get("ordStlEndDt"))
if not oid or day is None or not (start <= day <= end):
@@ -218,7 +227,6 @@ class ElevenstAdapter(MarketplaceAdapter):
o["raw"]["stlDy"] = r.get("stlDy")
settled = set(orders)
hi = max(end, min(end + timedelta(days=LOOKAHEAD_DAYS), today))
seen: set[str] = set()
for tmpl in ORDER_PATHS:
status = ORDER_STATUS[tmpl.split("/")[3]]
@@ -262,6 +270,7 @@ class ElevenstAdapter(MarketplaceAdapter):
def _get(self, ctx: AdapterContext, path: str) -> bytes:
import httpx # 지연 import
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
headers = {"openapikey": ctx.credentials.get("api_key").strip(), "Accept": "application/xml"}
try:
res = httpx.get(f"{HOST}{path}", headers=headers, timeout=ctx.timeout_sec)
+293 -6
View File
@@ -1,21 +1,308 @@
"""GS샵 — 협력사 API.
"""GS샵 — GSSHOP 제휴 API(협력사 API V3, partners.gsshop.com → 제휴 API → 개발가이드).
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
인증(개발가이드 2026-09-30 확인): 요청 헤더
supCd = 협력사코드
token = AES256( Sysdate("yyyyMMddHHmmss") + 협력사코드 ) 예: "20181017174913" + "1036018"
AES256 암복호화 키는 partners.gsshop.com/api/apiMain 에 로그인하면 보인다.
암호화 모드(CBC/ECB, IV)와 키를 바이트로 쓰는 법은 문서에 없다 → 키 변형(글자 그대로 / 16진수 풀기 / 앞 32자,
key_variants) × 모드(CBC·IV=키 앞 16바이트 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억한다. 출력은 base64.
(포털 "운영 KEY" 는 16진수처럼 보이는 글자 — 32자면 글자 그대로 AES256, 64자면 16진수로 풀어 32바이트일 수 있다.)
token 이 틀리면 HTTP 200 + {"result":"fail","message":"키 인증 중 오류…","code":"401 UNAUTHORIZED"}.
주소: 운영 https://withgs-api.gsshop.com (개발가이드의 예시 주소 atwithgs-api 는 테스트용 — 두 곳 모두 응답 확인).
매출(Settlement API 1.0): GET /api/v2/settlement/out/sales/period?supCode=&fromDate=&toDate=&pageIdx=&rowsPerPage=
— 매출인식일(YYYYMMDD) 기준, 한 번에 10일까지, 쪽당 최대 1만 건. 응답 {data:[…], hasMorePage, totalCount, …}.
배송비는 /api/v2/settlement/out/sales/shippingFee/period(같은 조건).
응답 줄 항목(2026-09-30 실데이터 9/3 — 개발가이드 예시에는 없음): saleAwareDt(매출인식일), ordNo·ordItemNo·orgOrdNo,
ordType(SALE …), prdCd·prdNm, chrQty(수량), salePrice(할인 전 판매가 — 줄 합계), dcTotAmt(할인 합계),
custChrAmt(고객 결제금액 = salePrice − dcTotAmt), supGiveAmt(협력사 지급액, 수수료 차감), sup*DcAmt(협력사 부담 할인).
9/3: salePrice 211,100 − dcTotAmt 19,528 = custChrAmt 191,572, supGiveAmt 179,435, 배송비 내역 7,000.
**주문일 기준 조회 API 는 없다**(V3 문서에 주문 조회 없음) — 협력사 포털 주문 통계(총주문금액, 주문일)와는 기준이 달라
날짜별로 똑같이 맞출 수 없다.
매출 규칙 — 협력사 포털 주문 통계의 금액 = **supGiveAmt(협력사 지급액)**(2026-09-30, 9월 실데이터로 확인):
미라미라클 6호세트 포털 176,715 ÷ 9 = 19,635 = API 줄 supGiveAmt 19,635(판매가 23,100·고객 결제 20,330),
7호세트 39,015 = 45,900 × 85%, 주부체험 세트 8,910 = 9,900 × 90% — 상품마다 GS 수수료율이 달라 판매가 × 요율로는 못 맞춘다.
9/1~9/29: 지급액 4,972,689 / 포털 순주문 4,823,074(차이는 주문일 ↔ 매출인식일 기준 차이·취소분).
- 매출 내역 한 줄 = 사건 하나(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일.
- 금액 = supGiveAmt, 배송비 제외. 이미 GS 수수료를 뺀 금액이라 **실적 설정의 GS샵 수수료율은 0%** 로 둔다.
ordType 이 SALE 이 아니면(취소·반품 등) 음수로(RETURN). 할인 = dcTotAmt. 기간을 통째로 다시 받는다(replace_range).
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import base64
from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .elevenst import field_summary
HOST = "https://withgs-api.gsshop.com"
SALES_PATH = "/api/v2/settlement/out/sales/period"
SHIPPING_PATH = "/api/v2/settlement/out/sales/shippingFee/period"
DAILY_SALES_PATH = "/api/v2/settlement/out/sales"
CHUNK_DAYS = 10 # 기간 조회는 시작일부터 10일 이내
ROWS_PER_PAGE = 10000
MAX_PAGES = 50
PROBE_MAX_DAYS = 31
TOKEN_MODES = ("cbc-keyiv", "ecb", "cbc-zeroiv")
MODE_LABEL = {"cbc-keyiv": "AES/CBC(IV=키 앞 16바이트)", "ecb": "AES/ECB", "cbc-zeroiv": "AES/CBC(IV=0)"}
KEY_LABEL = {"text": "키 글자 그대로", "hex": "키 16진수 풀기", "first32": "키 앞 32자"}
def key_variants(aes_key: str) -> list[tuple[str, bytes]]:
"""AES 키로 쓸 수 있는 바이트 후보(시도 순서). 하나도 없으면 길이 오류."""
raw = aes_key.strip().encode("utf-8")
out: list[tuple[str, bytes]] = []
if len(raw) in (16, 24, 32):
out.append(("text", raw))
txt = aes_key.strip()
if len(txt) in (32, 48, 64) and all(c in "0123456789abcdefABCDEF" for c in txt):
out.append(("hex", bytes.fromhex(txt)))
if len(raw) > 32:
out.append(("first32", raw[:32]))
if not out:
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(raw)}자). 제휴 API 메인 화면의 운영 KEY 를 "
"[복사] 버튼으로 복사해 그대로 붙여 넣으세요.")
return out
def make_token(aes_key: str | bytes, sup_cd: str, now: datetime, mode: str) -> str:
"""token = base64(AES(yyyyMMddHHmmss + 협력사코드)), PKCS7(=PKCS5) 패딩. aes_key 가 글자면 그대로 바이트로."""
from cryptography.hazmat.primitives import padding # 지연 import
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = aes_key if isinstance(aes_key, bytes) else aes_key.encode("utf-8")
if len(key) not in (16, 24, 32):
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(key)}바이트 — 16·24·32 중 하나여야 함). "
"제휴 API 메인 화면의 키를 그대로 붙여 넣으세요.")
plain = (now.strftime("%Y%m%d%H%M%S") + sup_cd).encode("utf-8")
padder = padding.PKCS7(128).padder()
data = padder.update(plain) + padder.finalize()
if mode == "ecb":
cipher = Cipher(algorithms.AES(key), modes.ECB())
elif mode == "cbc-zeroiv":
cipher = Cipher(algorithms.AES(key), modes.CBC(b"\0" * 16))
else:
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
enc = cipher.encryptor()
return base64.b64encode(enc.update(data) + enc.finalize()).decode("ascii")
def _rows(body: dict[str, Any]) -> list[dict[str, Any]]:
data = body.get("data")
return [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
def _strs(row: dict[str, Any]) -> dict[str, str]:
"""원본 확인용 — 값은 모두 글자로(중첩은 JSON 글자 그대로 짧게)."""
return {str(k): ("" if v is None else str(v)) for k, v in row.items()}
EVENT_PREFIX = "gs:"
def _won(value: Any) -> int:
try:
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
except ValueError:
return 0
def _yyyymmdd(value: Any) -> date | None:
s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8]
if len(s) < 8:
return None
try:
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
except ValueError:
return None
class GsshopAdapter(MarketplaceAdapter):
code = "gsshop"
name = "GS샵"
auth_type = "api_key"
note = "입력 항목은 연동 단계에서 GS샵 협력사 API 문서로 확정합니다."
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://partners.gsshop.com/api/apiDevGuide"
note = ("GS SHOP 협력사 포털(partners.gsshop.com) → 제휴 API 메인 화면의 협력사코드와 "
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
def __init__(self) -> None:
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
def credential_fields(self) -> list[CredentialField]:
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
return [
CredentialField("vendor_code", "협력사 코드"),
CredentialField("api_key", "API Key", secret=True),
CredentialField("vendor_code", "협력사코드(supCd)", help="예: 1036018"),
CredentialField("api_key", "운영 KEY(AES256 암복호화 키)", secret=True,
help="제휴 API 메인 화면의 운영 KEY — [복사] 버튼으로 복사해 붙여 넣기"),
]
# ── 호출 ──────────────────────────────────────────────
def _creds(self, ctx: AdapterContext) -> tuple[str, str]:
sup = ctx.credentials.get("vendor_code").strip()
key = ctx.credentials.get("api_key").strip()
if not sup or not key:
raise NotConfigured("협력사코드와 AES256 키를 입력하세요.")
return sup, key
def _call(self, ctx: AdapterContext, path: str, params: dict[str, Any], how: tuple[str, str]) -> dict[str, Any]:
import httpx # 지연 import
from app.timezone import now_kst # noqa: WPS433
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
sup, key = self._creds(ctx)
key_bytes = dict(key_variants(key))[how[0]]
headers = {"supCd": sup, "token": make_token(key_bytes, sup, now_kst(), how[1]), "Accept": "application/json"}
try:
res = httpx.get(f"{HOST}{path}", params={"supCode": sup, **params}, headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"GS샵 API 연결 실패: {type(exc).__name__}") from None
try:
body = res.json()
except ValueError:
raise ApiError(f"GS샵이 예상하지 못한 응답을 돌려줬습니다({res.status_code}): {res.text[:150].strip()}") from None
if not isinstance(body, dict):
body = {"data": body}
code = str(body.get("code") or "")
msg = str(body.get("message") or "")[:200]
if res.status_code in (401, 403) or (str(body.get("result")) == "fail" and ("401" in code or "403" in code)):
raise AuthFailed(f"GS샵 인증 거부({code or res.status_code}): {msg}")
if res.status_code >= 400 or str(body.get("result")) == "fail":
raise ApiError(f"GS샵 API 오류({code or res.status_code}): {msg or res.text[:150].strip()}")
return body
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
sup, key = self._creds(ctx)
known = self._mode.get(sup)
if known:
return self._call(ctx, path, params, known)
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
last: AuthFailed | None = None
for how in tries:
try:
body = self._call(ctx, path, params, how)
except AuthFailed as exc:
last = exc
continue
self._mode[sup] = how
return body
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
def _pages(self, ctx: AdapterContext, path: str, lo: date, hi: date) -> list[dict[str, Any]]:
"""[lo, hi] 를 10일씩 나눠 쪽을 넘겨 모두 받는다."""
out: list[dict[str, Any]] = []
s = lo
while s <= hi:
e = min(hi, s + timedelta(days=CHUNK_DAYS - 1))
for page in range(1, MAX_PAGES + 1):
body = self._get(ctx, path, {"fromDate": s.strftime("%Y%m%d"), "toDate": e.strftime("%Y%m%d"),
"pageIdx": page, "rowsPerPage": ROWS_PER_PAGE})
rows = _rows(body)
out.extend(rows)
if not body.get("hasMorePage") or not rows:
break
ctx.progress.step(items=len(out))
s = e + timedelta(days=1)
return out
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""매출인식일이 [start, end] 인 매출 내역 줄. 같은 사건 ID 가 두 번 나오면 뒤에 번호를 붙여 둘 다 남긴다."""
ctx.progress.plan(max(1, ((end - start).days + CHUNK_DAYS) // CHUNK_DAYS), "구간")
seen: dict[str, int] = {}
for r in self._pages(ctx, SALES_PATH, start, end):
day = _yyyymmdd(r.get("saleAwareDt"))
if day is None or not (start <= day <= end):
continue
base = f"{r.get('ordNo')}-{r.get('ordItemNo')}-{r.get('ordType') or 'SALE'}-{day.strftime('%Y%m%d')}"
n = seen.get(base, 0)
seen[base] = n + 1
yield {**r, "_day": day, "_id": base if n == 0 else f"{base}-{n + 1}"}
def normalize_order(self, r: dict[str, Any]) -> list[SaleEvent]:
"""매출 내역 한 줄 → SALE(ordType=SALE) 또는 RETURN(그 밖, 음수). 금액 = supGiveAmt(협력사 지급액 — 포털 주문 통계 금액)."""
oid, day = str(r.get("ordNo") or ""), r.get("_day")
if not oid or day is None:
return []
kind = str(r.get("ordType") or "SALE").upper()
amount = abs(_won(r.get("supGiveAmt")))
is_sale = kind == "SALE"
return [SaleEvent(
event_type="SALE" if is_sale else "RETURN", external_event_id=f"{EVENT_PREFIX}{r['_id']}",
external_order_id=oid, external_line_id=str(r.get("ordItemNo") or ""), event_date=day,
payment_date=day if is_sale else None, amount=amount if is_sale else -amount,
product_name=str(r.get("prdNm") or "")[:200], quantity=abs(_won(r.get("chrQty"))),
discount_amount=abs(_won(r.get("dcTotAmt"))), order_status=kind[:50],
raw={"salePrice": _won(r.get("salePrice")), "custChrAmt": _won(r.get("custChrAmt")),
"orgOrdNo": str(r.get("orgOrdNo") or ""), "prdCd": str(r.get("prdCd") or "")},
)]
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
sup, _ = self._creds(ctx)
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
day = today_kst() - timedelta(days=1)
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
total = body.get("totalCount")
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
f"토큰 {self._how_label(sup)}).")
def _how_label(self, sup: str) -> str:
v, m = self._mode.get(sup, ("", ""))
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""매출 내역·배송비 내역을 기간(최대 31일, 10일씩)으로 실제 불러 항목별 합계를 돌려준다(저장 안 함).
응답 항목 이름이 개발가이드에 없어 협력사 포털 매출 화면과 맞는 항목을 실데이터로 확정하는 용도."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
probes = []
got: dict[str, list[dict[str, Any]]] = {}
for key, label, path in (("sales", "매출 내역(매출인식일 기준)", SALES_PATH),
("shipping", "배송비 내역(매출인식일 기준)", SHIPPING_PATH)):
row: dict[str, Any] = {"key": key, "label": label, "path": path}
try:
rows = self._pages(ctx, path, day, to)
except AdapterError as exc:
probes.append({**row, "ok": False, "error": exc.message[:300]})
continue
got[key] = rows
probes.append({**row, "ok": True, "count": len(rows), "fields": field_summary([_strs(r) for r in rows])})
# 날짜별 현재 규칙 매출(supGiveAmt, SALE 아닌 줄은 음수) — 협력사 포털 매출 화면과 나란히 비교
days = []
d = day
while d <= to:
sales = [r for r in got.get("sales", []) if _yyyymmdd(r.get("saleAwareDt")) == d]
ret = [r for r in sales if str(r.get("ordType") or "SALE").upper() != "SALE"]
amt = sum(abs(_won(r.get("supGiveAmt"))) for r in sales if r not in ret) - sum(abs(_won(r.get("supGiveAmt"))) for r in ret)
days.append({"date": d.isoformat(), "orders": len({str(r.get("ordNo")) for r in sales if r not in ret}),
"amount": amt, "claimed": sum(abs(_won(r.get("supGiveAmt"))) for r in ret),
"ship": sum(_won(r.get("salePrice")) for r in got.get("shipping", [])
if _yyyymmdd(r.get("saleAwareDt")) == d)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"day_cols": {"claimed": "그중 취소·반품(음수로 반영)", "ship": "배송비(참고, 매출 제외)"},
"rule": "매출인식일 기준 매출 내역 supGiveAmt(협력사 지급액 = 포털 주문 통계 금액) 합, SALE 이 아닌 줄은 빼기, "
"배송비 제외. 주문 통계는 주문일 기준이라 날마다 같지는 않고 기간이 길수록 가까워진다"}
+392 -5
View File
@@ -1,27 +1,414 @@
"""네이버 스마트스토어 — 네이버 커머스API.
인증: 애플리케이션 ID + 시크릿으로 전자서명(bcrypt) → OAuth2 client_credentials 토큰.
토큰은 발급받아 암호화 저장하고 만료 시 재발급한다(다음 단계에서 구현).
인증(공식 방식): 애플리케이션 ID + 시크릿으로 전자서명 → OAuth2 client_credentials 토큰.
client_secret_sign = base64( bcrypt.hashpw("{client_id}_{timestamp(ms)}", client_secret) )
POST https://api.commerce.naver.com/external/v1/oauth2/token
(client_id, timestamp, client_secret_sign, grant_type=client_credentials, type=SELF | SELLER+account_id)
토큰은 약 3시간 — 암호화 저장(access_token·access_token_expires_at)해 두고 만료 5분 전에 새로 받는다.
커머스API센터 애플리케이션에 **API 호출 IP(이 서버 외부 IP)** 를 등록해야 호출된다.
매출 수집 — 스마트스토어센터 **판매분석 "판매금액(총)"** 과 같은 기준(2026-09-30 사용자 확인: 9/1 매출 4,455,600원.
판매금액은 할인(판매자·네이버 부담) 뒤 금액, 배송비 332,486원은 별도, 환불 346,340원은 환불일에 따로 빠져 판매금액(순)):
- 조건형 상품 주문 상세 조회 GET /v1/pay-order/seller/product-orders
?from=…&to=…&rangeType=PAYED_DATETIME&pageSize=&page= — 결제일 기준, 한 번에 24시간까지(하루씩 부른다),
from 부터 180일 안의 주문만. 응답에 주문·상품주문 상세가 바로 들어 있다(네이버 안내: 소량·조회용 권장 API).
- SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(order.paymentDate).
금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 — 배송비 제외.
- 결제 뒤 취소·반품된 상품주문도 결제일 매출에 그대로 둔다(판매금액(총)). 입금대기·미입금 취소만 뺀다.
그래서 지난 날짜 매출이 나중에 줄지 않는다. 환불(판매금액(순))은 아직 따로 만들지 않는다.
- 구매자 이름·연락처·주소는 저장하지 않는다.
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import base64
import re
import time
from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
TokenExpired,
)
HOST = "https://api.commerce.naver.com/external"
TOKEN_PATH = "/v1/oauth2/token"
ORDERS_PATH = "/v1/pay-order/seller/product-orders"
EVENT_PREFIX = "naver:"
PAGE_SIZE = 100
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
TOKEN_MARGIN_SEC = 300 # 만료 5분 전이면 새로 받는다
CALL_INTERVAL_SEC = 0.35 # 초당 호출 제한(넘으면 429) — 호출 사이 간격
RETRY_429 = 3
PROBE_MAX_DAYS = 31
# 매출에서 빼는 상품주문 상태 — 결제되지 않은 것만(입금대기·미입금 취소). 결제 뒤 취소·반품된 것은 판매분석
# "판매금액(총)"처럼 결제일 매출에 그대로 둔다(환불은 판매분석에서도 환불일에 따로 빠진다).
EXCLUDED_STATUS = frozenset({"PAYMENT_WAITING", "CANCELED_BY_NOPAYMENT"})
CLAIMED_STATUS = frozenset({"CANCELED", "RETURNED"}) # 결제 뒤 취소·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
STATUS_KO = {
"PAYMENT_WAITING": "입금대기", "PAYED": "결제완료", "DELIVERING": "배송중", "DELIVERED": "배송완료",
"PURCHASE_DECIDED": "구매확정", "EXCHANGED": "교환", "CANCELED": "취소", "RETURNED": "반품",
"CANCELED_BY_NOPAYMENT": "미입금취소",
}
# 원본 데이터 확인 — 개인정보로 보이는 항목은 값 없이 이름만. 금액·상태·날짜·상품명 등은 보인다.
PERSONAL = re.compile(r"orderer|receiver|shippingAddress|takingAddress|returnAddress|pickupAddress|collectAddress|"
r"name$|tel|phone|address|zip|mail|memo|customsClearance|buyer|recipient", re.IGNORECASE)
SAFE = re.compile(r"(productName|productOption|optionCode|productClass|productId|deliveryCompany|reason|Status|Type|"
r"Date|Amount|Price|Fee|Quantity|Count|Id)$")
NUMBER = re.compile(r"^-?\d+(\.\d+)?$")
def _won(value: Any) -> int:
try:
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
except ValueError:
return 0
def _day(value: Any) -> date | None:
""""2026-09-29T10:11:12.0+09:00" → date(2026, 9, 29). 네이버 날짜는 한국 시간(+09:00)으로 온다."""
s = str(value or "")
m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s)
if not m:
return None
try:
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
except ValueError:
return None
def sign(client_id: str, client_secret: str, timestamp_ms: int) -> str:
"""커머스API 전자서명 — bcrypt(비밀번호 = "{client_id}_{timestamp}", 솔트 = 애플리케이션 시크릿) 을 base64."""
import bcrypt # 지연 import
try:
hashed = bcrypt.hashpw(f"{client_id}_{timestamp_ms}".encode("utf-8"), client_secret.encode("utf-8"))
except ValueError:
raise AuthFailed("애플리케이션 시크릿 형식이 올바르지 않습니다. 커머스API센터의 시크릿을 그대로 붙여 넣으세요.") from None
return base64.standard_b64encode(hashed).decode("ascii")
def product_order_items(body: Any) -> list[dict[str, Any]]:
"""조건형 조회 응답에서 상품주문 하나씩 {"order": {...}, "productOrder": {...}, ...} 로 꺼낸다.
응답 모양(data.contents[].content / data 목록 / 바로 목록)이 달라도 받아들인다."""
data = body.get("data", body) if isinstance(body, dict) else body
if isinstance(data, dict):
data = data.get("contents") or data.get("productOrders") or data.get("items") or []
out = []
for it in data if isinstance(data, list) else []:
if not isinstance(it, dict):
continue
c = it.get("content") if isinstance(it.get("content"), dict) else it
if isinstance(c.get("productOrder"), dict):
out.append(c)
return out
def has_next(body: Any, page: int, got: int) -> bool:
data = body.get("data") if isinstance(body, dict) else None
pg = data.get("pagination") if isinstance(data, dict) else None
if isinstance(pg, dict):
if "hasNext" in pg:
return bool(pg["hasNext"])
total = pg.get("totalPages") or pg.get("totalPage")
if total:
return page < int(total)
return got >= PAGE_SIZE
def flatten(obj: Any, prefix: str = "") -> dict[str, str]:
"""중첩 사전 → {"productOrder.totalPaymentAmount": "12000", …}. 목록은 건너뛴다(개수만)."""
out: dict[str, str] = {}
if isinstance(obj, dict):
for k, v in obj.items():
key = f"{prefix}.{k}" if prefix else str(k)
if isinstance(v, dict):
out.update(flatten(v, key))
elif isinstance(v, list):
out[key + "[]"] = str(len(v))
elif v is not None:
out[key] = str(v)
return out
def is_personal(key: str) -> bool:
last = key.rsplit(".", 1)[-1]
if "Address." in key or key.split(".")[0] in ("orderer",):
return True
return bool(PERSONAL.search(key)) and not SAFE.search(last)
def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]:
"""항목별: 채워진 줄 수, 숫자면 합계, 개인정보 아니면 예시 값 하나."""
names: dict[str, dict[str, Any]] = {}
for r in records:
for k, v in r.items():
f = names.setdefault(k, {"name": k, "filled": 0, "numeric": True, "sum": 0.0, "sample": "",
"personal": is_personal(k)})
if v == "":
continue
f["filled"] += 1
if NUMBER.match(v) and f["numeric"]:
f["sum"] += float(v)
else:
f["numeric"] = False
if not f["sample"] and not f["personal"]:
f["sample"] = v[:40]
for f in names.values():
f["sum"] = int(round(f["sum"])) if f["numeric"] and f["filled"] else None
return sorted(names.values(), key=lambda f: f["name"])
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
"""상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
금액 = totalPaymentAmount 합(할인 뒤 상품 결제금액, 배송비 제외) = 판매분석 "판매금액(총)".
배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
orders: dict[str, dict[str, Any]] = {}
for c in items:
po, od = c.get("productOrder") or {}, c.get("order") or {}
oid = str(od.get("orderId") or po.get("orderId") or "")
day = _day(od.get("paymentDate") or po.get("paymentDate"))
status = str(po.get("productOrderStatus") or "")
if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
continue
o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
"discount": 0, "names": [], "opt": "", "statuses": [],
"order_day": _day(od.get("orderDate"))})
paid = _won(po.get("totalPaymentAmount"))
o["amount"] += paid
if status in CLAIMED_STATUS:
o["claimed"] += paid
o["ship"] += _won(po.get("deliveryFeeAmount")) - _won(po.get("deliveryDiscountAmount"))
o["qty"] += _won(po.get("quantity"))
o["discount"] += _won(po.get("productDiscountAmount"))
name = str(po.get("productName") or "")
if name and name not in o["names"]:
o["names"].append(name)
o["opt"] = o["opt"] or str(po.get("productOption") or "")
if status and status not in o["statuses"]:
o["statuses"].append(status)
return orders
class NaverAdapter(MarketplaceAdapter):
code = "naver"
name = "네이버 스마트스토어"
auth_type = "oauth"
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://apicenter.commerce.naver.com/"
note = "커머스API센터에서 발급한 애플리케이션 ID/시크릿을 입력합니다."
note = ("커머스API센터에서 발급한 애플리케이션 ID/시크릿을 입력합니다. 애플리케이션의 API 호출 IP 에 "
"이 서버의 외부 IP 를 등록해야 호출됩니다.")
def __init__(self) -> None:
self._last_call = 0.0
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("client_id", "애플리케이션 ID(Client ID)"),
CredentialField("client_secret", "애플리케이션 시크릿(Client Secret)", secret=True),
CredentialField("account_id", "판매자 ID", required=False,
help="판매자 계정 지정이 필요한 경우에만 입력"),
help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
]
# ── 인증 ──────────────────────────────────────────────
def _token(self, ctx: AdapterContext, *, force: bool = False) -> str:
"""저장된 토큰이 5분 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
if not force:
tok = ctx.credentials.get("access_token")
try:
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
except ValueError:
exp = 0.0
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
return tok
return self._issue_token(ctx)
def _issue_token(self, ctx: AdapterContext) -> str:
import httpx # 지연 import
client_id = ctx.credentials.get("client_id").strip()
client_secret = ctx.credentials.get("client_secret").strip()
if not client_id or not client_secret:
raise NotConfigured("애플리케이션 ID와 시크릿을 입력하세요.")
ts = int(time.time() * 1000)
form = {"client_id": client_id, "timestamp": str(ts), "grant_type": "client_credentials",
"client_secret_sign": sign(client_id, client_secret, ts), "type": "SELF"}
account_id = ctx.credentials.get("account_id").strip()
if account_id:
form.update(type="SELLER", account_id=account_id)
try:
res = httpx.post(f"{HOST}{TOKEN_PATH}", data=form, timeout=ctx.timeout_sec,
headers={"Accept": "application/json"})
except httpx.HTTPError as exc:
raise ApiError(f"네이버 커머스API 연결 실패: {type(exc).__name__}") from None
body = self._json(res)
if res.status_code >= 400 or not body.get("access_token"):
msg = self._err_text(body, res)
if res.status_code in (400, 401, 403):
raise AuthFailed(f"네이버 토큰 발급 실패({res.status_code}): {msg}. 애플리케이션 ID·시크릿과 "
"API 호출 IP(이 서버 외부 IP) 등록을 확인하세요.")
raise ApiError(f"네이버 토큰 발급 오류({res.status_code}): {msg}")
tok = str(body["access_token"])
expires_in = _won(body.get("expires_in")) or 3 * 3600
ctx.credentials.set("access_token", tok)
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
return tok
def authenticate(self, ctx: AdapterContext) -> None:
super().authenticate(ctx)
self._token(ctx)
def refresh_token(self, ctx: AdapterContext) -> None:
self._token(ctx, force=True)
# ── 호출 ──────────────────────────────────────────────
@staticmethod
def _json(res: Any) -> dict[str, Any]:
try:
body = res.json()
except ValueError:
return {}
return body if isinstance(body, dict) else {"data": body}
@staticmethod
def _err_text(body: dict[str, Any], res: Any) -> str:
parts = [str(body.get(k)) for k in ("code", "message", "error", "error_description") if body.get(k)]
inv = body.get("invalidInputs")
if isinstance(inv, list) and inv:
parts.append("; ".join(str(i.get("message") or i) if isinstance(i, dict) else str(i) for i in inv[:3]))
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더."""
import httpx # 지연 import
retried_auth = False
for attempt in range(RETRY_429 + 1):
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
if wait > 0:
time.sleep(wait)
headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"}
try:
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"네이버 커머스API 연결 실패: {type(exc).__name__}") from None
finally:
self._last_call = time.monotonic()
if res.status_code == 429 and attempt < RETRY_429:
time.sleep(1.0 * (2 ** attempt))
continue
if res.status_code == 401 and not retried_auth:
retried_auth = True
self._token(ctx, force=True)
continue
body = self._json(res)
if res.status_code == 401:
raise TokenExpired(f"네이버 인증 만료·거부(401): {self._err_text(body, res)}")
if res.status_code == 403:
raise AuthFailed(f"네이버 권한 거부(403): {self._err_text(body, res)}. 애플리케이션의 API 권한(주문)과 "
"API 호출 IP 등록을 확인하세요.")
if res.status_code >= 400:
raise ApiError(f"네이버 API 오류({res.status_code}): {self._err_text(body, res)}")
return body
raise ApiError("네이버 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
def _day_items(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
"""결제일이 d(한국 시간 0시~23:59:59.999)인 상품주문 전체 — 모든 상태."""
params: dict[str, Any] = {
"from": f"{d.isoformat()}T00:00:00.000+09:00", "to": f"{d.isoformat()}T23:59:59.999+09:00",
"rangeType": "PAYED_DATETIME", "pageSize": PAGE_SIZE,
}
out: list[dict[str, Any]] = []
for page in range(1, MAX_PAGES + 1):
body = self._get(ctx, ORDERS_PATH, {**params, "page": page})
items = product_order_items(body)
out.extend(items)
if not items or not has_next(body, page, len(items)):
break
return out
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
d = start
while d <= end:
rows = self._day_items(ctx, d)
ctx.progress.step(items=len(rows))
yield from rows
d += timedelta(days=1)
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
yield from group_orders(self._items(ctx, start, end), start, end).values()
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
oid, day = str(o.get("orderId") or ""), o.get("_day")
if not oid or day is None:
return []
names = o.get("names") or []
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
return [SaleEvent(
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid,
order_date=o.get("order_day"), payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50],
)]
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
# 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다.
super().authenticate(ctx)
self._token(ctx, force=True)
items = self._day_items(ctx, today_kst())
return f"네이버 커머스API 연결 정상(토큰 발급·주문 조회 확인, 오늘 결제 상품주문 {len(items)}건)."
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""결제일 기준 기간(최대 31일)의 상품주문을 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을 돌려준다.
스마트스토어센터 화면 매출과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보 항목은 값 없이 이름만."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
try:
items = list(self._items(ctx, day, to))
except AdapterError as exc:
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
{"key": "payed", "label": "결제일 기준 상품주문", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
by_status: dict[str, list[dict[str, Any]]] = {}
for c in items:
by_status.setdefault(str((c.get("productOrder") or {}).get("productOrderStatus") or "?"), []).append(c)
probes = [{"key": "payed", "label": "결제일 기준 상품주문(전체 상태)", "path": ORDERS_PATH + " (PAYED_DATETIME)",
"ok": True, "count": len(items), "fields": field_summary([flatten(c) for c in items])}]
for st, rows in sorted(by_status.items()):
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
+ (" — 매출 제외(미결제)" if st in EXCLUDED_STATUS else
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "productOrderStatus",
"ok": True, "count": len(rows),
"fields": [f for f in field_summary([flatten(c) for c in rows])
if f["sum"] is not None and f["name"].startswith("productOrder.")]})
days = []
orders = group_orders(items, day, to)
d = day
while d <= to:
day_orders = [o for o in orders.values() if o["_day"] == d]
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders),
"claimed": sum(o["claimed"] for o in day_orders), "ship": sum(o["ship"] for o in day_orders)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, "
"미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}
+201
View File
@@ -0,0 +1,201 @@
"""매출 업데이트 진행 상황 — 백그라운드 수집 작업(쇼핑몰별 진행 막대)을 메모리에 둔다.
- [매출 업데이트]·[과거 매출 가져오기]는 수집을 백그라운드 스레드로 돌리고 작업 번호를 바로 돌려준다.
화면은 GET /performance/api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다.
- 어댑터가 ctx.progress.plan()/step() 으로 알린 단계를 ShopProgress 가 모은다(쇼핑몰마다 단위가 다르다 —
네이버 "일", 11번가·카페24 "구간").
- 웹 프로세스 하나(uvicorn 단일 워커) 기준 — 워커를 여러 개로 늘리면 진행 상황을 DB 로 옮겨야 한다.
서버를 다시 켜면 진행 중 작업 정보는 사라진다(수집 결과는 DB 에 이미 저장된 만큼 남음).
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
"""
from __future__ import annotations
import threading
import time
import uuid
from datetime import date
from typing import Any
from .adapters.base import Cancelled, Progress
MAX_JOBS = 20
_LOCK = threading.Lock()
_JOBS: dict[str, "SyncJob"] = {}
# 끝났지만 막대에서 빼는 쇼핑몰(수집할 수 없어 바로 끝난 것) — 전체 진행률 계산에서 제외
PASSIVE_STATUS = frozenset({"not_implemented", "not_configured"})
class ShopProgress(Progress):
"""쇼핑몰 하나의 진행 상황. state: waiting → running → saving → done | error | skipped | cancelled."""
def __init__(self, code: str, name: str, *, active: bool = True, job: "SyncJob | None" = None) -> None:
self.code, self.name, self.active, self.job = code, name, active, job
self.state = "waiting"
self.done = self.total = self.items = self.upserted = 0
self.unit = "단계"
self.status = self.label = self.message = ""
self.started_at = self.finished_at = 0.0
self._lock = threading.Lock()
# ── 어댑터가 부르는 쪽(Progress) ──
def plan(self, total: int, unit: str = "단계") -> None:
with self._lock:
self.total, self.unit, self.done = max(0, int(total)), unit or "단계", 0
def add(self, n: int) -> None:
with self._lock:
self.total += max(0, int(n))
def check(self) -> None:
if self.cancel_requested and self.state == "running":
raise Cancelled("사용자가 업데이트를 취소했습니다.")
@property
def cancel_requested(self) -> bool:
return bool(self.job is not None and self.job.cancel_requested)
def step(self, n: int = 1, *, items: int = 0) -> None:
self.check()
with self._lock:
self.done += max(0, int(n))
self.items += max(0, int(items))
if self.total and self.done > self.total: # 계획보다 많이 돌면 전체를 늘려 100% 를 넘지 않게
self.total = self.done
# ── sync 가 부르는 쪽 ──
def start(self) -> None:
with self._lock:
self.state, self.started_at = "running", time.time()
def saving(self) -> None:
with self._lock:
self.state = "saving"
def finish(self, *, upserted: int, message: str = "") -> None:
with self._lock:
self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok"
if self.total:
self.done = self.total
self.finished_at = time.time()
def fail(self, *, status: str, label: str, message: str) -> None:
with self._lock:
self.state, self.status, self.label, self.message = "error", status, label, message
if status in PASSIVE_STATUS:
self.active = False
self.finished_at = time.time()
def cancelled(self) -> None:
with self._lock:
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
self.finished_at = time.time()
def skip(self, message: str) -> None:
with self._lock:
self.state, self.status, self.message = "skipped", "running", message
self.finished_at = time.time()
@property
def finished(self) -> bool:
return self.state in ("done", "error", "skipped", "cancelled")
def fraction(self) -> float:
if self.finished:
return 1.0
if self.state == "saving":
return 0.98
if self.state == "running" and self.total:
return min(0.97, self.done / self.total)
return 0.0
def snapshot(self) -> dict[str, Any]:
with self._lock:
return {
"code": self.code, "name": self.name, "active": self.active, "state": self.state,
"done": self.done, "total": self.total, "unit": self.unit, "items": self.items,
"upserted": self.upserted, "status": self.status, "label": self.label, "message": self.message,
"fraction": round(self.fraction(), 4),
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
}
class SyncJob:
def __init__(self, *, user: str, start: date | None, end: date | None) -> None:
self.id = uuid.uuid4().hex[:12]
self.user, self.start, self.end = user, start, end
self.created_at = time.time()
self.finished_at = 0.0
self.shops: list[ShopProgress] = []
self.error = ""
self.last_update_at: str | None = None
self.cancel_requested = False
self.cancelled_by = ""
self._lock = threading.Lock()
def set_targets(self, targets: list[tuple[str, str, bool]], start: date, end: date) -> dict[str, ShopProgress]:
with self._lock:
self.start, self.end = start, end
self.shops = [ShopProgress(code, name, active=active, job=self) for code, name, active in targets]
return {s.code: s for s in self.shops}
def cancel(self, user: str = "") -> None:
"""[업데이트 취소] — 돌고 있는 쇼핑몰은 다음 API 호출 직전에, 기다리는 쇼핑몰은 차례가 오면 멈춘다."""
with self._lock:
if not self.finished_at and not self.cancel_requested:
self.cancel_requested, self.cancelled_by = True, user
def finish(self, *, error: str = "", last_update_at: str | None = None) -> None:
with self._lock:
self.error, self.last_update_at, self.finished_at = error, last_update_at, time.time()
@property
def finished(self) -> bool:
return bool(self.finished_at)
def snapshot(self) -> dict[str, Any]:
with self._lock:
shops = [s.snapshot() for s in self.shops]
active = [s for s in shops if s["active"]]
return {
"id": self.id, "finished": self.finished, "error": self.error, "user": self.user,
"cancel_requested": self.cancel_requested,
"from": self.start.isoformat() if self.start else None, "to": self.end.isoformat() if self.end else None,
"elapsed": round((self.finished_at or time.time()) - self.created_at, 1),
"last_update_at": self.last_update_at, "shops": shops,
"overall": {
"shops": len(active),
"finished": sum(1 for s in active if s["state"] in ("done", "error", "skipped", "cancelled")),
"fraction": round(sum(s["fraction"] for s in active) / len(active), 4) if active else
(1.0 if self.finished else 0.0),
"items": sum(s["items"] for s in shops), "upserted": sum(s["upserted"] for s in shops),
},
}
def create_job(*, user: str, start: date | None, end: date | None) -> SyncJob:
job = SyncJob(user=user, start=start, end=end)
with _LOCK:
_JOBS[job.id] = job
if len(_JOBS) > MAX_JOBS: # 오래된 끝난 작업부터 정리
for jid, j in sorted(_JOBS.items(), key=lambda kv: kv[1].created_at):
if len(_JOBS) <= MAX_JOBS:
break
if j.finished:
del _JOBS[jid]
return job
def get_job(job_id: str) -> SyncJob | None:
with _LOCK:
return _JOBS.get(job_id)
def running_job() -> SyncJob | None:
"""지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
with _LOCK:
live = [j for j in _JOBS.values() if not j.finished]
return max(live, key=lambda j: j.created_at) if live else None
+77
View File
@@ -5,6 +5,10 @@
GET /performance/settings 실적 설정(관리자)
JSON API — 모듈 권한
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
@@ -155,10 +159,83 @@ def api_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JS
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
raise HTTPException(status_code=403,
detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
if payload.get("background"):
return JSONResponse(_start_background_sync(store, sync, start=start, end=end, codes=codes or None,
user=user["email"]))
results = sync.sync_all(start=start, end=end, codes=codes or None, user=user["email"])
return JSONResponse({"results": results, "last_update_at": store.last_update_at()})
def _start_background_sync(store: Any, sync: Any, *, start: date | None, end: date | None,
codes: list[str] | None, user: str) -> dict[str, Any]:
"""수집을 스레드로 돌리고 작업 번호를 바로 돌려준다. 이미 돌고 있는 업데이트가 있으면 새로 시작하지 않고
그 작업을 보여 준다(같은 쇼핑몰 동시 실행은 어차피 막혀 있다)."""
import logging # noqa: WPS433
import threading # noqa: WPS433
from . import jobs # noqa: WPS433
live = jobs.running_job()
if live is not None:
return {"job": live.snapshot(), "joined": True}
job = jobs.create_job(user=user, start=start, end=end)
def run() -> None:
error = ""
try:
sync.sync_all(start=start, end=end, codes=codes, user=user, job=job)
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
logging.getLogger("performance.sync").exception("background sync failed")
error = f"업데이트 중 오류: {type(exc).__name__}"
last = None
try:
last = store.last_update_at()
except Exception: # noqa: BLE001
pass
job.finish(error=error, last_update_at=last)
threading.Thread(target=run, name=f"perf-sync-{job.id}", daemon=True).start()
return {"job": job.snapshot(), "joined": False}
@router.get("/api/sync/jobs/{job_id}")
def api_sync_job(request: Request, job_id: str) -> JSONResponse:
common.require_store(request)
from . import jobs # noqa: WPS433
job = jobs.get_job(job_id)
if job is None:
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
return JSONResponse({"job": job.snapshot()})
@router.post("/api/sync/jobs/{job_id}/cancel")
def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
"""[업데이트 취소] — 시작한 사람 또는 관리자. 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
기다리는 쇼핑몰은 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 그대로 남는다."""
from app.store import is_admin # noqa: WPS433
from . import jobs # noqa: WPS433
_, user = common.require_store(request)
job = jobs.get_job(job_id)
if job is None:
raise HTTPException(status_code=404, detail="진행 상황을 찾을 수 없습니다(서버가 다시 시작됐을 수 있습니다).")
if job.user and job.user != user["email"] and not is_admin(user):
raise HTTPException(status_code=403, detail="업데이트를 시작한 사람이나 관리자만 취소할 수 있습니다.")
job.cancel(user["email"])
return JSONResponse({"job": job.snapshot()})
@router.get("/api/sync/current")
def api_sync_current(request: Request) -> JSONResponse:
common.require_store(request)
from . import jobs # noqa: WPS433
job = jobs.running_job()
return JSONResponse({"job": job.snapshot() if job else None})
@router.get("/api/events")
def api_events(request: Request, code: str, from_: str = Query(..., alias="from"), to: str | None = None) -> JSONResponse:
store, _ = common.require_store(request)
+44 -5
View File
@@ -20,7 +20,7 @@ from typing import Any, Iterable
from app.timezone import today_kst
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, MarketplaceAdapter, SaleEvent
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, Cancelled, MarketplaceAdapter, SaleEvent
from .adapters.registry import all_adapters, get_adapter
from .credentials import CredentialService
from .security.crypto import CryptoConfigError, DecryptError
@@ -94,18 +94,32 @@ class SyncService:
# ── 동기화 ──────────────────────────────────────────────
def sync_marketplace(self, code: str, start: date, end: date, *, trigger: str = "manual",
user: str = "") -> dict[str, Any]:
user: str = "", progress: Any = None) -> dict[str, Any]:
"""progress: jobs.ShopProgress(매출 업데이트 창 진행 막대) — 없으면 알리지 않는다."""
adapter = get_adapter(code)
result: dict[str, Any] = {"code": code, "ok": False, "skipped": False, "fetched": 0, "upserted": 0}
if adapter is None:
if progress is not None:
progress.fail(status="api_error", label=STATUS_LABELS["api_error"], message="알 수 없는 쇼핑몰입니다.")
return {**result, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
if progress is not None and progress.cancel_requested: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
run_id = self._store.start_run(code, trigger=trigger, range_from=start, range_to=end, user=user)
if run_id is None:
if progress is not None:
progress.skip("이미 다른 업데이트가 진행 중입니다.")
return {**result, "skipped": True, "status": "running", "message": "이미 업데이트 중입니다."}
if progress is not None:
progress.start()
ctx = None
try:
ctx = self._ctx(adapter, user=user)
if progress is not None:
ctx.progress = progress
fetched, events = adapter.collect(ctx, start, end)
if progress is not None:
progress.saving()
known = ctx.credentials.known_secrets()
rows = [event_row(ev, known) for ev in events]
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
@@ -121,22 +135,47 @@ class SyncService:
upserted = self._store.upsert_events(code, rows)
self._store.finish_run(run_id, ok=True, fetched=fetched, upserted=upserted)
self._store.record_sync(code, status="ok", ok=True)
if progress is not None:
progress.finish(upserted=upserted, message=f"{upserted}건 반영")
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
"message": f"{upserted}건 반영"}
except Cancelled:
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
if progress is not None:
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
status, message = self._failure(exc, ctx)
logger.warning("performance sync %s failed: %s %s", code, status, message)
self._store.finish_run(run_id, ok=False, error=message)
self._store.record_sync(code, status=status, ok=False, error=message)
if progress is not None:
progress.fail(status=status, label=STATUS_LABELS.get(status, status), message=message)
return {**result, "status": status, "label": STATUS_LABELS.get(status, status), "message": message}
def sync_all(self, *, start: date | None = None, end: date | None = None, codes: list[str] | None = None,
trigger: str = "manual", user: str = "") -> list[dict[str, Any]]:
trigger: str = "manual", user: str = "", job: Any = None) -> list[dict[str, Any]]:
"""job: jobs.SyncJob — 주면 쇼핑몰마다 진행 상황(ShopProgress)을 채운다(매출 업데이트 창)."""
end = end or today_kst()
start = start or (end - timedelta(days=sync_days() - 1))
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
targets = [a.code for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
return [self.sync_marketplace(c, start, end, trigger=trigger, user=user) for c in targets]
targets = [a for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
progress: dict[str, Any] = {}
if job is not None:
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
# 쇼핑몰이 전체 진행률을 부풀리거나, 아직 차례가 안 와서 진행률을 낮추지 않게.
def ready(a: MarketplaceAdapter) -> bool:
if not a.implemented:
return False
try:
return a.is_configured(self._ctx(a, user=user))
except Exception: # noqa: BLE001 — 확인이 안 되면 일단 막대로(실제 결과는 수집 때 나온다)
return True
progress = job.set_targets([(a.code, a.name, ready(a)) for a in targets], start, end)
return [self.sync_marketplace(a.code, start, end, trigger=trigger, user=user, progress=progress.get(a.code))
for a in targets]
# ── 쇼핑몰 화면과 대조 ────────────────────────────────
def reconcile(self, code: str, day: date, *, to: date | None = None, user: str = "") -> dict[str, Any]:
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930e" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -239,4 +239,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930e" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -117,16 +117,23 @@
</div>
<div class="erp-card perf-card perf-card-wide">
<div class="perf-card-head"><h2 class="perf-h">11번가 원본 데이터 확인</h2></div>
<p class="perf-muted">11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.</p>
<div class="perf-card-head"><h2 class="perf-h">쇼핑몰 원본 데이터 확인</h2></div>
<p class="perf-muted">쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음).
쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다.
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.</p>
<div class="perf-sample-form">
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
<option value="naver">네이버 스마트스토어</option>
<option value="elevenst">11번가</option>
<option value="gsshop">GS샵</option>
</select>
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" id="perf-probe-to" value="{{ default_sample_to }}" />
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe" data-code="elevenst">불러오기</button>
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe">불러오기</button>
</div>
<div id="perf-probe-result"></div>
</div>
@@ -170,4 +177,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
@@ -966,6 +966,425 @@ def test_registry_and_event_validation():
raise AssertionError(f"검증 실패해야 함: {bad.event_type} {bad.amount}")
def _naver_item(order_id, po_id, pay_day, amount, *, status="PAYED", ship=0, ship_dc=0, qty=1, dc=0, name="밀폐용기"):
"""조건형 상품 주문 조회 응답의 contents[] 한 줄(개인정보 항목 포함 — 저장 안 되는지 확인용)."""
return {"productOrderId": po_id, "content": {
"order": {"orderId": order_id, "paymentDate": f"{pay_day}T10:11:12.0+09:00", "orderDate": f"{pay_day}T10:10:00.0+09:00",
"ordererName": "홍길동", "ordererTel": "010-1234-5678", "ordererId": "hong***"},
"productOrder": {"productOrderId": po_id, "productOrderStatus": status, "productName": name, "productOption": "3개입",
"quantity": qty, "totalPaymentAmount": amount, "productDiscountAmount": dc,
"deliveryFeeAmount": ship, "deliveryDiscountAmount": ship_dc,
"shippingAddress": {"name": "홍길동", "tel1": "010-1234-5678", "baseAddress": "서울시 어딘가"}},
}}
def test_naver_sign_token_and_connection():
"""네이버: bcrypt 전자서명 → 토큰(form) → Bearer 로 조건형 주문 조회. 시크릿·토큰은 오류 문구에 없음."""
import base64
import bcrypt
import httpx
from app.modules.performance.adapters import naver as nv
from app.modules.performance.adapters.base import AdapterContext
secret = bcrypt.gensalt(rounds=4).decode()
sig = nv.sign("my-app-id", secret, 1727600000000)
assert bcrypt.checkpw(b"my-app-id_1727600000000", base64.b64decode(sig))
try:
nv.sign("my-app-id", "not-a-bcrypt-salt", 1)
except AuthFailed as exc:
assert "not-a-bcrypt-salt" not in exc.message
else:
raise AssertionError("시크릿 형식 오류여야 합니다")
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
def set(self, k, v):
self[k] = v
ctx = AdapterContext(code="naver", credentials=Creds(client_id="my-app-id", client_secret=secret))
seen = {"gets": []}
def post(url, data=None, timeout=None, headers=None):
seen["post"] = (url, dict(data))
return httpx.Response(200, json={"access_token": "TOKEN-XYZ", "expires_in": 10799, "token_type": "Bearer"})
def get(url, params=None, headers=None, timeout=None):
seen["gets"].append((url, dict(params), headers["Authorization"]))
return httpx.Response(200, json={"data": {"contents": [_naver_item("O1", "P1", "2026-09-30", 12000)],
"pagination": {"page": 1, "size": 100, "hasNext": False}}})
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = post, get, 0
try:
msg = nv.NaverAdapter().test_connection(ctx)
assert "연결 정상" in msg and "1건" in msg
url, form = seen["post"]
assert url.endswith("/external/v1/oauth2/token") and form["type"] == "SELF" and form["grant_type"] == "client_credentials"
assert bcrypt.checkpw(f"my-app-id_{form['timestamp']}".encode(), base64.b64decode(form["client_secret_sign"]))
gurl, params, auth = seen["gets"][0]
assert gurl.endswith("/v1/pay-order/seller/product-orders") and auth == "Bearer TOKEN-XYZ"
assert params["rangeType"] == "PAYED_DATETIME" and params["from"].endswith("T00:00:00.000+09:00")
assert params["to"].endswith("T23:59:59.999+09:00") and params["from"][:10] == params["to"][:10]
assert ctx.credentials["access_token"] == "TOKEN-XYZ" and int(ctx.credentials["access_token_expires_at"]) > 0
# 토큰 발급 거부 → 인증 실패(시크릿·서명은 문구에 없음)
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
400, json={"code": "BadRequest", "message": "client_secret_sign 이 올바르지 않습니다"})
try:
nv.NaverAdapter().test_connection(ctx)
except AuthFailed as exc:
assert secret not in exc.message and "올바르지 않습니다" in exc.message
else:
raise AssertionError("인증 실패여야 합니다")
# 주문 조회 403(IP 미등록 등) → 인증 실패 안내
httpx.post = post
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
403, json={"code": "GW.IP_NOT_ALLOWED", "message": "허용되지 않은 IP"})
try:
nv.NaverAdapter().test_connection(ctx)
except AuthFailed as exc:
assert "허용되지 않은 IP" in exc.message and "TOKEN-XYZ" not in exc.message
else:
raise AssertionError("권한 거부여야 합니다")
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
def test_naver_collect_sales():
"""네이버 매출 = 판매분석 "판매금액(총)" — 주문 단위, 결제일 기준, 상품주문 결제금액 합(배송비 제외).
결제 뒤 취소·반품된 것도 포함, 미입금 취소만 뺀다(9/1 실데이터: 판매금액(총) 4,455,600, 배송비 별도).
페이지를 넘겨 받고, 구매자 정보는 저장하지 않는다."""
import bcrypt
import httpx
from app.modules.performance.adapters import naver as nv
pages = {
("2026-09-09", 1): ([_naver_item("A", "A1", "2026-09-09", 20000, ship=3000, qty=2, dc=1000),
_naver_item("A", "A2", "2026-09-09", 5000, ship=3000, name="뚜껑")], True),
("2026-09-09", 2): ([_naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")], False),
("2026-09-10", 1): ([_naver_item("C", "C1", "2026-09-10", 15000, ship=3000, ship_dc=3000, status="PURCHASE_DECIDED"),
_naver_item("C", "C2", "2026-09-10", 7000, status="RETURNED"),
_naver_item("D", "D1", "2026-09-10", 4000, status="CANCELED_BY_NOPAYMENT")], False),
}
calls = []
def get(url, params=None, headers=None, timeout=None):
key = (params["from"][:10], params["page"])
calls.append(key)
rows, more = pages.get(key, ([], False))
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"page": params["page"], "hasNext": more}}})
def post(url, data=None, timeout=None, headers=None):
return httpx.Response(200, json={"access_token": "TOKEN-N", "expires_in": 10799})
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "naver"),
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = post, get, 0
try:
r = SyncService(st, creds).sync_marketplace("naver", date(2026, 9, 9), date(2026, 9, 10))
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "naver"}
assert set(ev_) == {"naver:A", "naver:B", "naver:C"} # D 미입금취소만 제외
assert ev_["naver:A"]["amount"] == 20000 + 5000 # 배송비 제외
assert ev_["naver:B"]["amount"] == 9900 # 결제 뒤 취소도 결제일 매출(판매금액(총))
assert ev_["naver:A"]["quantity"] == 3 and ev_["naver:A"]["discount_amount"] == 1000
assert ev_["naver:A"]["sales_date"] == date(2026, 9, 9) and ev_["naver:A"]["product_name"] == "밀폐용기 외 1건"
assert ev_["naver:C"]["amount"] == 15000 + 7000 # 반품 줄도 포함
assert ev_["naver:C"]["order_status"] == "구매확정/반품"
assert ("2026-09-09", 2) in calls and ("2026-09-10", 2) not in calls # hasNext 일 때만 다음 쪽
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
def test_naver_reconcile_hides_personal():
import httpx
from app.modules.performance.adapters import naver as nv
from app.modules.performance.adapters.base import AdapterContext
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
def set(self, k, v):
self[k] = v
import time as _t
ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T",
access_token_expires_at=str(int(_t.time()) + 9999)))
rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")]
orig = (httpx.get, nv.CALL_INTERVAL_SEC)
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
200, json={"data": {"contents": rows if params["from"].startswith("2026-09-09") else []}})
nv.CALL_INTERVAL_SEC = 0
try:
rec = nv.NaverAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
finally:
httpx.get, nv.CALL_INTERVAL_SEC = orig
allp = rec["probes"][0]
assert allp["ok"] and allp["count"] == 2
f = {x["name"]: x for x in allp["fields"]}
assert f["productOrder.totalPaymentAmount"]["sum"] == 29900
assert f["order.ordererName"]["personal"] and f["order.ordererName"]["sample"] == ""
assert f["productOrder.shippingAddress.baseAddress"]["personal"]
assert not f["productOrder.productName"]["personal"] and f["productOrder.productName"]["sample"] == "밀폐용기"
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec)
assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 9900, "ship": 3000},
{"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 0, "ship": 0}]
assert any("결제 뒤 취소·반품(매출 포함)" in p["label"] for p in rec["probes"])
def test_sync_job_progress():
"""매출 업데이트 진행 창: 쇼핑몰별 단계(네이버 = 일)·받은 건수·상태, 전체 진행률.
수집이 없는 쇼핑몰(연동 준비 중)·인증정보 없는 쇼핑몰은 막대에서 빼고(active=False) 전체 진행률에 넣지 않는다."""
import bcrypt
import httpx
from app.modules.performance import jobs
from app.modules.performance.adapters import naver as nv
mid = {}
job = jobs.create_job(user="king@x", start=None, end=None)
def get(url, params=None, headers=None, timeout=None):
day = params["from"][:10]
if day == "2026-09-10": # 둘째 날을 받는 중 — 진행 상황 중간 모습
mid.update(job.snapshot())
rows = [_naver_item("A" + day, "P" + day, day, 10000), _naver_item("B" + day, "Q" + day, day, 5000)]
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
st = FakeStore()
st.markets = [m for m in st.markets if m["code"] in ("naver", "ohouse", "elevenst")]
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "naver"),
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
httpx.get, nv.CALL_INTERVAL_SEC = get, 0
try:
SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 10), user="king@x", job=job)
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
job.finish(last_update_at="2026-09-30T10:00:00")
m = {s["code"]: s for s in mid["shops"]}
assert m["naver"]["state"] == "running" and (m["naver"]["done"], m["naver"]["total"], m["naver"]["unit"]) == (1, 2, "일")
assert m["naver"]["items"] == 2 and m["naver"]["fraction"] == 0.5
assert mid["overall"]["shops"] == 1 and mid["overall"]["fraction"] == 0.5 and not mid["finished"]
snap = job.snapshot()
s = {x["code"]: x for x in snap["shops"]}
assert s["naver"]["state"] == "done" and s["naver"]["upserted"] == 4 and s["naver"]["items"] == 4
assert s["naver"]["done"] == s["naver"]["total"] == 2 and s["naver"]["fraction"] == 1.0
assert s["ohouse"]["state"] == "error" and s["ohouse"]["status"] in ("not_implemented", "not_configured")
assert not s["ohouse"]["active"]
assert s["elevenst"]["state"] == "error" and s["elevenst"]["status"] == "not_configured" and not s["elevenst"]["active"]
assert snap["finished"] and snap["overall"] == {"shops": 1, "finished": 1, "fraction": 1.0, "items": 4, "upserted": 4}
assert snap["from"] == "2026-09-09" and snap["to"] == "2026-09-10"
assert jobs.get_job(job.id) is job and jobs.running_job() is None
def test_gsshop_token_connection_and_probe():
"""GS샵: token = AES256(yyyyMMddHHmmss + 협력사코드), 헤더 supCd·token. 암호화 모드를 모르니 순서대로 시도해
통과한 모드를 기억. 인증 오류는 HTTP 200 + result=fail/code 401. 원본 확인은 10일씩·쪽 넘김, 키는 문구에 없음."""
import base64
from datetime import datetime
import httpx
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from app.modules.performance.adapters import gsshop as gs
from app.modules.performance.adapters.base import AdapterContext
key = "0123456789abcdef0123456789ABCDEF" # 32바이트 = AES256
def decrypt(tok, mode):
m = {"ecb": modes.ECB(), "cbc-zeroiv": modes.CBC(b"\0" * 16)}.get(mode, modes.CBC(key.encode()[:16]))
d = Cipher(algorithms.AES(key.encode()), m).decryptor()
raw = d.update(base64.b64decode(tok)) + d.finalize()
u = padding.PKCS7(128).unpadder()
return (u.update(raw) + u.finalize()).decode()
# 키 변형: 32자 16진수 → 글자 그대로(AES256) + 16진수 풀기(16바이트), 64자 16진수 → 풀어서 32바이트 + 앞 32자
hex32 = "af3df6c96b92f9166fd75b80006c6812"
assert [v for v, _ in gs.key_variants(hex32)] == ["text", "hex"]
assert [(v, len(b)) for v, b in gs.key_variants(hex32 * 2)] == [("hex", 32), ("first32", 32)]
now = datetime(2018, 10, 17, 17, 49, 13)
for mode in gs.TOKEN_MODES:
assert decrypt(gs.make_token(key, "1036018", now, mode), mode) == "201810171749131036018"
try:
gs.make_token("short-key", "1", now, "ecb")
except AuthFailed as exc:
assert "short-key" not in exc.message
else:
raise AssertionError("키 길이 오류여야 합니다")
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
ctx = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key=key))
calls = []
def get(url, params=None, headers=None, timeout=None):
assert headers["supCd"] == "1036018" and params["supCode"] == "1036018"
# 서버는 ECB 로 풀어 본다고 가정 — CBC 토큰은 거부(HTTP 200 + result=fail)
try:
plain = decrypt(headers["token"], "ecb")
except Exception: # noqa: BLE001
plain = ""
if not plain.endswith("1036018"):
return httpx.Response(200, json={"result": "fail", "message": "키 인증 중 오류가 발생하였습니다.", "code": "401 UNAUTHORIZED"})
calls.append((url, dict(params)))
if url.endswith("/sales"):
return httpx.Response(200, json={"data": [], "hasMorePage": False, "totalCount": 3})
page = params["pageIdx"]
more = url.endswith("/sales/period") and params["fromDate"] == "20260901" and page == 1
rows = [{"ordNo": f"{params['fromDate']}-{page}", "saleAmt": 10000, "custNm": "홍길동", "prdNm": "밀폐용기"}]
return httpx.Response(200, json={"data": rows, "hasMorePage": more, "totalCount": 2 if more else 1})
orig = httpx.get
httpx.get = get
try:
msg = gs.GsshopAdapter().test_connection(ctx)
assert "연결 정상" in msg and "3건" in msg and "ECB" in msg
adapter = gs.GsshopAdapter()
rec = adapter.reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 15)) # 10일 + 5일
sales, ship = rec["probes"]
assert sales["ok"] and sales["count"] == 3 and ship["ok"] and ship["count"] == 2 # 9/1 두 쪽 + 9/11
f = {x["name"]: x for x in sales["fields"]}
assert f["saleAmt"]["sum"] == 30000 and f["custNm"]["personal"] and f["custNm"]["sample"] == ""
assert f["prdNm"]["sample"] == "밀폐용기" and "홍길동" not in repr(rec)
periods = {(p["fromDate"], p["toDate"]) for u, p in calls if u.endswith("/sales/period")}
assert periods == {("20260901", "20260910"), ("20260911", "20260915")}
# 틀린 키 → 세 가지 모드 모두 거부 → 인증 실패(키는 문구에 없음)
bad = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="X" * 32))
try:
gs.GsshopAdapter().test_connection(bad)
except AuthFailed as exc:
assert "X" * 32 not in exc.message and "3가지" in exc.message # 32자 글자 키 → 모드 3가지
else:
raise AssertionError("인증 실패여야 합니다")
finally:
httpx.get = orig
def test_gsshop_collect_sales():
"""GS샵 매출 = 매출 내역 supGiveAmt(협력사 지급액 = 포털 주문 통계 금액), 매출인식일 기준, 배송비 제외.
SALE 이 아닌 줄은 음수(RETURN). 실데이터 9/3: 판매가 16,400 → 지급액 13,940(85%), 고객 결제 15,580."""
import httpx
from app.modules.performance.adapters import gsshop as gs
key = "0123456789abcdef0123456789ABCDEF"
def line(no, item, day, sale, dc, typ="SALE", qty=1):
return {"rnum": 1, "saleAwareDt": day, "prdCd": 1064149860, "prdNm": "미라클통 황토 3200ml", "supCd": 1047142,
"ordNo": no, "ordItemNo": item, "orgOrdNo": no, "ordType": typ, "chrQty": qty, "salePrice": sale,
"dcTotAmt": dc, "custChrAmt": sale - dc, "supGiveAmt": round(sale * 0.85)}
rows = [line(3470403225, 1, 20260903, 16400, 820), line(3470403225, 2, 20260903, 32800, 1640, qty=2),
line(3470409999, 1, 20260904, 20000, 0, typ="RTN"), line(3470500000, 1, 20260912, 9900, 0)]
def get(url, params=None, headers=None, timeout=None):
if url.endswith("/shippingFee/period"):
return httpx.Response(200, json={"data": [{"saleAwareDt": 20260903, "prdNm": "배송비상품", "ordType": "SALE",
"ordNo": 3470403225, "ordItemNo": 3, "salePrice": 3500}],
"hasMorePage": False})
lo, hi = int(params["fromDate"]), int(params["toDate"])
return httpx.Response(200, json={"data": [r for r in rows if lo <= r["saleAwareDt"] <= hi], "hasMorePage": False})
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "gsshop"), {"vendor_code": "1047142", "api_key": key})
orig = httpx.get
httpx.get = get
try:
r = SyncService(st, creds).sync_marketplace("gsshop", date(2026, 9, 3), date(2026, 9, 4))
finally:
httpx.get = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "gsshop"}
assert set(ev_) == {"gs:3470403225-1-SALE-20260903", "gs:3470403225-2-SALE-20260903", "gs:3470409999-1-RTN-20260904"}
assert ev_["gs:3470403225-1-SALE-20260903"]["amount"] == 13940 and ev_["gs:3470403225-1-SALE-20260903"]["discount_amount"] == 820
assert ev_["gs:3470403225-2-SALE-20260903"]["quantity"] == 2
ret = ev_["gs:3470409999-1-RTN-20260904"]
assert ret["event_type"] == "RETURN" and ret["amount"] == -17000 and ret["sales_date"] == date(2026, 9, 4)
assert sum(v["amount"] for v in ev_.values()) == 13940 + 27880 - 17000 # 배송비 3,500 제외
httpx.get = get
try:
rec = gs.GsshopAdapter().reconcile(__import__("app.modules.performance.adapters.base", fromlist=["x"]).AdapterContext(
code="gsshop", credentials=creds.accessor("gsshop")), date(2026, 9, 3), to=date(2026, 9, 4))
finally:
httpx.get = orig
assert rec["days"][0] == {"date": "2026-09-03", "orders": 1, "amount": 41820, "claimed": 0, "ship": 3500}
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
def test_sync_job_cancel():
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
import bcrypt
import httpx
from app.modules.performance import jobs
from app.modules.performance.adapters import naver as nv
job = jobs.create_job(user="king@x", start=None, end=None)
days = []
def get(url, params=None, headers=None, timeout=None):
days.append(params["from"][:10])
if len(days) == 2:
job.cancel("king@x") # 둘째 날을 받는 도중 취소
rows = [_naver_item("A" + days[-1], "P" + days[-1], days[-1], 10000)]
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"hasNext": False}}})
st = FakeStore()
st.markets = [m for m in st.markets if m["code"] in ("naver", "gsshop")]
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "naver"),
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
creds.save(next(a for a in all_adapters() if a.code == "gsshop"),
{"vendor_code": "1047142", "api_key": "0123456789abcdef0123456789ABCDEF"})
st.events[("naver", "SALE", "naver:OLD")] = {"amount": 5000, "is_sample": False, "sales_date": date(2026, 9, 10)}
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(200, json={"access_token": "T", "expires_in": 10799})
httpx.get, nv.CALL_INTERVAL_SEC = get, 0
try:
res = SyncService(st, creds).sync_all(start=date(2026, 9, 9), end=date(2026, 9, 12), user="king@x", job=job)
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
job.finish()
assert days == ["2026-09-09", "2026-09-10"] # 셋째 날은 부르지 않음
assert [r.get("cancelled") for r in res] == [True, True]
snap = {s["code"]: s for s in job.snapshot()["shops"]}
assert snap["naver"]["state"] == "cancelled" and snap["gsshop"]["state"] == "cancelled"
assert list(st.events) == [("naver", "SALE", "naver:OLD")] # 저장 안 함 — 기존 매출 그대로
assert "naver" not in st.status and "gsshop" not in st.status # 연결 상태 안 바뀜
snapshot = job.snapshot()
assert snapshot["cancel_requested"] and snapshot["overall"]["finished"] == 2 and snapshot["overall"]["fraction"] == 1.0
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0
+151
View File
@@ -0,0 +1,151 @@
"""프로젝트 관리 — 현재 접근 권한의 공통 기준(서버).
라우터·마감 알림이 같은 규칙을 쓰도록 한 곳에 모은다. 모든 판단은 "지금" 기준이다 —
예전에 멤버였거나 담당자·멘션·협업자로 기록돼 있어도, 지금 권한이 없으면 보이지도
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
프로젝트
관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다.
작업
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
→ 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
"""
from __future__ import annotations
from typing import Any, Callable, Iterable
from . import store
FULL = "full"
READ = "read"
UserLookup = Callable[[str], "dict[str, Any] | None"]
def default_user_lookup(email: str) -> dict[str, Any] | None:
"""등록 사용자 레코드(app.main.user_store). 지연 import — 테스트는 lookup 을 직접 넘긴다."""
from app.main import user_store # noqa: WPS433
return user_store.get(store.norm_str(email, lower=True))
def _is_admin(user: dict[str, Any] | None) -> bool:
from app.store import is_admin # noqa: WPS433
return is_admin(user)
def can_use_module(user: dict[str, Any] | None) -> bool:
from app.store import has_module # noqa: WPS433
return bool(user) and has_module(user, "project")
def email_of(user: dict[str, Any] | None) -> str:
return store.norm_str((user or {}).get("email", ""), lower=True)
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
"""프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False."""
if not can_use_module(user):
return False
if _is_admin(user):
return True
try:
pid = int(project_id)
except (TypeError, ValueError):
return False
return bool(st.is_member(project_id=pid, user_email=email_of(user)))
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
"""관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
if _is_admin(user):
return None
if not can_use_module(user):
return set()
return {
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
}
def task_access(st: Any, user: dict[str, Any] | None, task: dict[str, Any] | None) -> str | None:
"""작업 하나에 대한 지금 권한: FULL / READ / None."""
if not task or not can_use_module(user):
return None
if can_manage_project(st, user, task.get("project_id")):
return FULL
for pid in link_scope(st, [int(task["id"])]).get(int(task["id"]), set()):
if can_manage_project(st, user, pid):
return READ
return None
def link_scope(st: Any, task_ids: Iterable[int]) -> dict[int, set[int]]:
"""작업 id → 이 작업 또는 상위 작업이 연결된 프로젝트 id 들. 연결 표가 없으면 빈 값."""
ids = [int(i) for i in task_ids]
if not ids:
return {}
try:
return st.task_link_scope(task_ids=ids)
except Exception: # noqa: BLE001 - 003 미적용(연결 기능 없음) → 연결로 보이는 작업 없음
return {}
def filter_visible_tasks(st: Any, user: dict[str, Any], tasks: list[dict[str, Any]],
*, key: str = "id") -> list[dict[str, Any]]:
"""목록에서 지금 볼 수 있는(FULL 또는 READ) 작업만 남긴다 — 내 작업·수신함·알림 공용."""
allowed = visible_project_ids(st, user)
if allowed is None:
return list(tasks)
ids = [int(t[key]) for t in tasks if t.get(key) is not None]
scope = link_scope(st, ids)
out = []
for t in tasks:
tid = t.get(key)
pid = t.get("project_id")
if pid is not None and int(pid) in allowed:
out.append(t)
elif tid is not None and scope.get(int(tid), set()) & allowed:
out.append(t)
return out
def email_task_access(st: Any, email: str, task: dict[str, Any],
lookup: UserLookup | None = None) -> str | None:
"""이메일(알림·멘션 대상)이 지금 이 작업을 볼 수 있는지. 등록 안 된 사람·모듈 권한 없는 사람은 None."""
rec = (lookup or default_user_lookup)(email)
if not rec:
return None
rec = {**rec, "email": rec.get("email") or email}
return task_access(st, rec, task)
def filter_recipients(st: Any, task: dict[str, Any], emails: Iterable[str],
lookup: UserLookup | None = None) -> list[str]:
"""알림·메일·멘션 대상 중 지금 이 작업을 볼 수 있는 사람만(순서 유지, 중복 제거)."""
out: list[str] = []
seen: set[str] = set()
for e in emails:
em = store.norm_str(e, lower=True)
if not em or em in seen:
continue
seen.add(em)
if email_task_access(st, em, task, lookup) is not None:
out.append(em)
return out
def can_assign(st: Any, email: str, project_id: Any, lookup: UserLookup | None = None) -> bool:
"""담당자·소유자 후보 — 등록된 사용자이고 project 모듈 권한이 있으며, 그 프로젝트를
관리할 수 있어야 한다(관리자 포함). 권한 없는 사람에게 작업 정보가 담긴 알림이 가지 않게."""
rec = (lookup or default_user_lookup)(email)
if not rec:
return False
rec = {**rec, "email": rec.get("email") or email}
return can_manage_project(st, rec, project_id)
+137 -5
View File
@@ -100,6 +100,7 @@ class ProjectStore:
ic = store.validate_project_icon(icon)
sd = store.validate_date(start_date)
dd = store.validate_date(due_date)
store.validate_date_range(sd, dd)
with self._pool.connection() as conn:
with conn.transaction():
if parent_id is not None:
@@ -158,15 +159,26 @@ class ProjectStore:
}
sets: list[str] = []
params: list[Any] = []
clean: dict[str, Any] = {}
for key, fn in allowed.items():
if key in fields:
clean[key] = fn(fields[key])
sets.append(f"{key} = %s")
params.append(fn(fields[key]))
params.append(clean[key])
if not sets:
existing = self.get_project(project_id=project_id)
if existing is None:
raise KeyError(project_id)
return existing
if "start_date" in clean or "due_date" in clean:
# 한쪽만 바꿔도 기존 값과 합친 최종 상태로 검사한다.
existing = self.get_project(project_id=project_id)
if existing is None:
raise KeyError(project_id)
store.validate_date_range(
clean["start_date"] if "start_date" in clean else existing.get("start_date"),
clean["due_date"] if "due_date" in clean else existing.get("due_date"),
)
params.append(project_id)
with self._pool.connection() as conn:
row = conn.execute(
@@ -605,7 +617,9 @@ class ProjectStore:
dd = store.validate_date(due_date)
sti = store.validate_time(start_time)
dti = store.validate_time(due_time)
store.validate_date_range(sd, dd, sti, dti)
assignee = store.norm_str(assignee_email, lower=True)
done_at = None
with self._pool.connection() as conn:
with conn.transaction():
if parent_task_id is not None:
@@ -636,6 +650,13 @@ class ProjectStore:
# 세션이 없어 해당 없음).
if not assignee and stage_id is not None:
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id)
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
if stage_id is not None:
done_row = conn.execute(
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
).fetchone()
if done_row and done_row["is_done_stage"]:
done_at = now_kst()
nxt = conn.execute(
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
"WHERE project_id = %s",
@@ -646,21 +667,26 @@ class ProjectStore:
INSERT INTO tasks
(project_id, stage_id, parent_task_id, title, description,
assignee_email, assignee_name, priority, start_date, due_date,
start_time, due_time, sort_order, created_by)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
start_time, due_time, sort_order, created_by, completed_at)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
RETURNING *
""",
(
project_id, stage_id, parent_task_id, ttl, store.norm_str(description),
assignee, store.norm_str(assignee_name), pr, sd, dd,
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True),
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at,
),
).fetchone()
if assignee:
self._log(conn, project_id=project_id, task_id=row["id"],
actor=created_by, action=store.ACTION_ASSIGNED,
detail=f"{ttl} → {assignee}")
return self.get_task(task_id=row["id"])
if done_at is not None:
self._log(conn, project_id=project_id, task_id=row["id"],
actor=created_by, action=store.ACTION_COMPLETED, detail=ttl)
out = self.get_task(task_id=row["id"])
out["_newly_completed"] = done_at is not None
return out
def move_subtask(
self, *, task_id: int, parent_task_id: int, actor: str = ""
@@ -806,6 +832,15 @@ class ProjectStore:
if not sets:
return {**prev, "_newly_assigned": None, "_newly_completed": False}
# 날짜 범위 — 한쪽만 바꾸거나 지워도 기존 값과 합친 최종 상태로 검사.
if any(k in fields for k in ("start_date", "due_date", "start_time", "due_time")):
def final(key: str, fn: Any) -> Any:
return fn(fields[key]) if key in fields else prev.get(key)
store.validate_date_range(
final("start_date", store.validate_date), final("due_date", store.validate_date),
final("start_time", store.validate_time), final("due_time", store.validate_time),
)
params.append(task_id)
with self._pool.connection() as conn:
with conn.transaction():
@@ -1217,6 +1252,51 @@ class ProjectStore:
).fetchone()
return self._serialize(row)
def add_comment_with_attachments(
self, *, task_id: int, author_email: str, author_name: str, body: str,
files: list[dict[str, Any]], parent_id: int | None = None,
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""댓글과 첨부를 한 트랜잭션에 — 둘 중 하나라도 실패하면 아무것도 남지 않는다
(첨부 없이 빈 댓글만 남던 문제). files = [{filename, stored_name, content_type, size_bytes}].
본문이 비어도 되지만 첨부가 한 개 이상 있어야 한다."""
text = store.norm_str(body)
if not files and not text:
raise ValueError("댓글 내용이 비었습니다.")
author = store.norm_str(author_email, lower=True)
with self._pool.connection() as conn:
with conn.transaction():
root = None
if parent_id:
p = conn.execute(
"SELECT id, task_id, parent_id FROM task_comments WHERE id = %s", (parent_id,)
).fetchone()
if not p or int(p["task_id"]) != int(task_id):
raise ValueError("답글을 달 댓글을 찾을 수 없습니다.")
root = int(p["parent_id"] or p["id"])
if root is not None:
row = conn.execute(
"INSERT INTO task_comments (task_id, author_email, author_name, body, parent_id) "
"VALUES (%s,%s,%s,%s,%s) RETURNING *",
(task_id, author, store.norm_str(author_name), text, root),
).fetchone()
else:
row = conn.execute(
"INSERT INTO task_comments (task_id, author_email, author_name, body) "
"VALUES (%s,%s,%s,%s) RETURNING *",
(task_id, author, store.norm_str(author_name), text),
).fetchone()
atts = []
for f in files:
atts.append(conn.execute(
"INSERT INTO task_attachments "
"(task_id, filename, stored_name, content_type, size_bytes, uploaded_by, comment_id) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING *",
(task_id, store.norm_str(f["filename"]), f["stored_name"],
store.norm_str(f.get("content_type") or "application/octet-stream"),
int(f["size_bytes"]), author, row["id"]),
).fetchone())
return self._serialize(row), [self._serialize(a) for a in atts]
def update_comment(
self, *, comment_id: int, requester: str, is_admin: bool, body: str
) -> dict[str, Any]:
@@ -1655,6 +1735,58 @@ class ProjectStore:
).fetchall()
return [self._serialize(r) for r in rows]
def add_reminder_notification(
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
project_id: int | None, title: str, body: str,
) -> bool:
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
다시 시도된다(예전엔 기록만 남아 영영 안 갔다). 동시에 두 번 돌아도 UNIQUE 로 한 번만."""
rcpt = store.norm_str(recipient_email, lower=True)
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"INSERT INTO task_reminders (task_id, kind, due_date, recipient_email) "
"VALUES (%s,%s,%s,%s) ON CONFLICT DO NOTHING RETURNING id",
(task_id, kind, due_date, rcpt),
).fetchone()
if row is None:
return False
conn.execute(
"INSERT INTO project_notifications "
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
"VALUES (%s,'',%s,%s,%s,%s,%s)",
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)),
)
return True
def task_link_scope(self, *, task_ids: list[int]) -> dict[int, set[int]]:
"""작업 id → 이 작업 또는 그 상위 작업들이 연결(멀티호밍)된 프로젝트 id 집합.
연결된 프로젝트 멤버가 그 작업(과 하위 작업)을 읽기 전용으로 볼 수 있는지 판단한다."""
ids = sorted({int(i) for i in task_ids})
if not ids:
return {}
with self._pool.connection() as conn:
rows = conn.execute(
"""
WITH RECURSIVE chain AS (
SELECT id AS task_id, id AS anc_id, parent_task_id, 0 AS depth
FROM tasks WHERE id = ANY(%s)
UNION ALL
SELECT c.task_id, t.id, t.parent_task_id, c.depth + 1
FROM chain c JOIN tasks t ON t.id = c.parent_task_id
WHERE c.depth < 20
)
SELECT c.task_id, l.project_id
FROM chain c JOIN task_project_links l ON l.task_id = c.anc_id
""",
(ids,),
).fetchall()
out: dict[int, set[int]] = {}
for r in rows:
out.setdefault(int(r["task_id"]), set()).add(int(r["project_id"]))
return out
def record_reminder(
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
) -> bool:
+28 -14
View File
@@ -5,10 +5,11 @@
· due_today — 오늘 마감
· overdue — 마감이 지남(최근 7일 이내 마감분만 — 첫 적용 때 오래된 업무가
한꺼번에 쏟아지지 않게, 연휴로 며칠 건너뛰어도 놓치지 않게)
수신자는 담당자. 담당자가 없으면 팔로워 전원.
수신자는 담당자. 담당자가 없으면 팔로워 전원. 단, 지금 그 작업을 볼 수 있는 사람만.
중복 방지: task_reminders(업무, 종류, 마감일, 수신자) UNIQUE — 같은 알림은 한 번만
간다(재기동·여러 번 실행해도 안전). 마감일을 바꾸면 새 마감일 기준으로 다시 알린다.
발송 기록과 수신함 알림은 한 트랜잭션이라, 알림 생성이 실패하면 다음 실행에 다시 시도된다.
실행 방식: 웹 프로세스 안의 데몬 스레드(start_reminder_thread). 5분마다 깨어나
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
@@ -33,7 +34,7 @@ from typing import Any
from app.timezone import now_kst
from . import store
from . import access, store
logger = logging.getLogger("project.reminders")
@@ -87,8 +88,18 @@ def _title_for(kind: str, task: dict[str, Any], today: date) -> str:
return f"마감 지남({(today - due).days}일): {task['title']}"
def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]:
"""한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다."""
def run_due_reminders(
st: Any, *, today: date | None = None, lookup: access.UserLookup | None = None,
) -> dict[str, int]:
"""한 번 실행. 새로 만든 알림 수를 종류별로 돌려준다.
- 수신자는 지금 그 작업을 볼 수 있는 사람만(access.filter_recipients) — 멤버에서 빠진 담당자·
협업자, 모듈 권한이 없어진 직원에게는 수신함 알림도 메일도 가지 않는다.
- 발송 기록(task_reminders)과 수신함 알림은 한 트랜잭션(add_reminder_notification) — 알림 생성이
실패하면 기록도 되돌려져 다음 실행에서 다시 시도된다. 같은 알림은 UNIQUE 로 한 번만(동시 실행 포함).
- 보장 범위: 수신함 알림까지. 메일(PROJECT_REMINDER_EMAIL)은 알림이 새로 만들어진 것만 요약해 한 번
보내며, 메일 발송 실패는 재시도하지 않는다(수신함 알림은 이미 남아 있다).
"""
today = today or now_kst().date()
start = today - timedelta(days=OVERDUE_WINDOW_DAYS)
end = next_workday(today)
@@ -101,22 +112,25 @@ def run_due_reminders(st: Any, *, today: date | None = None) -> dict[str, int]:
if kind is None:
continue
assignee = store.norm_str(t.get("assignee_email"), lower=True)
recipients = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
try:
recipients = access.filter_recipients(st, t, wanted, lookup)
except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다(다음 실행에 재시도)
logger.warning("마감 알림 수신자 확인 실패: task=%s", t["id"])
continue
for rcpt in recipients:
if not st.record_reminder(
task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt,
):
continue # 이미 보냄
title = _title_for(kind, t, today)
try:
st.add_notification(
recipient_email=rcpt, actor_email="", project_id=t["project_id"],
task_id=t["id"], type=kind, title=title,
created = st.add_reminder_notification(
task_id=t["id"], kind=kind, due_date=t["due_date"][:10], recipient_email=rcpt,
project_id=t["project_id"], title=title,
body=f"{t.get('project_name') or ''} · 마감 {t['due_date'][:10]}",
)
except Exception: # noqa: BLE001
logger.warning("마감 알림 생성 실패: task=%s", t["id"])
except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도
logger.warning("마감 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"])
continue
if not created:
continue # 이미 보냄
counts[kind] += 1
digest.setdefault(rcpt, []).append((title, t))
File diff suppressed because it is too large Load Diff
+33 -3
View File
@@ -313,6 +313,30 @@ def validate_date(d: Any) -> str | None:
return v[:10]
DATE_RANGE_ERROR = "시작일이 마감일보다 늦을 수 없습니다."
TIME_RANGE_ERROR = "같은 날이면 시작 시각이 마감 시각보다 늦을 수 없습니다."
def validate_date_range(
start_date: Any, due_date: Any, start_time: Any = None, due_time: Any = None
) -> None:
"""최종 상태(부분 수정이면 기존 값 + 바꾼 값)의 날짜 범위 검사 — 프로젝트·작업 공용.
둘 다 있으면 start_date <= due_date. 같은 날이고 두 시각이 모두 있으면 start_time <= due_time.
한쪽이 비어 있는 입력은 허용. 값 형식 오류는 validate_date/validate_time 이 먼저 낸다.
"""
sd = validate_date(start_date)
dd = validate_date(due_date)
if sd and dd:
if sd > dd:
raise ValueError(DATE_RANGE_ERROR)
if sd == dd:
st = validate_time(start_time)
dt = validate_time(due_time)
if st and dt and st > dt:
raise ValueError(TIME_RANGE_ERROR)
def validate_time(t: Any) -> str | None:
"""'HH:MM' 형식만 통과(초는 버림). 빈값/None 은 None(=종일)."""
v = norm_str(t)
@@ -334,11 +358,14 @@ def validate_time(t: Any) -> str | None:
# ════════════════════════════════════════════════════════════
GOAL_METRICS: tuple[str, ...] = ("sales", "roas") # 매출 · 로아스
GOAL_KINDS: tuple[str, ...] = ("target", "actual") # 목표 · 실적
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색만(글자는 항상 진한 색).
# 업무 영역 줄 배경색 — 스프레드시트처럼 연한 색 16가지(글자는 항상 진한 색, 8칸×2줄).
# 처음 8색(상품·마케팅·컨텐츠·유통 기본색 포함)은 예전 목록 그대로 들어 있다.
# 빈 문자열 = 색 없음(흰 배경, GOAL_NO_COLOR).
GOAL_AREA_COLORS: tuple[str, ...] = (
"#fbe1d5", "#d9f2d0", "#d4d4d4", "#f0cdec",
"#dbe8fb", "#fff2c2", "#e3dcfb", "#d3f0ee",
"#fcd9d9", "#fde4c8", "#fbe1d5", "#fff2c2", "#eef5c8", "#d9f2d0", "#c9ecd9", "#d3f0ee",
"#cfeaf7", "#dbe8fb", "#e3dcfb", "#f0cdec", "#fcdcec", "#eadcd0", "#d4d4d4", "#eef0f2",
)
GOAL_NO_COLOR = ""
# 새 연도를 만들 때 이전 연도가 없으면 이 영역으로 시작한다(이전 연도가 있으면 그 구조를 복사).
DEFAULT_GOAL_AREAS: tuple[tuple[str, str, tuple[str, ...]], ...] = (
("상품", "#fbe1d5", ("",)),
@@ -401,7 +428,10 @@ def validate_goal_row_label(label: Any) -> str:
def validate_goal_color(color: Any) -> str:
"""영역 색 — 16색 중 하나, 빈값/"none" 은 색 없음(""), 목록 밖은 첫 색."""
v = norm_str(color).lower()
if v in ("", "none"):
return GOAL_NO_COLOR
return v if v in GOAL_AREA_COLORS else GOAL_AREA_COLORS[0]
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -66,8 +66,9 @@
data-admin="{{ 'true' if is_admin else 'false' }}">
<thead>
<tr>
<th class="pj-goal-c1"></th>
<th class="pj-goal-c2"></th>
{# 오른쪽 끝을 끌어 이름 칸 너비 조절 — 브라우저에 기억(localStorage pj_goal_col_w) #}
<th class="pj-goal-c1"><span class="pj-goal-colresize" data-col="c1" title="끌어서 너비 조절"></span></th>
<th class="pj-goal-c2"><span class="pj-goal-colresize" data-col="c2" title="끌어서 너비 조절"></span></th>
<th class="pj-goal-year-col">연간</th>
{% for mo in months %}<th class="{% if mo == this_month %}is-now{% endif %}">{{ mo }}월</th>{% endfor %}
</tr>
@@ -106,7 +107,7 @@
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색 ── #}
{% for area in board.areas %}
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color }}">
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" style="--goal-bg: {{ area.color or '#fff' }}">
{% for row in area.rows %}
<tr data-row-id="{{ row.id }}">
{% if loop.first %}
@@ -168,5 +169,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260930a" defer></script>
<script src="/static/project.js?v=20260930g" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<link rel="stylesheet" href="/static/project-help.css?v=20260926v" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -119,7 +119,9 @@
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
<tr><td>새 프로젝트, 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
<tr><td>멤버 배정·제외</td><td>관리자</td></tr>
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
<tr><td>목표 보기</td><td>누구나 · <b>목표 입력·연도 추가·업무 영역 편집</b>은 관리자</td></tr>
</table>
@@ -263,7 +265,7 @@
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 하위 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다.</td></tr>
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
</table>
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
@@ -301,7 +303,8 @@
</ol>
<p>작업은 하나라서 어느 보드에서 고쳐도 모두 같이 바뀝니다.</p>
<h3>댓글</h3>
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다.</p>
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
</section>
<!-- 9. 작업 창의 하위 작업 -->
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -104,5 +104,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260930a" defer></script>
<script src="/static/project.js?v=20260930g" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20260930a" defer></script>
<script src="/static/project.js?v=20260930g" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -265,6 +265,11 @@
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
</button>
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="작업 제목"></textarea>
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
<span class="material-symbols-outlined">visibility</span>
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 작업이라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
</div>
<div class="pj-modal-body">
<div class="pj-modal-col-main">
@@ -491,5 +496,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20260930a" defer></script>
<script src="/static/project.js?v=20260930g" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20260930a" />
<link rel="stylesheet" href="/static/project.css?v=20260930g" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20260930a" defer></script>
<script src="/static/project.js?v=20260930g" defer></script>
{% endblock %}
+36
View File
@@ -229,3 +229,39 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
.perf-ev-table thead th { background: var(--perf-soft, #fafafa); box-shadow: 0 1px 0 var(--perf-line, #e5e5e5); }
/* 취소 행 — 행 전체를 기울임 + 취소선 + 회색 */
.perf-ev-table tr.is-cancel td { font-style: italic; text-decoration: line-through; color: #9a9a9a; }
/* ── 매출 업데이트 진행 창 — 쇼핑몰별·전체 진행 막대(runSyncWithProgress) ── */
.perf-prog-card { width: min(640px, 100%); }
.perf-prog-row {
display: grid; grid-template-columns: 150px 1fr 44px; align-items: center; column-gap: 10px; row-gap: 3px;
padding: 9px 0; border-bottom: 1px solid var(--perf-line);
}
.perf-prog-name { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.perf-prog-bar { height: 10px; border-radius: 999px; background: #eef0f3; overflow: hidden; }
.perf-prog-bar > span {
display: block; height: 100%; border-radius: inherit; background: var(--perf-sat);
transition: width .5s ease;
}
.perf-prog-pct { font-size: 12px; text-align: right; font-variant-numeric: tabular-nums; color: var(--color-midtone-gray); }
.perf-prog-text { grid-column: 2 / -1; font-size: 12px; color: var(--color-midtone-gray); overflow-wrap: anywhere; }
.perf-prog-row.is-done .perf-prog-bar > span { background: var(--perf-up); }
.perf-prog-row.is-error .perf-prog-bar > span { background: var(--perf-down); }
.perf-prog-row.is-error .perf-prog-text { color: var(--perf-down); }
.perf-prog-row.is-skip .perf-prog-bar > span { background: #b8bec7; }
/* 진행 중인 막대에 흐르는 빗금 — 멈춘 게 아니라는 표시 */
.perf-prog-row:not(.is-done):not(.is-error):not(.is-skip) .perf-prog-bar > span {
background-image: linear-gradient(45deg, rgba(255,255,255,.22) 25%, transparent 25%, transparent 50%,
rgba(255,255,255,.22) 50%, rgba(255,255,255,.22) 75%, transparent 75%, transparent);
background-size: 16px 16px; animation: perf-prog-flow 1s linear infinite;
}
@keyframes perf-prog-flow { from { background-position: 0 0; } to { background-position: 16px 0; } }
.perf-prog-row.is-total { border-bottom: none; border-top: 2px solid var(--perf-line); margin-top: 4px; padding-top: 12px; }
.perf-prog-row.is-total .perf-prog-name { font-weight: 700; }
.perf-prog-row.is-total .perf-prog-bar { height: 14px; }
.perf-prog-row.is-total .perf-prog-pct { font-weight: 700; color: inherit; }
@media (max-width: 560px) { .perf-prog-row { grid-template-columns: 1fr 44px; } .perf-prog-name { grid-column: 1 / -1; } .perf-prog-text { grid-column: 1 / -1; } }
/* [업데이트 취소] — 창 아래 왼쪽, 빨간 글자. 끝나면 숨김 */
.perf-prog-cancel { margin-right: auto; color: var(--perf-down); border-color: currentColor; }
.perf-prog-cancel[hidden] { display: none; }
.perf-prog-cancel:disabled { opacity: .6; cursor: default; }
+167 -12
View File
@@ -76,6 +76,134 @@
return { card: card, body: body, foot: foot, close: close };
}
// ── 매출 업데이트 진행 창 — 서버가 백그라운드로 수집(POST /api/sync background)하는 동안
// GET /api/sync/jobs/{id} 를 0.8초마다 불러 쇼핑몰별·전체 진행 막대를 그린다.
// 창을 닫아도 수집은 서버에서 계속된다. 끝나면 resolve(마지막 상태), 호출 자체가 실패하면 reject.
const SHOP_STATE = { waiting: "대기", running: "수집 중", saving: "저장 중", done: "완료", error: "실패", skipped: "건너뜀",
cancelled: "취소됨" };
function fmtSec(sec) {
sec = Math.max(0, Math.round(sec || 0));
return Math.floor(sec / 60) + ":" + String(sec % 60).padStart(2, "0");
}
function progressRow(name, fraction, text, cls) {
const pct = Math.round((fraction || 0) * 100);
return '<div class="perf-prog-row' + (cls ? " " + cls : "") + '">' +
'<div class="perf-prog-name">' + esc(name) + "</div>" +
'<div class="perf-prog-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' + pct + '">' +
'<span style="width:' + pct + '%"></span></div>' +
'<div class="perf-prog-pct">' + pct + "%</div>" +
'<div class="perf-prog-text">' + text + "</div></div>";
}
function shopText(s) {
let t = SHOP_STATE[s.state] || s.state;
if (s.state === "running" && s.total) t += " " + fmt(s.done) + "/" + fmt(s.total) + s.unit;
if (s.items && s.state !== "done") t += " · 받은 자료 " + fmt(s.items) + "건";
if (s.state === "done") t += " · " + fmt(s.upserted) + "건 반영";
if (s.state === "error") t += " · " + (s.label ? s.label + " — " : "") + (s.message || "");
if (s.state === "skipped") t += " · " + (s.message || "");
if (s.state === "cancelled") t += " · 저장하지 않음(기존 매출 그대로)";
if (s.state === "running" && s.cancel_pending) t += " · 취소하는 중…";
let html = esc(t);
if (s.elapsed && s.state !== "waiting") html += ' <span class="perf-muted">(' + fmtSec(s.elapsed) + ")</span>";
return html;
}
function renderSyncJob(box, job, joined) {
const active = job.shops.filter(function (s) { return s.active; });
const passive = job.shops.filter(function (s) { return !s.active; });
const o = job.overall;
let html = joined ? '<p class="perf-notice">이미 진행 중인 업데이트를 보여 줍니다.</p>' : "";
html += '<p class="perf-muted" style="margin:0 0 10px">기간 ' + esc(job.from || "") + " ~ " + esc(job.to || "") +
" · 경과 " + fmtSec(job.elapsed) + (job.finished ? "" : " · 창을 닫아도 서버에서 계속 진행됩니다") + "</p>";
html += active.map(function (s) {
const cls = s.state === "error" ? "is-error" : s.state === "done" ? "is-done" :
(s.state === "skipped" || s.state === "cancelled") ? "is-skip" : "";
if (job.cancel_requested) s.cancel_pending = true;
return progressRow(s.name, s.fraction, shopText(s), cls);
}).join("");
html += progressRow("전체", o.fraction,
esc((job.cancel_requested ? (job.finished ? "업데이트 취소됨 · " : "취소하는 중 · ") : "") +
fmt(o.finished) + "/" + fmt(o.shops) + " 쇼핑몰 완료" +
(o.items ? " · 받은 자료 " + fmt(o.items) + "건" : "") + (job.finished ? " · " + fmt(o.upserted) + "건 반영" : "")),
"is-total" + (job.finished ? (job.cancel_requested ? " is-skip" : " is-done") : ""));
if (passive.length) {
html += '<p class="perf-muted" style="margin:10px 0 0">건너뜀: ' + esc(passive.map(function (s) {
return s.name + (s.label ? "(" + s.label + ")" : "");
}).join(", ")) + "</p>";
}
if (job.error) html += '<p class="perf-notice is-warn">' + esc(job.error) + "</p>";
box.innerHTML = html;
}
function runSyncWithProgress(payload, title) {
return new Promise(function (resolve, reject) {
let timer = null, closed = false, last = null;
const m = openModal(title || "매출 업데이트", { narrow: true, onClose: function () { closed = true; clearTimeout(timer); if (last) resolve(last); } });
m.card.classList.add("perf-prog-card");
m.body.innerHTML = '<p class="perf-muted">업데이트를 시작하는 중…</p>';
// [업데이트 취소] — 돌고 있는 쇼핑몰은 다음 API 호출 직전에 멈추고(저장 전이면 DB 그대로),
// 이미 저장이 끝난 쇼핑몰 결과는 남는다. 끝나면 숨긴다.
const cancelBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline perf-prog-cancel", hidden: "hidden" }, "업데이트 취소");
const closeBtn = el("button", { type: "button", class: "erp-btn erp-btn-outline" }, "닫기");
closeBtn.addEventListener("click", m.close);
m.foot.appendChild(cancelBtn);
m.foot.appendChild(closeBtn);
let jobId = null;
cancelBtn.addEventListener("click", async function () {
if (!jobId) return;
if (!(await confirmMsg("매출 업데이트를 취소할까요?\n수집 중인 쇼핑몰은 저장하지 않고 멈추고, 이미 끝난 쇼핑몰 결과는 그대로 남습니다."))) return;
cancelBtn.disabled = true;
cancelBtn.textContent = "취소하는 중…";
try {
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
last = r.job;
renderSyncJob(m.body, r.job, false);
} catch (err) {
cancelBtn.disabled = false;
cancelBtn.textContent = "업데이트 취소";
alertMsg("취소 실패: " + err.message);
}
});
api("POST", "/performance/api/sync", Object.assign({ background: true }, payload)).then(function (res) {
last = res.job;
jobId = res.job.id;
const joined = res.joined;
renderSyncJob(m.body, res.job, joined);
if (!res.job.finished) cancelBtn.hidden = false;
if (res.job.cancel_requested) { cancelBtn.disabled = true; cancelBtn.textContent = "취소하는 중…"; }
async function poll() {
if (closed) return;
try {
const r = await api("GET", "/performance/api/sync/jobs/" + encodeURIComponent(res.job.id));
last = r.job;
renderSyncJob(m.body, r.job, joined);
if (r.job.finished) {
cancelBtn.hidden = true;
closeBtn.textContent = "확인";
closeBtn.className = "erp-btn erp-btn-primary";
return;
}
} catch (err) {
m.body.insertAdjacentHTML("beforeend", '<p class="perf-notice is-warn">' + esc(err.message) + "</p>");
return;
}
timer = setTimeout(poll, 800);
}
timer = setTimeout(poll, 500);
}).catch(function (err) {
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
closed = true;
reject(err);
});
});
}
// 끝난 작업 → 기존 결과 줄(반영/실패/건너뜀)에 쓰던 모양
function jobResults(job) {
return (job && job.shops || []).map(function (s) {
return { code: s.code, name: s.name, ok: s.state === "done", skipped: s.state === "skipped",
cancelled: s.state === "cancelled",
upserted: s.upserted, status: s.status, label: s.label, message: s.message, finished: s.state !== "waiting" && s.state !== "running" && s.state !== "saving" };
});
}
// ════════════════════════════════════════════════════
// 대시보드
// ════════════════════════════════════════════════════
@@ -129,14 +257,18 @@
// 지금 보고 있는 기간(오늘까지)을 가져온다 — "이번달"이면 1일부터 오늘까지.
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
const res = await api("POST", "/performance/api/sync", { from: from, to: to });
// 진행 창(쇼핑몰별·전체 막대) — 창을 닫아도 서버에서 계속된다.
const job = await runSyncWithProgress({ from: from, to: to }, "매출 업데이트 " + from + " ~ " + to);
const res = { results: jobResults(job).filter(function (r) { return r.finished; }), last_update_at: job && job.last_update_at };
const running = job && !job.finished;
// 실패(빨강)는 인증 실패·API 오류처럼 손봐야 하는 것만. 인증정보를 아직 안 넣은 쇼핑몰(미설정)과
// 수집을 아직 만들지 않은 쇼핑몰(연동 준비 중)은 회색 한 줄로 이름만.
const ok = [], bad = [], pending = [], unset = [], busy = [];
const ok = [], bad = [], pending = [], unset = [], busy = [], cancelled = [];
let changed = 0;
(res.results || []).forEach(function (r) {
const name = (data.names || {})[r.code] || r.code;
if (r.skipped) busy.push(name);
const name = (data.names || {})[r.code] || r.name || r.code;
if (r.cancelled) cancelled.push(name);
else if (r.skipped) busy.push(name);
else if (r.ok) { ok.push(name + " " + fmt(r.upserted) + "건"); changed += r.upserted; }
else if (r.status === "not_implemented") pending.push(name);
else if (r.status === "not_configured") unset.push(name);
@@ -146,8 +278,10 @@
if (ok.length) parts.push("<b>반영</b> " + esc(ok.join(", ")));
if (bad.length) parts.push("<b>실패</b> " + esc(bad.join(", ")));
if (busy.length) parts.push("<b>이미 진행 중</b> " + esc(busy.join(", ")));
if (cancelled.length) parts.push("<b>취소됨</b>(기존 매출 그대로) " + esc(cancelled.join(", ")));
if (pending.length) parts.push('<span class="perf-muted">연동 준비 중: ' + esc(pending.join(", ")) + "</span>");
if (unset.length) parts.push('<span class="perf-muted">인증정보 미설정: ' + esc(unset.join(", ")) + "</span>");
if (running) parts.unshift("<b>업데이트가 아직 진행 중입니다</b> — 끝나면 다시 [매출 업데이트]를 눌러 결과를 보세요");
resultBox.innerHTML = parts.join(" · ") || "업데이트할 쇼핑몰이 없습니다.";
resultBox.className = "perf-notice" + (bad.length ? " is-warn" : " is-ok");
resultBox.hidden = false;
@@ -155,7 +289,7 @@
const lu = document.querySelector("#perf-last-update b");
if (lu) lu.textContent = res.last_update_at.slice(0, 16).replace("T", " ");
}
if (changed > 0) setTimeout(function () { location.reload(); }, 1200);
if (changed > 0 && !running) setTimeout(function () { location.reload(); }, 800);
} catch (err) {
resultBox.textContent = "업데이트 실패: " + err.message;
resultBox.className = "perf-notice is-warn";
@@ -826,17 +960,21 @@
}
});
// ── 11번가 원본 데이터 확인 — 후보 조회 주소별 동작 여부·항목 합계 ──
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
const probe = document.getElementById("perf-probe");
if (probe) probe.addEventListener("click", async function () {
const day = document.getElementById("perf-probe-date").value;
const out = document.getElementById("perf-probe-result");
if (!day) return;
probe.disabled = true;
out.innerHTML = '<p class="perf-muted">11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)</p>';
const codeSel = document.getElementById("perf-probe-code");
const code = codeSel ? codeSel.value : "elevenst";
const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)",
gsshop: "GS샵에서 불러오는 중… (10일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)";
out.innerHTML = '<p class="perf-muted">' + loading + "</p>";
try {
const to = document.getElementById("perf-probe-to").value || day;
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day) +
const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) +
"&to=" + encodeURIComponent(to));
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
const summary = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
@@ -855,7 +993,21 @@
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
}).join("") + "</tbody></table>";
}).join("");
out.innerHTML = summary + (details || '<p class="perf-muted" style="margin-top:8px">그날 조회된 주문이 없습니다. 셀러오피스에서 매출이 있던 날로 다시 해 보세요.</p>');
// 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
'<table class="perf-table"><thead><tr><th class="perf-th-label">날짜</th><th>주문 수</th><th>매출</th>' +
"<th>" + esc((r.day_cols || {}).claimed || "그중 결제 뒤 취소·반품(참고)") + "</th><th>" +
esc((r.day_cols || {}).ship || "배송비(참고, 매출 제외)") + "</th></tr></thead><tbody>" +
r.days.map(function (d) {
return '<tr><td class="perf-td-label">' + esc(d.date) + '</td><td class="perf-num">' + fmt(d.orders) +
'</td><td class="perf-num">' + fmt(d.amount) + '</td><td class="perf-num">' + fmt(d.claimed || 0) +
'</td><td class="perf-num">' + fmt(d.ship || 0) + "</td></tr>";
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td>' +
["orders", "amount", "claimed", "ship"].map(function (k) {
return '<td class="perf-num"><b>' + fmt(r.days.reduce(function (a, d) { return a + (d[k] || 0); }, 0)) + "</b></td>";
}).join("") + "</tr></tbody></table>" : "";
out.innerHTML = summary + days + (details || '<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
} catch (err) {
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} finally { probe.disabled = false; }
@@ -875,11 +1027,14 @@
backfill.textContent = "가져오는 중…";
box.hidden = true;
try {
const res = await api("POST", "/performance/api/sync", { from: from, to: to });
const job = await runSyncWithProgress({ from: from, to: to }, "과거 매출 가져오기 " + from + " ~ " + to);
const res = { results: jobResults(job).filter(function (r) { return r.finished; }) };
const ok = [], bad = [], rest = [];
if (job && !job.finished) rest.push("(아직 진행 중 — 창을 닫았습니다. 끝나면 대시보드에 반영됩니다)");
(res.results || []).forEach(function (r) {
const name = names[r.code] || r.code;
if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
const name = names[r.code] || r.name || r.code;
if (r.cancelled) rest.push(name + "(취소됨)");
else if (r.ok) ok.push(name + " " + fmt(r.upserted) + "건");
else if (r.skipped) rest.push(name + "(이미 진행 중)");
else if (r.status === "not_implemented" || r.status === "not_configured") rest.push(name);
else bad.push(name + "(" + (r.label || r.status) + ": " + (r.message || "") + ")");
+97 -20
View File
@@ -2010,37 +2010,53 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: 12.5px;
color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px;
}
/* 칸 너비는 여백·테두리 포함(border-box) — 안 그러면 padding 만큼 넓어진다 */
.pj-goal-table th, .pj-goal-table td {
box-sizing: border-box;
border-right: 1px solid #e6e8eb; border-bottom: 1px solid #e6e8eb; padding: 0; vertical-align: top;
}
.pj-goal-table tr > :last-child { border-right: none; }
.pj-goal-table thead th {
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 10px;
font-weight: 700; text-align: left; vertical-align: middle; white-space: nowrap;
font-weight: 700; text-align: center; vertical-align: middle; white-space: nowrap;
}
.pj-goal-table thead th:not(.pj-goal-c1):not(.pj-goal-c2) { width: 150px; min-width: 150px; }
.pj-goal-table thead th.pj-goal-year-col { width: 210px; min-width: 210px; }
.pj-goal-table thead th { width: 85px; min-width: 85px; max-width: 85px; } /* 1~12월 */
.pj-goal-table thead th.pj-goal-year-col { width: 90px; min-width: 90px; max-width: 90px; }
.pj-goal-table thead th.is-now { color: var(--pj-accent-dark); box-shadow: inset 0 -2px 0 var(--pj-accent); }
/* 왼쪽 고정 두 칸(구분·항목) — 너비는 머리 칸 오른쪽 끝을 끌어 조절(initGoals, localStorage
pj_goal_col_w). --goal-c1-w 가 c2 의 left 도 같이 정한다. */
.pj-goal-table { --goal-c1-w: 72px; --goal-c2-w: 72px; }
.pj-goal-c1, .pj-goal-c2 {
position: sticky; z-index: 2; width: 72px; min-width: 72px; max-width: 72px;
background: #fff; text-align: left; font-weight: 700;
position: sticky; z-index: 2; background: #fff; text-align: center; font-weight: 700;
}
.pj-goal-c1 { left: 0; }
.pj-goal-c2 { left: 72px; font-weight: 600; color: #3b4048; }
.pj-goal-table thead .pj-goal-c1, .pj-goal-table thead .pj-goal-c2 { z-index: 4; }
.pj-goal-table tbody th { padding: 7px 8px; }
.pj-goal-c1 { left: 0; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
.pj-goal-c2 {
left: var(--goal-c1-w); width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w);
font-weight: 600; color: #3b4048;
}
.pj-goal-table thead th.pj-goal-c1 { z-index: 4; width: var(--goal-c1-w); min-width: var(--goal-c1-w); max-width: var(--goal-c1-w); }
.pj-goal-table thead th.pj-goal-c2 { z-index: 4; width: var(--goal-c2-w); min-width: var(--goal-c2-w); max-width: var(--goal-c2-w); }
.pj-goal-colresize {
position: absolute; top: 0; right: -4px; bottom: 0; width: 8px; z-index: 5; cursor: col-resize;
}
.pj-goal-colresize::after {
content: ""; position: absolute; top: 6px; bottom: 6px; left: 3px; width: 2px; border-radius: 2px; background: transparent;
}
.pj-goal-colresize:hover::after, .pj-goal-colresize.is-dragging::after { background: var(--pj-accent); }
html.pj-goal-resizing, html.pj-goal-resizing * { cursor: col-resize !important; user-select: none !important; }
.pj-goal-table tbody th { padding: 7px 8px; vertical-align: middle; } /* 왼쪽 이름은 세로 가운데 */
/* 숫자 지표 */
.pj-goal-kpi td { height: 32px; vertical-align: middle; }
.pj-goal-kpi td.is-now { background: #faf9ff; }
input.pj-goal-num, span.pj-goal-num {
display: block; width: 100%; box-sizing: border-box; height: 32px; padding: 0 10px; border: none;
display: block; width: 100%; box-sizing: border-box; height: 32px; padding: 0 6px; border: none;
background: transparent; font: inherit; font-variant-numeric: tabular-nums; text-align: right; line-height: 32px;
}
input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: #fff; }
.pj-goal-sum { padding: 0 10px !important; text-align: right; font-weight: 700; background: #fafafb;
.pj-goal-sum { padding: 0 6px !important; text-align: right; font-weight: 700; background: #fafafb;
font-variant-numeric: tabular-nums; }
.pj-goal-rate { padding: 0 10px !important; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
.pj-goal-rate { padding: 0 6px !important; text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; }
.pj-goal-rate.is-good { color: #1f8a4c; }
.pj-goal-rate.is-low { color: #c2410c; }
.pj-goal-kpi tr:last-child > * { border-bottom: 2px solid #d5d9de; }
@@ -2050,19 +2066,27 @@ input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -
.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
.pj-goal-area-name { font-size: 13px; font-weight: 800 !important; }
.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; }
.pj-goal-tools { display: flex; flex-wrap: wrap; gap: 0; margin-top: 4px; opacity: 0; transition: opacity .12s; }
/* 관리자 도구(✎ 색 ↑ ↓ + ×) — 이름 칸 아래에 떠 있는 작은 막대. 자리를 차지하지 않아야
이름이 세로 가운데에 온다. 칸 안에 붙어 있어 마우스를 막대로 옮겨도 사라지지 않는다. */
.pj-goal-area-name:hover, .pj-goal-row-label:hover, .pj-goal-area-name:focus-within, .pj-goal-row-label:focus-within { z-index: 6; }
.pj-goal-tools {
position: absolute; top: calc(100% - 6px); left: 50%; transform: translateX(-50%); z-index: 7;
display: flex; flex-wrap: nowrap; gap: 1px; padding: 3px; background: #ffe3c7; border: 1px solid #f6c69a;
border-radius: 10px; box-shadow: 0 4px 12px rgba(16, 24, 40, .14); /* 파스텔 주황 */
opacity: 0; pointer-events: none; transition: opacity .12s;
}
.pj-goal-area-name:hover .pj-goal-tools, .pj-goal-row-label:hover .pj-goal-tools,
.pj-goal-tools:focus-within { opacity: 1; }
.pj-goal-tools .pj-icon-btn { width: 20px; height: 20px; font-size: 13px; }
.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 15px; }
.pj-goal-tools .pj-icon-btn:hover { background: rgba(255, 255, 255, .7); }
.pj-goal-tools:focus-within { opacity: 1; pointer-events: auto; }
.pj-goal-tools .pj-icon-btn { width: 30px; height: 30px; font-size: 20px; color: #8a4b14; border-radius: 7px; }
.pj-goal-tools .pj-icon-btn .material-symbols-outlined { font-size: 22px; }
.pj-goal-tools .pj-icon-btn:hover { background: #ffc98f; color: #5c2e06; }
textarea.pj-goal-text {
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 7px 9px; border: none;
display: block; width: 100%; box-sizing: border-box; min-height: 46px; padding: 6px; border: none;
background: transparent; font: inherit; line-height: 1.5; color: inherit; resize: none; overflow: hidden;
}
textarea.pj-goal-text:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .75); }
textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
.pj-goal-text-ro { min-height: 46px; padding: 7px 9px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
.pj-goal-text-ro { min-height: 46px; padding: 6px; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }
.pj-goal-area td.is-now { box-shadow: inset 2px 0 0 rgba(123, 104, 238, .35), inset -2px 0 0 rgba(123, 104, 238, .35); }
.pj-goal-texttd.pj-goal-year-col { font-weight: 600; }
@@ -2073,10 +2097,63 @@ textarea.pj-goal-text::placeholder { color: rgba(0, 0, 0, .3); }
/* 영역 색 고르기 팝업(body 에 붙음) */
.pj-goal-colorpop {
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(4, 26px); gap: 6px;
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
padding: 10px; background: #fff; border: 1px solid var(--pj-border); border-radius: 10px;
box-shadow: 0 8px 24px rgba(16, 24, 40, .16);
}
.pj-goal-swatch { width: 26px; height: 26px; border-radius: 6px; border: 1px solid rgba(0, 0, 0, .12); cursor: pointer; padding: 0; }
.pj-goal-swatch:hover { transform: scale(1.08); }
.pj-goal-swatch.is-on { outline: 2px solid var(--pj-accent); outline-offset: 1px; }
/* 맨 위 "색 없음" — 한 줄 전체, 흰 칸에 빨간 사선 */
.pj-goal-swatch-none {
grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 8px;
border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; color: var(--pj-ink);
font-size: 12.5px; cursor: pointer;
}
.pj-goal-swatch-none:hover { background: #f6f7f8; }
.pj-goal-swatch-none.is-on { outline: 2px solid var(--pj-accent); outline-offset: 1px; }
.pj-goal-swatch-x {
width: 16px; height: 16px; border: 1px solid rgba(0, 0, 0, .2); border-radius: 4px; background:
linear-gradient(to top right, transparent calc(50% - 1px), #e5484d calc(50% - 1px), #e5484d calc(50% + 1px), transparent calc(50% + 1px));
}
/* ════════════════════════════════════════════════════════════
권한·저장 안전장치(2026-09-30)
════════════════════════════════════════════════════════════ */
/* 읽기 전용 안내줄 — 다른 프로젝트에서 연결돼 온 작업(원 소속 권한 없음) */
.pj-readonly-note {
display: flex; align-items: center; gap: 6px; margin: 4px 0 8px; padding: 7px 10px;
border-radius: 8px; background: #f1f5fb; color: #34507a; font-size: 12.5px; line-height: 1.4;
}
.pj-readonly-note[hidden] { display: none; }
.pj-readonly-note .material-symbols-outlined { font-size: 17px; }
.pj-modal.is-readonly .pj-t-title-input { cursor: default; }
.pj-modal.is-readonly .pj-desc-editor { background: #fafbfc; }
.pj-subtask-row.is-readonly .pj-subtask-check,
.pj-subtask-row.is-readonly .pj-subtask-due,
.pj-subtask-row.is-readonly .pj-subtask-av { cursor: default; opacity: .7; }
/* 이 프로젝트 권한을 잃었을 때 화면 위 안내 */
.pj-access-lost {
margin: 0 0 10px; padding: 10px 14px; border-radius: 8px; background: #fdecea; color: #a1261b;
font-size: 13px; font-weight: 600;
}
.pj-access-lost a { color: inherit; text-decoration: underline; margin-left: 6px; }
/* 저장 실패 — 눌러서 다시 시도 */
.pj-autosave-state.is-retry { cursor: pointer; text-decoration: underline dotted; }
/* 작업 창 댓글의 첨부(파일만 있는 댓글도 보이게) */
.pj-comment-atts { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
.pj-comment-att { display: inline-flex; align-items: center; gap: 5px; text-decoration: none; color: var(--pj-ink); }
.pj-comment-att-file {
padding: 4px 8px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font-size: 12.5px;
}
.pj-comment-att-file:hover { background: #f6f7f8; }
.pj-comment-att-img img {
display: block; max-width: 160px; max-height: 120px; border-radius: 6px; border: 1px solid var(--pj-border);
object-fit: cover;
}
/* 첨부 파일 목록에서 댓글에 붙은 파일 표시 */
.pj-attach-from-comment {
margin-left: 6px; padding: 0 6px; border-radius: 999px; background: #eef0f2; color: #525860; font-size: 11px;
}
/* 댓글 대화창 — 보낼 수 없었던 파일(빈 파일·20MB 초과) */
.pj-chat-pending-chip.is-failed { border-color: #e5484d; background: #fdecea; color: #a1261b; }
+693 -146
View File
File diff suppressed because it is too large Load Diff
+57 -1
View File
@@ -29,7 +29,7 @@
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵 = **구현됨**, 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 단계에서 공식 API 문서로 확정**한다.
### 카페24 (`adapters/cafe24.py`, 구현됨)
@@ -102,6 +102,51 @@
- `replace_range` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜
금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다.
### 네이버 스마트스토어 (`adapters/naver.py`, 구현됨)
- 인증: 커머스API센터 애플리케이션 ID·시크릿 → 전자서명 `client_secret_sign = base64(bcrypt.hashpw("{client_id}_{timestamp ms}",
client_secret))` → `POST https://api.commerce.naver.com/external/v1/oauth2/token`(form: client_id·timestamp·client_secret_sign·
grant_type=client_credentials·type=SELF, 판매자 ID 입력 시 type=SELLER+account_id). 토큰(약 3시간)은 `access_token`·
`access_token_expires_at`(internal, 암호화)으로 저장해 만료 5분 전까지 재사용, 401 이면 한 번 새로 받아 다시 호출.
[연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. **애플리케이션의 API 호출 IP 에 운영 서버 외부 IP 등록 필요.**
의존성 `bcrypt`(requirements.txt).
- 수집: 조건형 상품 주문 상세 조회 `GET /v1/pay-order/seller/product-orders?from=&to=&rangeType=PAYED_DATETIME&pageSize=100&page=`
— 한 번에 **24시간까지**(하루씩 0시~23:59:59.999 +09:00), from 부터 180일 안 주문만(네이버 안내, GitHub discussions #1875·#2380).
응답 모양은 `data.contents[].content.{order, productOrder, …}` 로 보고 목록·`content` 유무가 달라도 받는다(`product_order_items`),
다음 쪽은 `pagination.hasNext`(없으면 100건 꽉 차면). 호출 간격 0.35초, 429 는 1·2·4초 쉬고 다시.
- **매출 규칙 = 스마트스토어센터 판매분석 "판매금액(총)"**(2026-09-30 사용자 확인): 판매분석 9/1 매출 4,455,600원 = 판매금액(총) —
할인(판매자·네이버 부담) 뒤 금액, **배송비(332,486원)는 별도**, 결제 뒤 취소·반품도 결제일에 포함하고 환불(346,340원)은 **환불일**에
따로 빼서 판매금액(순) 4,109,260원(예: 9/1 결제 0원인 상품에 환불 5건 75,040원). 주방세제 2.3L 16,640 = 17,900 − 네이버 부담 1,260.
처음 규칙(취소·반품 빼고 배송비 더함)은 4,245,300원으로 달랐다.
- SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(`order.paymentDate`), 금액 = 상품주문 `totalPaymentAmount` 합(배송비 제외),
할인 = `productDiscountAmount` 합. 결제 뒤 취소·반품(`CANCELED`·`RETURNED`)도 포함, 입금대기·미입금 취소만 뺀다
→ 지난 날짜 매출이 나중에 줄지 않는다. `replace_range`.
- 환불(판매금액(순))은 아직 사건으로 만들지 않는다 — 필요하면 클레임 완료일 기준 CANCEL/RETURN 을 추가.
- 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별
매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만.
### GS샵 (`adapters/gsshop.py`, 구현됨)
- 문서: 협력사 포털 → 제휴 API → 개발가이드(`partners.gsshop.com/api/apiDevGuide`, 본문은 `/docs/withgs-api-docs.html` Redoc).
- 인증: 헤더 `supCd`(협력사코드) + `token` = base64(AES256(`yyyyMMddHHmmss` + 협력사코드)), 키는 제휴 API 메인 화면(로그인 후).
키 = 포털 제휴 API 메인의 **운영 KEY**(개발 KEY 아님). 문서에 암호화 모드·키를 바이트로 쓰는 법이 없어 키 변형(글자 그대로 /
16진수 풀기 / 앞 32자, `key_variants`) × 모드(CBC·IV=키 앞 16 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억.
토큰이 틀리면 **HTTP 200** + `{"result":"fail","code":"401 UNAUTHORIZED"}`. 운영 주소 `withgs-api.gsshop.com`(문서 예시
`atwithgs-api` 는 테스트용 — 두 곳 모두 응답). 입력칸 키는 처음 만든 `vendor_code`·`api_key` 그대로(라벨만 협력사코드·AES256 키).
- 매출: `GET /api/v2/settlement/out/sales/period?supCode&fromDate&toDate&pageIdx&rowsPerPage` — **매출인식일** 기준, 한 번에 10일,
쪽당 1만 건, `{data, hasMorePage, totalCount}`. 배송비는 `/shippingFee/period`. 응답 줄 항목 이름이 문서 예시에 없어
("property1") 실데이터로 확인(2026-09-30, 9/3): `saleAwareDt`·`ordNo`·`ordItemNo`·`ordType`(SALE…)·`prdNm`·`chrQty`·
`salePrice`(할인 전, 줄 합계)·`dcTotAmt`·`custChrAmt`(= salePrice − dcTotAmt, 고객 결제금액)·`supGiveAmt`(협력사 지급액).
9/3: 211,100 − 19,528 = 191,572, 지급 179,435, 배송비 내역 7,000.
- **주문일 기준 조회 API 는 없다** — 협력사 포털 주문 통계(총주문금액·주문일, 할인 후 금액: 45,900 × 85% = 39,015)와는 날짜 기준이
달라 날마다 똑같이 맞지 않는다(매출인식일 = 정산 기준).
- **매출 규칙**: 매출 내역 한 줄 = 사건(`gs:{ordNo}-{ordItemNo}-{ordType}-{saleAwareDt}`), 날짜 = 매출인식일,
금액 = **`supGiveAmt`(협력사 지급액)** = 협력사 포털 주문 통계의 금액(2026-09-30 확인: 6호세트 포털 176,715 ÷ 9 = 19,635 = API
supGiveAmt 19,635 — 판매가 23,100·고객 결제 20,330. 7호세트 45,900 × 85%, 주부체험 9,900 × 90% — 상품마다 GS 수수료율이 다름).
9/1~9/29 지급액 4,972,689 vs 포털 순주문 4,823,074 — 남는 차이는 주문일 ↔ 매출인식일·취소분. 이미 GS 수수료를 뺀 금액이라
**GS샵 수수료율은 0%**. 배송비 제외, `ordType` 이 SALE 이 아니면 RETURN 음수. `replace_range`.
원본 데이터 확인에 날짜별 현재 규칙 매출·취소/반품·배송비(참고).
### 연동 단계 체크리스트(쇼핑몰마다)
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
@@ -164,6 +209,17 @@
- **대시보드 [매출 업데이트]** = 지금 보고 있는 기간(오늘까지)을 `POST /api/sync {from, to}` 로 다시 가져온다
("이번달"이면 1일~오늘). 모듈 권한자는 92일까지, 더 긴 기간(올해 등, 최대 366일)은 관리자만.
- **과거 매출 가져오기**(설정 화면, 관리자): 같은 API 로 임의 기간(최대 366일). 같은 사건은 덮어써서 여러 번 해도 중복 없음.
- **진행 창**(두 버튼 공통, `runSyncWithProgress`): `POST /api/sync {…, background: true}` → 수집을 스레드로 돌리고 작업 번호를
바로 돌려줌 → 화면이 `GET /api/sync/jobs/{id}` 를 0.8초마다 불러 **쇼핑몰별 막대 + 전체 막대**를 그린다(`jobs.py`, 메모리 보관 —
uvicorn 단일 워커 기준, 서버 재시작 시 진행 정보만 사라짐). 어댑터가 `ctx.progress.plan(전체, 단위)`/`step(items=)`/`add(n)` 로
알린다 — 네이버 = 일, 11번가 = 7일 구간(정산 + 주문 상태 4개), 카페24 = 60일 구간(결제·환불·환불 없는 취소 2종, 대조 필요 시 +).
상태: 대기 → 수집 중 n/전체 · 받은 자료 → 저장 중 → 완료 n건 반영 | 실패 | 건너뜀. 수집이 없거나 인증정보가 없는 쇼핑몰은
막대에서 빼고 "건너뜀" 한 줄(전체 진행률에 안 넣음). 전체 = 막대 쇼핑몰 진행률 평균. 이미 돌고 있는 업데이트가 있으면 새로 시작하지
않고 그 진행 상황을 보여 준다(`GET /api/sync/current`). 창을 닫아도 수집은 계속된다.
- **[업데이트 취소]**(진행 창 왼쪽 아래, 시작한 사람·관리자, `POST /api/sync/jobs/{id}/cancel`): 돌고 있는 쇼핑몰은 다음 API 호출
직전(`ctx.progress.check()` → `Cancelled`)에 멈추고 **저장하지 않는다**(저장은 수집이 끝난 뒤 한 트랜잭션이라 기존 매출 그대로),
차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다. 이미 저장이 끝난 쇼핑몰 결과는 남고, 저장 중이던 쇼핑몰은 그 저장을 끝낸다.
취소된 실행은 `perf_sync_runs` 에 failed + "업데이트 취소", 연결 상태(`perf_connection_status`)는 바꾸지 않는다.
- 카페24 **환불합계 규칙(확정, 2026-09-29 실데이터)**: 카페24 "일별 매출내역" 환불합계 = 환불 목록의 (실제 환불액 + 적립금·예치금 환불)
+ 환불 목록에 없는 취소·반품(네이버페이 등, 취소일 기준). 9/26 = 178,220 + 1,080 + 네이버페이 취소 96,500 = 275,800,
9/27 = 145,000 + 네이버페이 55,800 = 200,800 으로 일치. 대조 도구에 환불합계 후보(값 입력 시 일치 줄 강조)·환불 건별·
+79 -7
View File
@@ -33,11 +33,13 @@
| 연결 env | `PROJECT_DB_URL` (미설정 시 "설정 필요" 안내, 앱은 죽지 않음) |
| 진입 권한 | 권한키 `project` (관리자 페이지 토글로 직원별 부여, admin 자동) |
| 멤버 배정 후보 | `project` 권한 보유 등록 사용자 자동 목록 (`GET /project/api/assignable-users`) |
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. |
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`) |
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다 |
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다 |
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일 |
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 건 관리자만(비관리자가 `owner_email` 을 남으로 보내면 403) |
| 소유자 변경 | **관리자만**(2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
| 지금 권한 기준 | 모든 판단은 **지금** 권한(`app/modules/project/access.py`) — 멤버에서 빠진 사람은 예전 담당자·멘션·협업자 기록이 있어도 내 작업·수신함·알림·검색·상세·공유 링크·댓글·첨부에서 그 작업이 보이지 않고, 새 알림·메일도 받지 않는다(기록은 이력으로 남김) |
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다. 새 담당자는 그 프로젝트를 볼 수 있는 사람만(400). 날짜 범위(시작 ≤ 마감, 같은 날이면 시작 시각 ≤ 마감 시각)는 부분 수정도 기존 값과 합친 최종 상태로 검사(400) |
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일. **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
| 멤버 배정 | 여전히 관리자(`is_admin`) 전용. 비관리자가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
| 메일 알림 | `app/mail.py` (stdlib smtplib). 작업 배정/완료 시 관리자에게 발송 |
@@ -487,11 +489,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
(`initGoalSide`, localStorage `pj_goal_open`, 목표 화면에선 항상 펼침). 연도 목록은 `router._goal_years_nav`
(`goal_years` 최근 연도 먼저 + **올해는 항상**, 013 미적용이면 올해만) — 사이드바를 그리는 모든 화면 컨텍스트에 `goal_years`.
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
이번 달 열 강조.
이번 달 열 강조. 월 칸 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`), 머리·왼쪽 이름 가운데 정렬(왼쪽 이름은 세로도 가운데 — 관리자 도구는 칸 아래에 떠 있는 막대라 자리를 차지하지 않음). 왼쪽 이름 두 칸(구분·항목)은 머리 칸 오른쪽 끝을 끌어 너비 조절(48~320px, 더블클릭 = 72px) — 브라우저별 localStorage `pj_goal_col_w`, CSS 변수 `--goal-c1-w`·`--goal-c2-w`.
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, 연간은 실적이 있는 달의 목표 합계 대비)는
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 8색·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 관리자만**(`_require_admin`, 화면도 관리자에게만 입력칸·도구).
- 연도 추가(`POST /api/goals/years {year}`)는 가장 가까운 이전 연도(없으면 다음 연도)의 영역·줄 구조를 글 없이 복사,
@@ -507,6 +509,76 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
영역 색은 팝업(body 에 붙임)에서 바로 바뀜. 목표 테이블은 live-version 트리거에 넣지 않았다(입력 중 새로고침 방지).
- 추후: 매출 실적을 실적 모듈(`performance_db`)에서 월별로 자동으로 채우기.
## 6-10. 권한·저장 안전장치 (2026-09-30 점검 반영, 새 마이그레이션·환경변수 없음)
**권한 공통 기준 — `access.py`** (라우터·마감 알림이 같은 규칙)
- 프로젝트 관리 = 관리자 · owner · 배정 멤버, 모두 `project` 모듈 권한이 있어야 한다(`can_manage_project`).
- 작업 권한 `task_access`: **FULL** = 원 소속 프로젝트 관리 가능 / **READ** = 원 소속 권한은 없지만 이 작업(또는 상위 작업)이
연결된 프로젝트를 관리 가능(`task_link_scope`, 재귀 CTE) / 없음. 라우터 `_require_task(write=)` 가 FULL/READ 를 검사.
- READ 로 되는 것: 작업 상세(`access:"read"`)·하위 작업 목록·댓글 목록·첨부 목록/다운로드/미리보기·공유 링크(연결된 프로젝트
화면으로 이동). 안 되는 것: 제목·설명·담당자·완료·섹션(원 소속)·댓글/답글/반응·첨부 추가/삭제·협업자·삭제·하위 작업 변경.
이미 연결된 작업을 연결된 프로젝트 안에서 섹션 이동(`POST /links`)은 예전처럼 허용, 새 연결은 양쪽 권한. 상세의 `links` 는
내가 볼 수 있는 프로젝트만(다른 연결 프로젝트 이름도 숨김), `followers` 는 READ 면 null. 원 소속의 다른 작업·멤버는 계속 403.
- 목록·배지·알림: 내 작업(`_my_visible_tasks`/`_my_open_count`)·수신함 태그(`_safe_mentions`)·알림(`_visible_notifications`)을
지금 권한으로 거른다(FULL 또는 READ). 기존 기록은 지우지 않는다.
- 알림·메일·멘션 수신자: `filter_recipients` — 지금 그 작업을 볼 수 있는 등록 사용자만(담당자·협업자여도 권한을 잃었으면 제외).
@태그는 볼 수 없는 사람(비멤버·권한 회수·미등록 이메일)을 기록·알림·자동 협업자 등록 없이 건너뛰고 응답 `mention_skipped` 로
알려 준다(payload 에 이메일을 직접 넣어도 같음). 멘션이 권한을 만들지 않는다. 태그 후보 `GET /api/all-users?task_id=`.
- 새 담당자는 그 프로젝트를 볼 수 있는 사람만(`_check_assignee`, 400). 비우거나 예전 값 유지는 허용.
- 댓글 수정·삭제도 지금 원 소속 권한이 있어야 한다(작성자라도 멤버에서 빠지면 403). 첨부는 본인 댓글에만 붙일 수 있다.
**저장·동기화**
- 작업 창 세대(`taskGen`): 창을 열 때마다 +1. 상세·하위 작업·연결·첨부·댓글·담당자 후보·저장 결과는 요청 때 세대를 잡고, 돌아왔을
때 다르면 반영하지 않는다(A→B, A→B→A). 하위 작업·연결 블록도 자체 `ctxSeq` 로 늦은 응답을 버리고, 추가·연결은 누른 순간의
작업 id 로 보낸다. 설명 이미지 업로드는 시작한 작업·세대가 바뀌었으면 설명에 넣지 않는다(파일은 원래 작업 첨부로 남음).
- 자동 저장(`saveField`)은 성공/실패를 돌려준다. 실패한 칸은 `failedFields` 에 남고 "저장 실패 · 다시 시도"(눌러 재시도).
닫기·Esc·다른 작업 열기(`openTaskModal` → `settleBeforeLeave`)는 이미지 업로드·만들기·저장 큐가 끝나길 기다리고 실패한 칸을
한 번 더 보낸 뒤, 그래도 실패하면 "버리고 넘어가기 / 계속 편집"을 묻는다. 버리기를 고를 때만 초안을 버린다(`discardTaskEdits`).
저장 성공 뒤 화면 다시 그리기 오류는 저장 실패로 표시하지 않는다. 미저장(실패·대기·업로드 중)일 때만 페이지 이탈 경고.
- 읽기 전용 작업 창: 제목·설명·담당자·섹션·우선순위·마감일 잠금, 완료·삭제·댓글 입력·첨부 추가·서식 도구·하위 작업 추가·
연결 추가/해제 숨김, 안내줄 `#pj-t-readonly`. 댓글 대화창도 `GET /comments` 의 `access` 로 입력칸을 숨긴다.
- 실시간 동기화(`initLiveRefresh`): `observed`(서버에서 본 버전)와 `applied`(화면에 반영 성공한 버전)를 나눈다. 반영이
성공해야 applied 를 올리고, 실패하면 다음 주기(8→16→32→60초)에 같은 버전을 다시 받는다. 동기화 중엔 겹쳐 돌지 않고, 늦게 온
응답은 버린다(`syncSeq`). 프로젝트 화면은 `GET /api/projects/{id}/snapshot?scope=all` — 화면이 들고 있는 범위(볼 수 있는 모든
최상위 프로젝트의 작업·섹션·프로젝트 목록)를 통째로 바꿔 끼운다(다른 프로젝트의 생성·삭제·섹션 변경·권한 회수 반영, 멀티호밍은
`context_project_id` 별 한 행). 이 프로젝트 권한을 잃으면(403) 작업을 비우고 창을 닫고 안내줄 `.pj-access-lost`.
- 날짜: 업무 기준 "오늘" = 한국시간(`kstTodayIso`, UTC+9 고정) — 대시보드 지연 수·마감 색·오늘/내일·내 작업 필터가 브라우저
시간대와 무관하게 서버(`today_kst`)·마감 알림과 같다.
**댓글 파일** — 파일이 있는 댓글은 `POST /api/tasks/{id}/comments/files`(multipart: `files[]`·`body`·`parent_id`·`mentions`(JSON)·
`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도
있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지.
DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다.
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준).
작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시.
**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면
기록도 되돌려져 다음 실행에서 다시 시도, 동시 실행도 UNIQUE 로 한 번만. 수신자는 지금 볼 수 있는 사람만. 보장 범위는 수신함
알림까지 — 메일(`PROJECT_REMINDER_EMAIL`)은 새로 만든 알림만 요약해 보내고 메일 실패는 재시도하지 않는다.
**완료 섹션에 바로 만든 작업** — `create_task` 가 완료 섹션이면 `completed_at`·완료 이력(1건)을 넣고, 라우터가 완료 섹션 이동과
같은 완료 알림(`_notify_completed`)을 보낸다. 섹션 없는 하위 작업·수동 완료/취소는 그대로.
**테스트** — `tests/test_project_module.py`(로컬 테스트용 PostgreSQL + FastAPI TestClient, `PROJECT_TEST_DB_URL` 가
localhost 일 때만), `tests/js/project_ui.test.js`(jsdom, `python tests/js/render_project.py` 후 실행, `PJ_TEST_TZ` 로 해외 시간대).
프런트 테스트 훅은 `window.__PJ_TEST__` 가 있을 때만 열린다.
**기존 데이터 점검(조회만 — 운영 교정은 따로 승인 후)**
```sql
-- 시작일 > 마감일(프로젝트·작업), 같은 날 시각 역전
SELECT id, name, start_date, due_date FROM projects WHERE start_date > due_date;
SELECT id, project_id, title, start_date, due_date, start_time, due_time FROM tasks
WHERE start_date > due_date OR (start_date = due_date AND start_time > due_time);
-- 본문도 첨부도 없는 빈 댓글(예전 파일 업로드 실패 흔적)
SELECT c.id, c.task_id, c.author_email, c.created_at FROM task_comments c
WHERE btrim(c.body) = '' AND NOT EXISTS (SELECT 1 FROM task_attachments a WHERE a.comment_id = c.id);
-- 완료 섹션에 있는데 미완료인 작업(예전 완료 섹션 직접 생성)
SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id
WHERE s.is_done_stage AND t.completed_at IS NULL;
```
교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다.
권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다).
## 7. 추후 단계
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
+2
View File
@@ -12,6 +12,8 @@ pdfplumber>=0.11
pillow>=10.0
# 카페24 OAuth 토큰 암호화 저장(Fernet) — app/integrations/cafe24/crypto.py
cryptography>=42.0
# 네이버 커머스API 토큰 전자서명(client_secret_sign) — app/modules/performance/adapters/naver.py
bcrypt>=4.1
google-api-python-client>=2.100
google-auth>=2.30
# refresh token 발급 스크립트(scripts/google_sheets_authorize.py) 전용
+425
View File
@@ -0,0 +1,425 @@
// 프로젝트 관리 화면(project/project.html + static/project.js) UI 회귀 테스트 — jsdom.
// 서버 응답은 가짜(fetch 대체)로, 지연·실패·순서 역전을 직접 만든다. 실제 브라우저 레이아웃·입력기는 아니다.
//
// python tests/js/render_project.py # 템플릿 렌더 → tests/js/.out/project_render.html
// npm install jsdom # (최초 1회)
// TZ=America/Los_Angeles node tests/js/project_ui.test.js # 해외 시간대 브라우저 흉내
//
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
// Git Bash 는 윈도우 프로그램에 TZ 를 넘기지 않아 PJ_TEST_TZ 로도 받는다(날짜 객체를 만들기 전에 설정).
if (process.env.PJ_TEST_TZ) process.env.TZ = process.env.PJ_TEST_TZ;
const fs = require("fs");
const path = require("path");
const { JSDOM } = require("jsdom");
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 90000);
const ROOT = path.join(__dirname, "..", "..");
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.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); }
}
function deferred() {
let resolve, reject;
const p = new Promise(function (a, b) { resolve = a; reject = b; });
return { promise: p, resolve: resolve, reject: reject };
}
function makeEnv() {
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
const w = dom.window, d = w.document;
w.__PJ_TEST__ = true;
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
w.URL.createObjectURL = function () { return "blob:x"; };
w.URL.revokeObjectURL = function () {};
w.Image = function () { const self = this; Object.defineProperty(self, "src", { set: function () { setTimeout(function () { if (self.onerror) self.onerror(); }, 0); } }); };
w.console.error = function () {};
let confirmAnswer = false;
w.erpConfirm = function () { env.confirms++; return Promise.resolve(confirmAnswer); };
w.erpAlert = function (m) { env.alerts.push(m); };
w.alert = function (m) { env.alerts.push(m); };
// 8초 이상 타이머(실시간 새로고침)는 붙잡아 두고 테스트가 직접 돌린다.
const realSetTimeout = w.setTimeout.bind(w);
const slow = [];
w.setTimeout = function (fn, ms) {
if (ms >= 8000) { slow.push({ fn: fn, ms: ms }); return 999000 + slow.length; }
return realSetTimeout(fn, ms);
};
const env = {
w: w, d: d, calls: [], routes: [], slow: slow, confirms: 0, alerts: [],
setConfirm: function (v) { confirmAnswer = v; },
route: function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); },
runSlow: async function () { const t = slow.shift(); if (t) { t.fn(); await settle(); } return t; },
};
w.fetch = async function (url, opts) {
const method = (opts && opts.method) || "GET";
let body = opts && opts.body;
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
env.calls.push({ method: method, url: String(url), body: body });
if (process.env.PJ_TEST_TRACE && method === "PUT") console.log(" TRACE PUT", url, new Error().stack.split("\n").slice(2, 7).join(" | "));
for (const r of env.routes) {
if (r.method === method && r.re.test(String(url))) {
const out = await r.fn(String(url), body);
if (out === "NETWORK") throw new TypeError("Failed to fetch");
const status = out.status || 200;
return { ok: status < 400, status: status, statusText: "x", json: async function () { return out.body; } };
}
}
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; } };
};
return env;
}
function settle(n) {
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 30)) return r(); setImmediate(spin); })(); });
}
function detail(id, title, extra) {
return Object.assign({ id: id, title: title, project_id: 1, stage_id: 11, description: "", priority: "normal",
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null }, extra || {});
}
function baseRoutes(env) {
env.route("GET", /\/project\/api\/tasks\/\d+\/attachments/, function () { return { body: { attachments: [] } }; });
env.route("GET", /\/project\/api\/tasks\/\d+\/comments/, function () { return { body: { comments: [], events: [], features: {} } }; });
env.route("GET", /\/project\/api\/projects\/\d+\/members/, function () { return { body: { members: [{ user_email: "me@test.local" }] } }; });
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [] } }; });
env.route("GET", /\/project\/api\/all-users/, function () { return { body: { users: [] } }; });
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: "v1" } }; });
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; });
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B") } }; });
}
async function boot(env) {
// jsdom 이 문서를 다 읽고 DOMContentLoaded 를 보낸 뒤에 넣는다 — 먼저 넣으면 초기화가 두 번 돈다.
if (env.d.readyState === "loading") {
await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
}
// jsdom 의 <select>·일부 입력은 내부 Proxy 라 value 를 재정의(enhance*)하면 쓰기가 막힌다(실제 브라우저는
// 문제없음, 기존 코드 그대로). 테스트에서는 버튼 보강을 건너뛰고 원래 입력칸으로 시험한다.
env.d.querySelectorAll("select").forEach(function (s) { s.dataset.pjEnhanced = "1"; });
env.d.querySelectorAll("input[type=date]").forEach(function (i) { i.dataset.pjDate = "1"; });
env.w.eval(JS);
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
await settle();
return env.w.__pjProject;
}
function taskOf(P, id) { return P.state().tasks.find(function (t) { return t.id === id && t.context_project_id === 1; }); }
function subsText(d) { // 하위 작업 제목은 입력칸 값이다
return Array.from(d.querySelectorAll("#pj-subtask-list .pj-subtask-title")).map(function (i) { return i.value; }).join("|") ||
d.getElementById("pj-subtask-list").textContent;
}
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } // 창 닫기 애니메이션(0.32초) 대기
function titleVal(d) { return d.getElementById("pj-t-title").value; }
(async function () {
// ── [05] 한국시간 기준 오늘 ─────────────────────────────
{
const env = makeEnv(); baseRoutes(env); await boot(env);
const H = env.w.__pjHelpers;
const kst = function (y, m, d, hh, mm) { return Date.UTC(y, m - 1, d, hh - 9, mm); };
check("[05] KST 00:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 0, 0)) === "2026-09-30");
check("[05] KST 08:59(UTC 전날) → 그날", H.kstTodayIso(kst(2026, 9, 30, 8, 59)) === "2026-09-30");
check("[05] KST 09:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 9, 0)) === "2026-09-30");
check("[05] KST 23:59 → 그날", H.kstTodayIso(kst(2026, 9, 30, 23, 59)) === "2026-09-30");
const realNow = env.w.Date.now;
env.w.Date.now = function () { return kst(2026, 9, 30, 8, 30); };
const y = H.dueInfo("2026-09-29", false), t = H.dueInfo("2026-09-30", false);
check("[05] 해외 시간대(" + (process.env.TZ || "기본") + ")·한국 오전에도 전날 마감=지남", y.cls === "is-overdue" && y.text === "어제", y);
check("[05] 오늘 마감은 지남이 아님", t.cls === "is-soon" && t.text === "오늘", t);
env.w.Date.now = realNow;
}
// ── [09] A→B 전환 중 늦은 A 응답이 B 를 덮지 않는다 ───────────
{
const env = makeEnv(); baseRoutes(env);
const dA = deferred();
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return dA.promise; });
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B", { subtasks: [{ id: 902, title: "B-sub", project_id: 1 }] }) } }; });
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101));
await P.openTaskModal(taskOf(P, 102));
await settle();
dA.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 901, title: "A-sub", project_id: 1 }] }) } });
await settle();
check("[09] 늦은 A 상세가 B 의 하위 작업 목록을 덮지 않음", subsText(d).includes("B-sub") && !subsText(d).includes("A-sub"), subsText(d));
env.route("POST", /\/project\/api\/projects\/1\/tasks$/, function (u, b) { return { status: 201, body: { task: detail(903, b.title, { parent_task_id: b.parent_task_id }) } }; });
d.getElementById("pj-subtask-input").value = "새 하위";
d.getElementById("pj-subtask-add").click();
await settle();
const post = env.calls.filter(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }).pop();
check("[09] B 화면에서 추가한 하위 작업은 B 에 붙음", post && post.body.parent_task_id === 102, post && post.body);
}
// A→B→A — 같은 작업을 다시 열어도 이전 요청은 버린다
{
const env = makeEnv(); baseRoutes(env);
const dOld = deferred(); let n = 0;
env.route("GET", /\/project\/api\/tasks\/101$/, function () {
n++;
if (n === 1) return dOld.promise;
return { body: { task: detail(101, "작업 A", { subtasks: [{ id: 911, title: "A-new", project_id: 1 }] }) } };
});
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101));
await P.openTaskModal(taskOf(P, 102));
await P.openTaskModal(taskOf(P, 101));
await settle();
dOld.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 910, title: "A-old", project_id: 1 }] }) } });
await settle();
check("[09] A→B→A 에서 첫 A 의 늦은 응답은 버림", subsText(d).includes("A-new") && !subsText(d).includes("A-old"), subsText(d));
}
// 이미지 업로드 중 A→B 전환 — 업로드가 끝나 A 설명에 들어가고 저장된 뒤에 B 가 열린다
{
const env = makeEnv(); baseRoutes(env);
const up = deferred();
env.route("POST", /\/project\/api\/tasks\/101\/attachments$/, function () { return up.promise; });
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { return { body: { task: Object.assign(detail(101, "작업 A"), b) } }; });
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101));
await settle();
const box = d.getElementById("pj-t-desc");
const file = new env.w.File(["x"], "a.png", { type: "image/png" });
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return file; } }], getData: function () { return ""; } } });
box.dispatchEvent(ev);
await settle();
const switching = P.openTaskModal(taskOf(P, 102));
await settle();
check("[09] 업로드 중에는 B 로 넘어가지 않고 기다림", d.getElementById("pj-t-id").value === "101");
up.resolve({ status: 201, body: { attachment: { id: 55 } } });
await switching; await settle();
const put = env.calls.filter(function (c) { return c.method === "PUT" && /tasks\/101$/.test(c.url) && c.body.description; }).pop();
check("[09] 업로드된 이미지는 A 설명에 넣어 A 에 저장", !!put && put.body.description.includes("/attachments/55/inline"), put && put.body);
check("[09] 그 다음 B 가 열리고 B 설명엔 이미지 없음", d.getElementById("pj-t-id").value === "102" && !box.innerHTML.includes("/attachments/55/"));
}
// ── [10] 저장 실패 후 닫기 — 유실 없이 재시도/버리기 선택 ─────────
{
const env = makeEnv(); baseRoutes(env);
let putStatus = 500; const puts = [];
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
puts.push(b);
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
});
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
await P.openTaskModal(taskOf(P, 101)); await settle();
const ta = d.getElementById("pj-t-title");
ta.value = "작업 A2"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
check("[10] 실패한 칸 기록 + '저장 실패 · 다시 시도' 표시", P.state().failed.includes("title") && d.getElementById("pj-autosave-state").textContent.includes("저장 실패"), P.state().failed);
check("[10] 저장 안 된 상태면 페이지 이탈 경고 대상", P.state().unsaved === true);
env.setConfirm(false); // 계속 편집
await P.attemptClose(); await settle();
check("[10] 닫기 때 재시도해도 실패 → 묻고, '계속 편집'이면 창·입력 유지", !modal.hidden && titleVal(d) === "작업 A2" && env.confirms === 1);
putStatus = 200;
await P.attemptClose(); await settle(); await wait(400);
check("[10] 다시 닫기 → 재시도 성공 후 닫힘", modal.hidden && puts[puts.length - 1].title === "작업 A2", { hidden: modal.hidden, last: puts[puts.length - 1] });
check("[10] 저장된 상태에서는 이탈 경고 없음", P.state().unsaved === false);
}
{
// 403·지연 + Escape + 버리기, A 실패가 B 상태를 오염시키지 않음
const env = makeEnv(); baseRoutes(env);
const dPut = deferred();
env.route("PUT", /\/project\/api\/tasks\/101$/, function () { return dPut.promise; });
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
await P.openTaskModal(taskOf(P, 101)); await settle();
d.getElementById("pj-t-priority").value = "high";
d.getElementById("pj-t-priority").dispatchEvent(new env.w.Event("change")); await settle();
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
check("[10] 저장 중 Esc → 저장이 끝날 때까지 창 유지", !modal.hidden);
env.setConfirm(true); // 버리고 넘어가기
const opening = P.openTaskModal(taskOf(P, 102)); await settle();
dPut.resolve({ status: 403, body: { detail: "권한 없음" } });
await opening; await settle();
check("[10] 403 실패 → 버리기 선택 후 B 열림", d.getElementById("pj-t-id").value === "102" && !modal.hidden);
check("[10] A 의 실패가 B 상태를 오염시키지 않음", P.state().failed.length === 0 && d.getElementById("pj-autosave-state").textContent === "", P.state().failed);
}
{
// 네트워크 단절 → 계속 편집, 복구 후 표시줄 클릭으로 재시도
const env = makeEnv(); baseRoutes(env);
let net = false; const puts = [];
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { puts.push(b); return net ? { body: { task: Object.assign(detail(101, "작업 A"), b) } } : "NETWORK"; });
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101)); await settle();
d.getElementById("pj-t-due").value = "2026-10-10";
d.getElementById("pj-t-due").dispatchEvent(new env.w.Event("change")); await settle();
check("[10] 네트워크 오류 → 마감일 칸 실패로 남음", P.state().failed.includes("due"));
net = true;
const stEl = d.getElementById("pj-autosave-state");
const stBefore = stEl.dataset.state;
stEl.click(); await settle();
check("[10] '다시 시도' → 같은 값으로 재전송 성공", P.state().failed.length === 0 && puts[puts.length - 1].due_date === "2026-10-10",
{ stBefore: stBefore, failed: P.state().failed, puts: puts });
}
// ── [16] 한글 조합 Enter ─────────────────────────────────
{
const env = makeEnv(); baseRoutes(env);
const dPost = deferred();
env.route("POST", /\/project\/api\/tasks\/101\/comments$/, function () { return dPost.promise; });
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101)); await settle();
const inp = d.getElementById("pj-comment-input");
inp.value = "안녕하세요";
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true }));
const ev229 = new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
Object.defineProperty(ev229, "keyCode", { value: 229 });
inp.dispatchEvent(ev229);
await settle();
const posts = function () { return env.calls.filter(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }); };
check("[16] 조합 중 Enter(isComposing·229)는 댓글 전송 안 함", posts().length === 0);
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
await settle();
check("[16] 조합이 끝난 Enter 연타 → 한 번만 전송", posts().length === 1 && posts()[0].body.client_token, posts().length);
dPost.resolve({ status: 201, body: { comment: { id: 1, body: "안녕하세요" }, mention_skipped: [] } }); await settle();
const sub = d.getElementById("pj-subtask-input");
await settle(); sub.value = "하위";
sub.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
check("[16] 하위 작업 칸도 조합 중 Enter 는 추가 안 함", !env.calls.some(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }));
const cm = d.getElementById("pj-cm-input");
env.w.__pjChat.open(101); await settle();
cm.value = "채팅";
cm.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
check("[16] 댓글 대화창도 조합 중 Enter 는 전송 안 함", posts().length === 1);
}
// ── [03] 파일 댓글 — 실패 파일 표시·유지, 성공 시 비움 ───────────
{
const env = makeEnv(); baseRoutes(env);
let mode = "fail";
env.route("POST", /\/project\/api\/tasks\/101\/comments\/files$/, function () {
if (mode === "fail") return { status: 400, body: { detail: { message: "보낼 수 없는 파일이 있어 댓글을 등록하지 않았습니다.", failed: [{ index: "1", name: "b.png", reason: "빈 파일" }] } } };
if (mode === "net") return "NETWORK";
return { status: 201, body: { comment: { id: 5, body: "" }, attachments: [], mention_skipped: [] } };
});
const P = await boot(env); const d = env.d;
env.w.__pjChat.open(101); await settle();
const cm = d.getElementById("pj-cm-input");
function pasteImg(name, content) {
const f = new env.w.File(content, name, { type: "image/png" });
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return f; } }], getData: function () { return ""; } } });
cm.dispatchEvent(ev);
}
pasteImg("a.png", ["aaa"]); pasteImg("b.png", []);
await settle();
d.getElementById("pj-cm-send").click(); await settle();
const chips = function () { return Array.from(d.querySelectorAll("#pj-cm-pending .pj-chat-pending-chip")); };
check("[03] 서버가 거절한 파일만 빨간 표시, 두 파일 모두 남음", chips().length === 2 && chips()[1].classList.contains("is-failed") && !chips()[0].classList.contains("is-failed"));
const sent = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); });
check("[03] 파일은 본문과 한 요청으로(빈 댓글을 먼저 만들지 않음)", sent.length === 1 && !env.calls.some(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }));
mode = "net";
d.getElementById("pj-cm-send").click(); await settle();
check("[03] 네트워크 오류 → 파일·입력 유지", chips().length === 2);
const tok1 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
mode = "ok";
d.getElementById("pj-cm-send").click(); await settle();
const tok2 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
check("[03] 응답을 못 받은 재전송은 같은 client_token(서버가 한 번만 만듦)", tok1 && tok1 === tok2);
check("[03] 성공하면 대기 파일 비움", chips().length === 0);
}
// ── [14] 작업 창 댓글에 파일 표시 ─────────────────────────
{
const env = makeEnv(); baseRoutes(env);
env.route("GET", /\/project\/api\/tasks\/101\/comments/, function () {
return { body: { comments: [{ id: 7, body: "", author_email: "me@test.local", created_at: "2026-09-30T10:00" },
{ id: 8, body: "답글", parent_id: 7, author_email: "me@test.local", created_at: "2026-09-30T10:01" }],
events: [], features: { replies: true } } };
});
env.route("GET", /\/project\/api\/tasks\/101\/attachments/, function () {
return { body: { attachments: [{ id: 70, comment_id: 7, filename: "<b>x</b>.pdf", content_type: "application/pdf", size_bytes: 10 },
{ id: 71, comment_id: 8, filename: "r.png", content_type: "image/png", size_bytes: 10 },
{ id: 72, comment_id: null, filename: "plain.txt", content_type: "text/plain", size_bytes: 10 }] } };
});
const P = await boot(env); const d = env.d;
await P.openTaskModal(taskOf(P, 101)); await settle();
const list = d.getElementById("pj-comment-list");
check("[14] 파일만 있는 댓글에 파일 표시", list.querySelector('a[href="/project/api/attachments/70/download"]') !== null);
check("[14] 파일명은 이스케이프(태그로 해석 안 됨)", !list.querySelector(".pj-comment-atts b") && list.textContent.includes("<b>x</b>.pdf"));
check("[14] 답글의 파일은 답글에", !!list.querySelector(".pj-comment-item.is-reply img[src='/project/api/attachments/71/inline']"));
check("[14] 댓글 아닌 첨부는 댓글에 안 섞임", !list.innerHTML.includes("attachments/72/"));
check("[14] 첨부 목록에 '댓글' 표시", d.getElementById("pj-attach-list").textContent.includes("댓글"));
}
// ── [12] 연결된 작업은 읽기 전용 ─────────────────────────
{
const env = makeEnv(); baseRoutes(env);
env.route("GET", /\/project\/api\/tasks\/301$/, function () {
return { body: { task: detail(301, "연결된 작업", { project_id: 3, project_name: "비밀", access: "read", followers: null, subtasks: [{ id: 3011, title: "읽기 하위", project_id: 3 }] }) } };
});
const P = await boot(env); const d = env.d;
const linked = P.state().tasks.find(function (t) { return t.id === 301; });
await P.openTaskModal(linked); await settle();
check("[12] 제목·담당자 편집 불가", d.getElementById("pj-t-title").readOnly && d.getElementById("pj-t-assignee").disabled);
check("[12] 읽기 전용 안내 표시", !d.getElementById("pj-t-readonly").hidden);
check("[12] 댓글 입력·완료·삭제 숨김", d.getElementById("pj-comment-dock").hidden && d.getElementById("pj-toggle-complete").hidden && d.getElementById("pj-delete-task").hidden);
check("[12] 하위 작업 추가 칸 숨김, 목록은 보임", d.querySelector(".pj-subtask-form").hidden && subsText(d).includes("읽기 하위"));
d.getElementById("pj-t-title").value = "바꿈";
d.getElementById("pj-t-title").dispatchEvent(new env.w.Event("blur")); await settle();
const puts12 = env.calls.filter(function (c) { return c.method === "PUT"; });
check("[12] 읽기 전용이면 저장 요청을 보내지 않음(뒤늦은 403 없음)", puts12.length === 0, puts12);
}
// ── [13][01] 실시간 동기화 — 실패 후 같은 버전 재시도, 전체 범위 반영, 권한 회수 ──
{
const env = makeEnv(); baseRoutes(env);
let ver = "v1", snapMode = "fail";
const dSnap = deferred();
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: ver } }; });
env.route("GET", /\/snapshot\?scope=all/, function () {
if (snapMode === "fail") return { status: 500, body: { detail: "잠시 오류" } };
if (snapMode === "slow") return dSnap.promise;
if (snapMode === "gone") return { status: 403, body: { detail: "권한 없음" } };
return { body: { scope: "all", project: { id: 1, name: "P1" },
projects: [{ id: 1, name: "P1", color: "#4573d2", status: "active" }],
tasks: [{ id: 101, title: "작업 A(새 제목)", project_id: 1, context_project_id: 1, stage_id: 11, stage_name: "할 일" },
{ id: 150, title: "다른 사람이 만든 작업", project_id: 1, context_project_id: 1, stage_id: 13, stage_name: "검토" }],
stages_by_project: { "1": [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }] },
stages: [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }],
members: [{ user_email: "me@test.local" }] } };
});
const P = await boot(env); const d = env.d;
const st = function () { return env.w.pjLiveRefreshState(); };
const poll = function () { return env.w.__pjLivePoll(); };
const nextDelay = function () { const t = env.slow.filter(function (s) { return s.fn === env.w.__pjLivePoll; }).pop(); return t && t.ms; };
check("[13] 처음 본 버전 = 반영된 버전", st().observed === "v1" && st().applied === "v1");
ver = "v2";
await poll(); await settle();
check("[13] 스냅샷 실패 → 반영 버전은 그대로(v1), 실패 1", st().observed === "v2" && st().applied === "v1" && st().failures === 1, st());
check("[13] 실패 뒤 다음 확인은 늘어난 간격(16초)", nextDelay() === 16000, nextDelay());
snapMode = "ok";
await poll(); await settle();
check("[13] 같은 버전 다음 요청 성공 → v2 반영", st().applied === "v2" && st().failures === 0, st());
const s = P.state();
check("[01] 다른 프로젝트(P2) 작업·사이드바 항목 제거(권한 회수)", !s.tasks.some(function (t) { return t.project_id === 2; }) && !s.projectsMeta.some(function (p) { return p.id === 2; }));
check("[01] 새 작업·새 섹션 반영", s.tasks.some(function (t) { return t.id === 150; }) && s.boardStages.includes("검토"));
check("[01] 제목 변경 반영", s.tasks.find(function (t) { return t.id === 101; }).title === "작업 A(새 제목)");
// 동기화 중 버전이 또 바뀌면 끝난 뒤 한 번 더
snapMode = "slow"; ver = "v3";
const firstPoll = poll();
await settle();
ver = "v4";
const snapsBefore = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
await poll(); // 동기화가 도는 중에 또 확인 — 겹쳐 받지 않는다
const snapsDuring = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
dSnap.resolve({ body: { tasks: [], projects: [{ id: 1, name: "P1", status: "active" }], stages_by_project: {}, stages: [], members: [] } });
await firstPoll; await settle();
check("[13] 동기화 중 새 버전(v4) — 겹쳐 돌지 않고 반영 버전은 v3", st().applied === "v3" && st().observed === "v4" && snapsDuring === snapsBefore, { st: st(), snapsBefore: snapsBefore, snapsDuring: snapsDuring });
snapMode = "ok";
await poll(); await settle();
check("[13] 다음 주기에 v4 반영", st().applied === "v4", st());
snapMode = "gone"; ver = "v5";
await poll(); await settle();
check("[01][02] 이 프로젝트 권한 회수 → 작업 비우고 안내", !!d.querySelector(".pj-access-lost") && P.state().tasks.length === 0);
}
clearTimeout(WATCHDOG);
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})().catch(function (e) { console.error(e); process.exit(1); });
+71
View File
@@ -0,0 +1,71 @@
"""project/project.html 을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
python tests/js/render_project.py # → tests/js/.out/project_render.html
"""
from __future__ import annotations
import io
import os
import jinja2
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
ME = "me@test.local"
STAGES = {
1: [{"id": 11, "project_id": 1, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
"created_by": ME, "default_assignee_email": ""},
{"id": 12, "project_id": 1, "name": "완료", "is_done_stage": True, "sort_order": 1, "color": None,
"created_by": ME, "default_assignee_email": ""}],
2: [{"id": 21, "project_id": 2, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
"created_by": ME, "default_assignee_email": ""}],
}
def task(tid: int, title: str, pid: int, stage: int, *, ctx: int | None = None, linked: bool = False) -> dict:
return {"id": tid, "title": title, "project_id": pid, "context_project_id": ctx or pid, "is_linked": linked,
"stage_id": stage, "home_stage_id": stage, "stage_name": "할 일", "is_done_stage": False,
"description": "", "assignee_email": "", "assignee_name": "", "priority": "normal",
"start_date": None, "due_date": None, "completed_at": None, "created_by": ME,
"parent_task_id": None, "comment_count": 0, "subtask_count": 0, "subtask_done": 0,
"project_name": {1: "P1", 2: "P2", 3: "비밀"}[pid], "project_color": "#4573d2", "sort_order": tid}
TASKS = [task(101, "작업 A", 1, 11), task(102, "작업 B", 1, 11), task(103, "작업 C", 2, 21),
task(301, "연결된 작업", 3, 99, ctx=1, linked=True)]
PROJECTS = [{"id": 1, "name": "P1", "color": "#4573d2", "icon": "", "start_date": None, "due_date": None,
"created_by": ME, "description": "", "status": "active"},
{"id": 2, "name": "P2", "color": "#f06a6a", "icon": "", "start_date": None, "due_date": None,
"created_by": ME, "description": "", "status": "active"}]
def main() -> None:
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
]))
env.globals["pj_kr_holidays"] = {}
html = env.get_template("project/project.html").render(
user={"email": ME, "is_super_admin": False}, is_admin=False, can_manage=True,
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
avatars={}, priority_labels={"low": "낮음", "normal": "보통", "high": "높음"},
color_palette=["#4573d2"], project_icons=["folder"], stage_color_palette=["#c7c4c4"],
today="2026-09-30", holidays={}, year=2026, month=9, prev_y=2026, prev_m=8, next_y=2026, next_m=10,
weekdays=["일", "월", "화", "수", "목", "금", "토"], weeks=[], goal_years=[2026],
my_open_total=0, mention_unread=0,
)
os.makedirs(OUT_DIR, exist_ok=True)
path = os.path.join(OUT_DIR, "project_render.html")
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
print("rendered:", path)
if __name__ == "__main__":
main()
+471
View File
@@ -0,0 +1,471 @@
"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 PostgreSQL + FastAPI TestClient).
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 가상의 사용자·프로젝트만 만든다.
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회): project_db_init.sql + project_db_0*.sql
# 2) 실행
PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \
python tests/test_project_module.py
PROJECT_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
메일은 app.mail.send_email 을 가짜로 바꿔 기록만 한다(실제 발송 없음).
"""
from __future__ import annotations
import io
import os
import sys
import tempfile
import threading
import types
import uuid
from datetime import timedelta
from urllib.parse import urlparse
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
_host = urlparse(DSN).hostname if DSN else None
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
# ── app.main 대역(전체 앱을 띄우지 않고 프로젝트 라우터만 시험) ──────────────
class _Users:
def __init__(self) -> None:
self.d: dict[str, dict] = {}
def add(self, email: str, *, role: str = "user", project: bool = True, super_: bool = False) -> str:
email = email.lower()
self.d[email] = {"email": email, "name": email.split("@")[0], "role": role,
"modules": {"project": project}, "is_super_admin": super_}
return email
def get(self, email: str):
return self.d.get((email or "").lower())
def list_all(self):
return list(self.d.values())
USERS = _Users()
SENT_MAIL: list[dict] = []
if ENABLED:
from fastapi.responses import HTMLResponse
fake_main = types.ModuleType("app.main")
fake_main.user_store = USERS
def _current(request):
return USERS.get(request.headers.get("x-test-user", ""))
fake_main.get_current_user_record = _current
fake_main.build_erp_nav = lambda user, active="": []
fake_main.render_template = lambda request, name, ctx, status_code=200: HTMLResponse(
f"{name}|{ctx.get('reason', '')}", status_code=status_code)
sys.modules["app.main"] = fake_main
for k in list(os.environ):
if k.startswith("SMTP_") or k == "PROJECT_NOTIFY_EMAIL":
os.environ.pop(k)
import app.mail as _mail # noqa: E402
_mail.send_email = lambda **kw: SENT_MAIL.append(kw)
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from app.modules.project import reminders # noqa: E402
from app.modules.project import router as project_api_router # noqa: E402 - 패키지가 APIRouter 를 내보낸다
from app.modules.project.db import ProjectStore # noqa: E402
from app.timezone import today_kst # noqa: E402
ST = ProjectStore(DSN)
DATA_DIR = tempfile.mkdtemp(prefix="pj-test-")
APP = FastAPI()
APP.include_router(project_api_router)
APP.state.project_store = ST
APP.state.data_dir = DATA_DIR
CLIENT = TestClient(APP)
RUN = uuid.uuid4().hex[:6]
ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin")
SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True)
ALICE = USERS.add(f"alice-{RUN}@test.local")
BOB = USERS.add(f"bob-{RUN}@test.local")
CAROL = USERS.add(f"carol-{RUN}@test.local")
DAVE = USERS.add(f"dave-{RUN}@test.local") # 프로젝트 권한은 있으나 어디에도 멤버 아님
EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음
def req(method: str, url: str, who: str, **kw):
return CLIENT.request(method, url, headers={"x-test-user": who}, **kw)
def _project(name: str, owner: str, members: tuple[str, ...] = ()) -> dict:
p = ST.create_project(name=f"{name}-{uuid.uuid4().hex[:4]}", owner_email=owner, created_by=owner)
for m in members:
ST.add_member(project_id=p["id"], user_email=m)
return p
def _stage(pid: int, name: str = "할 일", done: bool = False, by: str = "") -> dict:
return ST.add_stage(project_id=pid, name=name, is_done_stage=done, created_by=by)
def _count(sql: str, *args) -> int:
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 전용 확인 쿼리
return int(conn.execute(sql, args).fetchone()["n"])
# ════════════════════════════════════════════════════════════
# [07] 소유자 변경은 관리자만
# ════════════════════════════════════════════════════════════
def test_owner_change_admin_only():
p = _project("P-owner", ADMIN, (BOB,))
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB})
assert r.status_code == 403, r.text
assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"})
assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x"
# 같은 값을 같이 보내는 건(화면 저장) 통과
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200
# 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200
assert ST.get_project(project_id=p["id"])["owner_email"] == CAROL
# 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200
assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403
# 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자
assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403
r = req("POST", "/project/api/projects", BOB, json={"name": "n2"})
assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB
# ════════════════════════════════════════════════════════════
# [06] 삭제 — 생성자 규칙 + 지금 권한
# ════════════════════════════════════════════════════════════
def test_delete_requires_current_access():
p = _project("P-del", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"]
ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi")
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
# 현재 멤버인 타인 → 생성자 규칙으로 거절
assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403
# 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음
ST.remove_member(project_id=p["id"], user_email=ALICE)
assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403
assert ST.get_task(task_id=t["id"]) is not None
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id = %s", t["id"]) == 1
assert _count("SELECT COUNT(*) AS n FROM project_trash") == trash_before
# 다시 멤버가 된 생성자 → 삭제(휴지통)
ST.add_member(project_id=p["id"], user_email=ALICE)
r = req("DELETE", f"/project/api/tasks/{t['id']}", ALICE)
assert r.status_code == 200 and ST.get_task(task_id=t["id"]) is None
# 프로젝트 삭제: 만든 사람이어도 지금 권한이 없으면 거절, 슈퍼관리자는 예외
p2 = _project("P-del2", ALICE)
ST.update_project(project_id=p2["id"], fields={"owner_email": ADMIN}) # 관리자가 소유자를 바꿈
assert req("DELETE", f"/project/api/projects/{p2['id']}", ALICE).status_code == 403
assert ST.get_project(project_id=p2["id"]) is not None
assert req("DELETE", f"/project/api/projects/{p2['id']}", SUPER).status_code == 200
# ════════════════════════════════════════════════════════════
# [02] 권한 회수 후 조회·변경·알림
# ════════════════════════════════════════════════════════════
def test_revoked_member_loses_everything():
p = _project("P-rev", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB,
json={"title": "shared", "stage_id": s["id"], "assignee_email": ALICE,
"description": f'<span class="pj-mention" data-email="{ALICE}">@a</span>'}).json()["task"]
c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "mine"}).json()["comment"]
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
assert any(n["task_id"] == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
ST.remove_member(project_id=p["id"], user_email=ALICE)
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
assert not any(n.get("task_id") == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
for m, u, body in (("GET", f"/project/api/tasks/{t['id']}", None),
("GET", f"/project/api/tasks/{t['id']}/comments", None),
("GET", f"/project/api/tasks/{t['id']}/attachments", None),
("PUT", f"/project/api/tasks/{t['id']}", {"title": "x"}),
("PUT", f"/project/api/comments/{c['id']}", {"body": "edited"}),
("DELETE", f"/project/api/comments/{c['id']}", None),
("POST", f"/project/api/tasks/{t['id']}/followers", {})):
r = req(m, u, ALICE, json=body) if body is not None else req(m, u, ALICE)
assert r.status_code == 403, (m, u, r.status_code)
assert ST.get_comment(comment_id=c["id"])["body"] == "mine"
assert req("GET", f"/project/t/{t['id']}", ALICE, follow_redirects=False).status_code == 403 # 옛 공유 링크
# 완료 알림은 권한 잃은 담당자에게 가지 않는다(담당자 기록은 남음)
before = _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"])
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"completed": True}).status_code == 200
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) == before
assert ST.get_task(task_id=t["id"])["assignee_email"] == ALICE
# 권한 없는 사람을 새 담당자로 지정할 수 없다
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"assignee_email": DAVE}).status_code == 400
# 관리자·owner·멤버는 그대로
assert req("GET", f"/project/api/tasks/{t['id']}", ADMIN).status_code == 200
assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 200
# ════════════════════════════════════════════════════════════
# [08] 비멤버 @태그
# ════════════════════════════════════════════════════════════
def test_mentions_only_for_people_who_can_see():
p = _project("P-men", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
desc = "".join(f'<span class="pj-mention" data-email="{e}">@x</span>' for e in (DAVE, EVE, "ghost@nowhere.test"))
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "m", "stage_id": s["id"], "description": desc})
t = r.json()["task"]
assert set(r.json()["mention_skipped"]) == {DAVE, EVE, "ghost@nowhere.test"}
assert _count("SELECT COUNT(*) AS n FROM task_mentions WHERE task_id=%s", t["id"]) == 0
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@dave hi", "mentions": [DAVE]})
assert r.status_code == 201 and r.json()["mention_skipped"] == [DAVE]
assert not req("GET", "/project/api/mentions", DAVE).json()["tasks"] or \
all(x["id"] != t["id"] for x in req("GET", "/project/api/mentions", DAVE).json()["tasks"])
# 멘션이 접근 권한을 만들지 않는다
assert req("GET", f"/project/api/tasks/{t['id']}", DAVE).status_code == 403
# 연결된 프로젝트 멤버는 태그 가능(읽기 권한)
p2 = _project("P-men2", ADMIN, (BOB, CAROL))
s2 = _stage(p2["id"], by=ADMIN)
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": p2["id"], "stage_id": s2["id"]}).status_code == 201
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@carol", "mentions": [CAROL]})
assert r.json()["mention_skipped"] == []
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", CAROL).json()["tasks"])
# 태그 후보 API 도 같은 기준
cands = {u["email"] for u in req("GET", f"/project/api/all-users?task_id={t['id']}", BOB).json()["users"]}
assert CAROL in cands and BOB in cands and DAVE not in cands and EVE not in cands
# ════════════════════════════════════════════════════════════
# [12] 연결된 프로젝트 — 읽기 전용
# ════════════════════════════════════════════════════════════
def test_linked_task_is_read_only():
home = _project("P-home", ADMIN, (BOB,))
other = _project("P-link", ADMIN, (BOB, CAROL))
secret = _project("P-secret", ADMIN, (BOB,))
hs, os_ = _stage(home["id"], by=ADMIN), _stage(other["id"], by=ADMIN)
os2 = _stage(other["id"], name="진행", by=ADMIN)
ss = _stage(secret["id"], by=ADMIN)
t = ST.create_task(project_id=home["id"], title="linked", stage_id=hs["id"], created_by=BOB)
sib = ST.create_task(project_id=home["id"], title="sibling", stage_id=hs["id"], created_by=BOB)
sub = ST.create_task(project_id=home["id"], title="child", parent_task_id=t["id"], created_by=BOB)
for pid, sid in ((other["id"], os_["id"]), (secret["id"], ss["id"])):
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": pid, "stage_id": sid}).status_code == 201
r = req("GET", f"/project/api/tasks/{t['id']}", CAROL)
assert r.status_code == 200 and r.json()["task"]["access"] == "read"
assert [ln["project_id"] for ln in r.json()["task"]["links"]] == [other["id"]] # 비밀 프로젝트는 숨김
assert r.json()["task"]["followers"] is None
assert req("GET", f"/project/api/tasks/{sub['id']}", CAROL).json()["task"]["access"] == "read" # 하위 작업도 읽기
assert req("GET", f"/project/api/tasks/{sib['id']}", CAROL).status_code == 403 # 원 소속의 다른 작업은 안 보임
assert req("GET", f"/project/api/projects/{home['id']}/members", CAROL).status_code == 403
assert req("GET", f"/project/api/tasks/{t['id']}/comments", CAROL).status_code == 200
for m, u, body in (("PUT", f"/project/api/tasks/{t['id']}", {"title": "hack"}),
("POST", f"/project/api/tasks/{t['id']}/comments", {"body": "hi"}),
("DELETE", f"/project/api/tasks/{t['id']}", None)):
r = req(m, u, CAROL, json=body) if body is not None else req(m, u, CAROL)
assert r.status_code == 403, (m, u, r.status_code)
assert ST.get_task(task_id=t["id"])["title"] == "linked"
# 연결된 프로젝트 안의 섹션 이동은 예전처럼 허용
assert req("POST", f"/project/api/tasks/{t['id']}/links", CAROL, json={"project_id": other["id"], "stage_id": os2["id"]}).status_code == 201
# 공유 링크 — 연결된 프로젝트 화면으로
r = req("GET", f"/project/t/{t['id']}", CAROL, follow_redirects=False)
assert r.status_code == 303 and r.headers["location"] == f"/project/p/{other['id']}?task={t['id']}"
# 전체 스냅샷에서 연결 행은 연결된 프로젝트 맥락으로 한 번씩(원 소속 행은 CAROL 에게 없음)
snap = req("GET", f"/project/api/projects/{other['id']}/snapshot?scope=all", CAROL).json()
rows = [x for x in snap["tasks"] if x["id"] == t["id"]]
assert [(x["context_project_id"], x["is_linked"]) for x in rows] == [(other["id"], True)]
# 연결 해제 후엔 볼 수 없다
assert req("DELETE", f"/project/api/tasks/{t['id']}/links/{other['id']}", BOB).status_code == 200
assert req("GET", f"/project/api/tasks/{t['id']}", CAROL).status_code == 403
# ════════════════════════════════════════════════════════════
# [03] 파일 댓글 — 원자적 등록·재전송 중복 방지
# ════════════════════════════════════════════════════════════
def test_file_comment_atomic_and_idempotent():
p = _project("P-file", ADMIN, (BOB, CAROL))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="files", stage_id=s["id"], created_by=BOB)
url = f"/project/api/tasks/{t['id']}/comments/files"
n0 = _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"])
# JSON 경로: 예전 has_attachment 플래그로 빈 댓글을 만들 수 없다
assert req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "", "has_attachment": True}).status_code == 400
# 한 파일이라도 문제면(빈 파일) 아무것도 만들지 않고 어느 파일인지 알려 준다
r = req("POST", url, BOB, files=[("files", ("ok.txt", b"hello", "text/plain")), ("files", ("empty.txt", b"", "text/plain"))])
assert r.status_code == 400 and [f["name"] for f in r.json()["detail"]["failed"]] == ["empty.txt"]
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0
assert not os.path.isdir(os.path.join(DATA_DIR, "project", str(t["id"]))) or \
not os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))
# 정상: 본문 없이 파일 두 개, 같은 토큰으로 두 번 보내도 한 번만
files = [("files", ("a.png", b"\x89PNG....", "image/png")), ("files", ("b.pdf", b"%PDF-1", "application/pdf"))]
r1 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
r2 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
assert r1.status_code == 201 and r2.status_code == 201
assert r1.json()["comment"]["id"] == r2.json()["comment"]["id"] and r2.json().get("duplicate")
cid = r1.json()["comment"]["id"]
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
assert _count("SELECT COUNT(*) AS n FROM task_attachments WHERE comment_id=%s", cid) == 2
# DB 저장 실패 → 방금 쓴 파일도 지우고 댓글 없음
orig = ST.add_comment_with_attachments
ST.add_comment_with_attachments = lambda **kw: (_ for _ in ()).throw(RuntimeError("db down"))
try:
before_files = set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"]))))
try:
req("POST", url, BOB, files=[("files", ("c.txt", b"data", "text/plain"))])
except RuntimeError:
pass # TestClient 가 서버 예외를 그대로 올린다(운영에선 500)
assert set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) == before_files
finally:
ST.add_comment_with_attachments = orig
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
# 남의 댓글에 파일을 붙일 수 없다
r = req("POST", f"/project/api/tasks/{t['id']}/attachments", CAROL,
data={"comment_id": str(cid)}, files={"file": ("x.txt", b"x", "text/plain")})
assert r.status_code == 403
# 동시에 같은 토큰 두 개 → 댓글 하나
out = []
ths = [threading.Thread(target=lambda: out.append(req("POST", url, BOB, data={"client_token": "tok-par"},
files=[("files", ("p.txt", b"p", "text/plain"))]).json()))
for _ in range(2)]
[th.start() for th in ths]
[th.join() for th in ths]
assert len({o["comment"]["id"] for o in out}) == 1
# ════════════════════════════════════════════════════════════
# [04] 날짜 범위
# ════════════════════════════════════════════════════════════
def test_date_range_validation():
p = _project("P-date", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
base = f"/project/api/projects/{p['id']}/tasks"
assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400
t = req("POST", base, BOB, json={"title": "ok", "stage_id": s["id"], "start_date": "2026-10-01", "due_date": "2026-10-05"}).json()["task"]
u = f"/project/api/tasks/{t['id']}"
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 400 # 한쪽만 바꿔도 최종 상태 검사
assert ST.get_task(task_id=t["id"])["due_date"] == "2026-10-05"
assert req("PUT", u, BOB, json={"start_date": None}).status_code == 200 # null 로 지우기
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 200 # 시작일 없으면 허용
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200
# 프로젝트도 같은 규칙(부분 수정 포함)
pu = f"/project/api/projects/{p['id']}"
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400
assert req("POST", "/project/api/projects", BOB, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
# ════════════════════════════════════════════════════════════
# [11] 완료 섹션에 바로 만든 작업
# ════════════════════════════════════════════════════════════
def test_create_in_done_stage_completes():
p = _project("P-done", ADMIN, (ALICE, BOB))
todo, done = _stage(p["id"], by=ADMIN), _stage(p["id"], name="완료", done=True, by=ADMIN)
SENT_MAIL.clear()
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "done now", "stage_id": done["id"], "assignee_email": ALICE})
t = r.json()["task"]
assert t["completed_at"] and "_newly_completed" not in t
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='completed'", t["id"]) == 1
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='completed' AND recipient_email=%s", t["id"], ALICE) == 1
# 일반 섹션 생성 → 미완료, 완료 섹션으로 이동 → 완료(이력 1건 더), 이탈 → 미완료
t2 = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "later", "stage_id": todo["id"]}).json()["task"]
assert not t2["completed_at"]
assert req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": done["id"]}).json()["task"]["completed_at"]
assert not req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": todo["id"]}).json()["task"]["completed_at"]
# 섹션 없는 하위 작업: 수동 완료/취소
sub = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "sub", "parent_task_id": t2["id"]}).json()["task"]
assert sub["stage_id"] is None and not sub["completed_at"]
assert req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": True}).json()["task"]["completed_at"]
assert not req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": False}).json()["task"]["completed_at"]
# ════════════════════════════════════════════════════════════
# [15] 마감 알림 — 원자적·재시도·중복 방지·권한
# ════════════════════════════════════════════════════════════
def test_due_reminders_atomic_and_access():
p = _project("P-rem", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
today = today_kst()
t_ok = ST.create_task(project_id=p["id"], title=f"rem-ok-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
t_gone = ST.create_task(project_id=p["id"], title=f"rem-gone-{RUN}", stage_id=s["id"], assignee_email=ALICE, due_date=today.isoformat(), created_by=BOB)
t_fail = ST.create_task(project_id=p["id"], title=f"FAILME-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
ST.remove_member(project_id=p["id"], user_email=ALICE)
q = "SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='due_today'"
qr = "SELECT COUNT(*) AS n FROM task_reminders WHERE task_id=%s"
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 DB 에서만: 알림 생성 실패 흉내
conn.execute(f"ALTER TABLE project_notifications ADD CONSTRAINT test_fail_{RUN} CHECK (title NOT LIKE '%%FAILME-{RUN}%%')")
try:
reminders.run_due_reminders(ST, today=today, lookup=USERS.get)
assert _count(q, t_ok["id"]) == 1 and _count(q, t_gone["id"]) == 0
assert _count(q, t_fail["id"]) == 0 and _count(qr, t_fail["id"]) == 0 # 실패 → 기록도 되돌려짐
finally:
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute(f"ALTER TABLE project_notifications DROP CONSTRAINT test_fail_{RUN}")
reminders.run_due_reminders(ST, today=today, lookup=USERS.get) # 재실행: 실패분만 생성
assert _count(q, t_fail["id"]) == 1 and _count(q, t_ok["id"]) == 1
# 동시 실행에도 중복 없음
t_par = ST.create_task(project_id=p["id"], title=f"rem-par-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
ths = [threading.Thread(target=reminders.run_due_reminders, args=(ST,), kwargs={"today": today, "lookup": USERS.get}) for _ in range(4)]
[th.start() for th in ths]
[th.join() for th in ths]
assert _count(q, t_par["id"]) == 1
assert _count(q, t_gone["id"]) == 0 and _count(qr, t_gone["id"]) == 0
# ════════════════════════════════════════════════════════════
# [01] 전체 범위 스냅샷 — 다른 프로젝트의 생성·삭제·섹션 변경·권한 회수
# ════════════════════════════════════════════════════════════
def test_snapshot_all_scope():
a = _project("P-sa", ADMIN, (BOB,))
b = _project("P-sb", ADMIN, (BOB,))
sa, sb = _stage(a["id"], by=ADMIN), _stage(b["id"], by=ADMIN)
tb = ST.create_task(project_id=b["id"], title="in b", stage_id=sb["id"], created_by=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert {a["id"], b["id"]} <= {x["id"] for x in snap["projects"]}
assert any(x["id"] == tb["id"] for x in snap["tasks"]) and str(b["id"]) in snap["stages_by_project"]
sb2 = _stage(b["id"], name="new", by=ADMIN)
ST.delete_task(task_id=tb["id"], deleted_by=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert not any(x["id"] == tb["id"] for x in snap["tasks"])
assert sb2["id"] in [s["id"] for s in snap["stages_by_project"][str(b["id"])]]
ST.remove_member(project_id=b["id"], user_email=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert b["id"] not in {x["id"] for x in snap["projects"]} and str(b["id"]) not in snap["stages_by_project"]
ST.remove_member(project_id=a["id"], user_email=BOB)
assert req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).status_code == 403
_ = sa
def test_store_date_range_unit():
from app.modules.project import store
store.validate_date_range(None, "2026-01-01")
store.validate_date_range("2026-01-01", None, "10:00", None)
store.validate_date_range("2026-01-01", "2026-01-01", "23:59", None)
for args in (("2026-01-02", "2026-01-01"), ("2026-01-01", "2026-01-01", "10:01", "10:00")):
try:
store.validate_date_range(*args)
except ValueError:
continue
raise AssertionError(args)
if __name__ == "__main__":
if not ENABLED:
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
sys.exit(0)
n = 0
for name, fn in sorted(globals().items()):
if name.startswith("test_") and callable(fn):
fn()
n += 1
print("ok", name)
print(f"{n} tests passed")
ST.close()
_ = io, timedelta