382 Commits

Author SHA1 Message Date
king c655eb100d Merge branch 'feat/perf-future-formula-total-top' 2026-10-21 11:30:16 +09:00
king f79b970056 feat(performance): 앞날 입력·계산식 칸·기간 합계 맨 위
- 매출 수동 입력·광고비 날짜 칸과 엑셀·광고 보고서 업로드에서 오늘 이후 날짜 허용
- 이번달 등 일자별 표의 기간 합계 행을 제목 행 바로 아래로
- 날짜 칸에 = 없이 1000+2000 계산식 입력(formula.parse_amount), 식은
  마이그레이션 008 formula 열에 저장해 파랑 굵은 숫자·다시 누르면 식
- 광고비 탭 직접 입력값은 굵게 해제(굵게는 계산식만)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:30:11 +09:00
king bc5023c708 Merge branch 'feat/perf-manual-input-skip-sync' 2026-10-21 10:44:56 +09:00
king 48cae3b163 feat(performance): 수동 입력 켠 쇼핑몰은 매출 업데이트에서 제외
API 가 설정돼 있어도 설정에서 수동 입력을 켠 쇼핑몰은 수동·자동 매출
업데이트(과거 매출 가져오기 포함)에서 빠진다. 설정 화면 안내 문구 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:44:50 +09:00
king d666d28c7c Merge branch 'feat/erp-sidebar-color-icons' 2026-10-20 20:59:34 +09:00
king d29c26a017 feat(erp): 사이드바 컬러 아이콘·축소 메뉴 간격 축소
- 메뉴 항목에 data-key 부여, 모듈별 아이콘 색(--erp-ic) 지정
- 축소 상태 항목 padding/gap 줄여 세로 간격 압축
- erp-shell.css 캐시 버전 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:59:33 +09:00
king 6feacf7582 Merge branch 'feat/perf-ad-update-button' 2026-10-20 13:44:46 +09:00
king 232695c004 feat(performance): 광고비 탭 [광고비 업데이트] 진행 창·자동 업데이트·업데이트 시각
- 채널별 [구글/메타 광고 불러오기] 버튼을 없애고 매출 탭과 같은 모양으로
  마지막 업데이트 · 다음 업데이트까지(카운트다운) · [광고비 업데이트]
- 진행 창 작업에 종류(sales/ads) 추가 — 광고 채널별 진행 막대(수집 → 저장
  → 완료), 채널별 중지·전체 취소는 저장 직전까지, 진행 중이면 합류
- POST /api/ad-sync, GET /api/ad-sync/current
- 자동 업데이트 회차에서 매출과 광고비를 동시에 각각 진행 창 작업으로
- 마지막 광고비 업데이트 = 광고 API 마지막 성공 가져오기 시각

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:44:45 +09:00
king 18b3ae007d Merge branch 'feat/project-owner-member' 2026-10-20 12:59:24 +09:00
king a281bebedf feat(project): 프로젝트 소유자를 멤버로 등록
소유자는 owner_email 로만 권한을 받고 멤버 행이 없어 멤버 목록에
보이지 않았다. 프로젝트를 만들 때·소유자를 바꿀 때 소유자를 멤버로
넣고, 소유자는 멤버에서 뺄 수 없게 한다(화면은 이미 체크 잠금).
기존 프로젝트는 마이그레이션 031 로 소유자 멤버 행을 채운다(멱등).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:59:23 +09:00
king 73c896a987 Merge branch 'feat/project-drive-move-with-task' 2026-10-20 12:32:07 +09:00
king bca1082c26 feat(project): 업무를 옮기면 설명 링크 속 드라이브 파일도 새 폴더로
업무의 섹션·프로젝트가 바뀌거나 세부 업무를 다른 상위 업무로 옮기면
드라이브 폴더 경로(프로젝트/섹션/업무/세부 업무)가 달라지는데 파일은
예전 폴더에 남았다. 이동 API(업무 수정·move-parent·move-project) 뒤
백그라운드로 업무와 모든 하위 업무의 설명 링크 파일을 새 폴더로 옮긴다.
그 업무가 올린 파일(appProperties dbxTaskId)만 옮기고, 예전 폴더는 둔다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:32:06 +09:00
king cad347a936 Merge branch 'fix/perf-naver-roas-missing' 2026-10-20 11:40:08 +09:00
king da5f4d3d65 fix(performance): 네이버 광고비 칸에 ROAS 가 안 나오던 문제
네이버 광고 보고서는 열 구성을 바꿀 수 있는데 업로드가 총비용·ROAS 를
고정 4열·12열에서만 읽어, 열 배치가 다른 파일은 ROAS 가 빈 값으로
저장돼 광고비 표에 괄호 ROAS 가 표시되지 않았다.

- 총비용·구매완료 광고수익률 열을 머리글 이름으로 찾음(없으면 고정 위치)
- 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용 × 100
- 이미 roas 가 빈 채 저장된 행은 ad_roas 가 보관된 보고서 항목에서 다시 구함

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:40:07 +09:00
king 2f05a73509 Merge branch 'feat/perf-naver-roas-col' 2026-10-20 11:36:38 +09:00
king c82f712f0b feat(performance): 광고 보고서 상세에서 ROAS 를 광고비 오른쪽에 표기
네이버 광고 보고서는 ROAS(구매완료 광고수익률(%))가 12열이라 일자별
보고서 창에서 광고비(총비용)와 멀리 떨어져 보였다. 상세 표에서 ROAS
열을 광고비 열 바로 오른쪽으로 옮기고, 네이버 머리글은 "ROAS(%)"로
보여 준다(말풍선에 원래 머리글). 저장된 키는 그대로라 예전 업로드에도
적용된다. 구글·메타 상세도 같은 순서.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:36:38 +09:00
king 3e56f1223a Merge branch 'fix/cafe24-ftp-temp-ext' 2026-10-20 11:01:40 +09:00
king bd1cc61434 fix(cafe24): 디자인 FTP 임시 파일이 확장자 제한에 걸려 적용 실패
카페24 디자인 FTP 는 허용 확장자만 받는다. 임시 이름
`product-swiper.js.cf24tmp-<tag>` 는 확장자가 바뀌어 STOR 가
`550 Operation not permitted` 로 거부돼 모바일 스와이프·PC/모바일
상품상세 적용이 모두 실패했다. 원래 확장자를 끝에 두도록
`<stem>_cf24tmp_<tag><ext>` 로 바꾼다(원본 비킴 이름도 동일).
테스트 FTP 대역에 확장자 제한을 흉내내 회귀를 막는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:01:39 +09:00
king e7d737f853 Merge branch 'feat/cafe24-swipe-code-copy' 2026-10-20 10:54:01 +09:00
king ef6313ec9f feat(cafe24): 옵션/품목 팝업에 모바일 스와이프 코드 복사 버튼
첫 줄 `// 상품명`, 이어서 품목마다 `"품목코드": "/web/... 썸네일 경로",`
형식으로 클립보드에 복사한다. 썸네일은 행에 보이는 이미지 기준이며
도메인·CDN 주소는 떼고 /web/ 부터 남긴다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:54:00 +09:00
king f1384d3a9a Merge branch 'fix/cafe24-status-read-lag' 2026-10-20 03:50:49 +09:00
king 1efc59ffcf fix(cafe24): 진열/판매 변경 후 예전 상태로 보이는 읽기 지연 보정
- overlay_recent_write: updated_date 가 같아도 값이 다르면 지연으로 판정
  (진열/판매만 바꾼 PUT 은 updated_date 를 올리지 않을 수 있음)
- 상품 목록에도 최근 쓰기 스냅샷 보정 적용(overlay_product_rows) —
  목록·필터가 예전 값으로 보이고 캐시가 예전 값으로 덮이던 문제
- 예약 폼 현재 상태 미리보기도 load_product 로 보정
- PUT 응답에 product_no 가 없어도 스냅샷 저장
- 회귀 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 03:50:48 +09:00
king ee752e66c0 Merge branch 'feat/desc-link-atomic' 2026-10-19 23:42:52 +09:00
king 5135e68569 feat(project): 설명란 링크 굵게·기울임·밑줄, 한 글자처럼 한 번에 지우기
- 링크는 contenteditable=false 로 잠가 커서가 링크 글자 안으로 들어가지 않음
- 링크 바로 뒤 Backspace·바로 앞 Delete = 링크 통째로 삭제(execCommand, Ctrl+Z 가능)
- 저장 HTML 에서는 잠금 표시를 뺀다(getHtml)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:42:35 +09:00
king d895c35d6a Merge branch 'feat/perf-net-kpi-drive-files' 2026-10-19 23:19:17 +09:00
king 52ca60df9a feat(project): 파일 끌어 놓기 → 구글 드라이브 링크, 필터 켠 보드 카드 순서 버그 수정
- 설명란·세부 업무 목록·보드 카드에 파일을 놓으면 드라이브 프로젝트/섹션/업무/세부 업무
  폴더에 올리고 설명에 "파일 이름.확장자" 링크(PROJECT_DRIVE_FOLDER_ID)
- 설명에서 링크를 지우면 우리가 올린 파일만 드라이브 휴지통, 되살리면 복구
- 브라우저별 필터(localStorage)가 켜져 있으면 섹션 안 카드가 제자리로 돌아가던 버그 —
  필터 중에도 순서 변경 허용, 숨은 업무는 제자리. 카드 속 이미지 끌기 오인 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:19:16 +09:00
king ee96c924fc feat(performance): KPI 수수료 차감 매출 한 줄·기본 보기 차감 매출·다음 업데이트 카운트다운·일 합계 ROAS
- KPI 는 수수료 차감 매출만 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %), 나머지 카드 제거
- 일자별 표 기본 보기 = 수수료 차감 매출(localStorage 저장값 안 씀)
- 마지막 업데이트 옆 다음 자동 업데이트까지 남은 시간(초 단위 실시간)
- 일 합계 ROAS = 일 합계 금액 ÷ 일 합계 광고비(보기 기준별 roas / roas_net)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:19:14 +09:00
king b23774420b Merge branch 'fix/meet-kpi-with-weeks' 2026-10-19 18:30:59 +09:00
king 1df0c2bbd6 fix(project): 회의록 월 계획 숫자 줄을 주차 탭과 같은 줄로
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:30:58 +09:00
king a11aaab9be Merge branch 'fix/meet-kpibar-above' 2026-10-19 18:25:23 +09:00
king 650df5b058 fix(project): 회의록 월 계획 숫자 한 줄을 카드 위 빈 공간으로(잘리지 않게) · 결정사항 제목 왼쪽
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:25:22 +09:00
king d6ea464733 Merge branch 'feat/meet-head-week-split' 2026-10-19 18:15:45 +09:00
king bff71eeeba feat(project): 회의록 머리 한 칸(월 계획 숫자+결정사항) · 회의록 표 구역선만 굵은 검정·나머지 회색 · 주차 목표 두 칸(유통·인플/카페24·네이버)
- 회의록 머리: 한 줄 = 월 계획 숫자 | 결정사항 제목, 아래 전체 = 결정사항(크게), 월 계획 상세 제거
- 회의록 표: 구역 처음·끝 가로선만 굵은 검정, 나머지 선 모두 회색
- 연간 목표 주차별 매출 목표 입력: 주차마다 유통·인플 / 카페24·네이버 두 칸, 머리글은 전체 목표 아래 — 마이그레이션 project_db 030(value_dist·value_mall, value=합계)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:15:21 +09:00
king 897d19ca1c Merge branch 'fix/naver-ev-goods' 2026-10-19 16:56:27 +09:00
king 8c1cc3e7bb fix(performance): 네이버 주문 내역 금액 칸 = 배송비 뺀 판매금액 · 맨 아래 그날 매출 계산식
저장 금액(판매금액 + 배송비)을 그대로 보여 배송비 칸과 겹쳐 보이던 문제

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:56:25 +09:00
king 962fed151a Merge branch 'feat/perf-sync-reopen' 2026-10-19 16:50:28 +09:00
king c710e184e7 feat(performance): 업데이트 중에도 [매출 업데이트]로 진행 창 다시 보기 · 서버 재시작으로 남은 진행 기록 정리
- 버튼은 업데이트 중 '업데이트 중 · 진행 보기', 누르면 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로
- 서버 시작 때 perf_sync_runs running 행을 '중단됨(서버 재시작)'으로 정리 — 30분 막힘 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:50:16 +09:00
king 50d66c00a6 Merge branch 'fix/naver-ship-per-package' 2026-10-19 16:19:23 +09:00
king 6249ced4fa fix(performance): 네이버 배송비 = 배송 묶음마다 한 번(할인 안 뺌) — 판매분석 배송비와 같게
10/18 실데이터: 상품주문마다 배송비 − 할인 = 38,500 → 묶음마다 deliveryFeeAmount 한 번 = 87,500(판매분석과 일치)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:18:42 +09:00
king 7f4fb93996 Merge branch 'feat/naver-ship-check' 2026-10-19 16:13:18 +09:00
king f2d4275b7f feat(performance): 네이버 배송비 대조 진단 — reconcile 응답에 주문·배송 묶음 단위 후보(ship_check)
10/18 실데이터에서 상품주문마다 배송비 − 할인 = 38,500, 판매분석 87,500 — 판매분석과 맞는 셈을 실데이터로 고르기 위한 진단

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:13:03 +09:00
king 11ab405783 Merge branch 'fix/perf-ev-footer-color' 2026-10-19 15:55:11 +09:00
king 3aaa1d9daa fix(performance): 주문 내역 합계 줄 적립금·배송비·환불 칸 글자 흰색
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:55:11 +09:00
king 91de84bec9 Merge branch 'feat/perf-points-shipping' 2026-10-19 15:46:32 +09:00
king 28e6cdd78a feat(performance): 카페24 적립금 제외 · 네이버 배송비 포함·환불일 환불 차감 · 주문 내역 칸·합계
- 카페24 매출 = 결제합계 − 적립금, 환불도 적립금 환불 제외, 주문 내역 [적립금 사용] 칸·합계
- 네이버 매출 = 판매금액(총) + 배송비, 환불 = 클레임 완료일 기준 취소·반품 완료(naver:{상품주문}-RF)
- 주문 내역 [배송비]·[환불금액] 칸·합계, 예전 자료는 과거 매출 가져오기로 다시 받으면 새 규칙

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:46:31 +09:00
king 39d730faa0 Merge branch 'feat/inout-order-notice-mail' 2026-10-19 15:21:48 +09:00
king c3d3b5e8f3 feat(inout): 발주 메일을 보내면 입고 담당에게 발주 알림 메일 자동 발송
- 같은 Gmail·같은 제목, 내용은 발주번호·발주일·제품 코드·제품명·수량
- 알림 실패·입고 담당 없음은 공장 메일을 막지 않고 결과에 안내, 미리보기에 받을 사람 표시

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:21:48 +09:00
king 137f6e4d98 Merge branch 'feat/fill-toggle-file-drop' 2026-10-19 14:41:27 +09:00
king a29854b2cb feat(inout,project): 남은 수량 채우기 되돌리기 · 업무 창/보드 카드에 파일 끌어 놓아 첨부
[입출고] [남은 수량 모두 채우기]를 한 번 더 누르면 채우기 전 값으로([채운 수량 되돌리기])
[프로젝트] 업무 창 아무 곳·보드 메인 업무 카드에 파일을 놓으면 첨부(여러 개), 받는 곳 밖에 놓쳐도 화면 이동 없음
[프로젝트] [파일 추가] 여러 개 선택, 도움말 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:41:26 +09:00
king cc3e702204 Merge branch 'feat/inout-mail-facts-compact' 2026-10-19 14:30:18 +09:00
king d4e4bc5dbf style(inout): 발주 메일 첫 요약 표 칸 높이를 글자 한 줄에 맞춤 · 두 표 사이 18px
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:30:16 +09:00
king 52e21a3a68 Merge branch 'feat/inout-order-mail-cc' 2026-10-19 14:25:14 +09:00
king 971666532e feat(inout): 발주 메일 참조 기본값 king@dbxcorp.co.kr · 옵션 → 공장에서 변경
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:25:13 +09:00
king 9cc508dc50 Merge branch 'feat/inout-recv-bar-buttons' 2026-10-19 14:13:58 +09:00
king 2a2c436013 style(inout): 입고 줄 버튼·입력칸 높이 34px 통일 · [입고증 업로드] 이름·사진 아이콘 28px
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:13:57 +09:00
king f486e6f263 Merge branch 'feat/inout-done-lock' 2026-10-19 14:04:18 +09:00
king 90af8a8486 feat(inout): 전체 입고 완료면 입고 저장 막기 · 사방넷 입고 파일 버튼 엑셀 초록
- 모든 품목 입고 완료·초과면 입고 칸·[입고 저장] 등 흐리게 disabled, 서버도 잠근 뒤 거절
- 사방넷 입고 파일 버튼 #217346

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:03:54 +09:00
king 2237e2e799 Merge branch 'feat/inout-sabangnet-file' 2026-10-19 13:44:43 +09:00
king 96438d5078 feat(inout): 입고 기록 줄 [사방넷 입고 파일] 엑셀 다운로드
- 1행 제목 상품코드·가용수량·불용수량, A=코드표 사방넷 코드, B=입고 수량, C=상품 이름
- 사방넷 코드가 없는 상품·코드표 연결 불가면 파일 대신 안내
- 발주·입고 담당, 마이그레이션 없음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:44:42 +09:00
king 038007c34e Merge branch 'feat/inout-receipt-mail' 2026-10-19 13:33:48 +09:00
king 08fe894d1b feat(inout): 물류센터 이메일 옵션 · 입고 저장 뒤 입고 요청 메일(Gmail, 본문 안 사진 600px)
- 옵션 → 물류센터 탭: 물류센터 담당자 이메일·입고 요청 메일 참조(기본 king@·bj@dbxcorp.co.kr)
- 입고 저장 → 미리보기 팝업 바로 → [메일 발송](입고 담당 본인 Gmail), 입고 기록 줄 보내기/다시 보내기
- 제목 "[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.", 본문 = 전산 등록 부탁 + 상품 이름·코드·입고 수량·비고 표
- 입고증 사진은 첨부가 아니라 본문 안 이미지(CID multipart/related), 가로 최대 600px·비율 유지로 줄임
- Gmail 연결 권한을 발주 담당 → 발주·입고 담당으로
- 마이그레이션 inout_db 005(inout_settings·inout_receipt_mails), 초기화 SQL 에도 반영

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:33:46 +09:00
king b95d3909a4 Merge branch 'feat/inout-mail-facts-grid' 2026-10-19 12:20:27 +09:00
king cb69b086d7 feat(inout): 발주 메일 첫 요약 표를 4열(항목·값 두 쌍씩) 4×4로
- 예전 2열 × 8행 → 4열 × 4행, 요청 사항은 맨 아래 한 줄 전체

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:20:27 +09:00
king 86720d073e Merge branch 'feat/meet-item-borders' 2026-10-19 12:16:47 +09:00
king 7540bc5610 feat(project): 주간 회의록 항목 사이 가로선 검정 · 같은 항목 하위 줄 사이만 회색
- markMeetSecEnds 가 칸 바로 아래 줄이 새 항목이면 .is-item-end(검정), 아니면 회색
- 구역 경계 굵은 선은 그대로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:16:46 +09:00
king 96d33c668b Merge branch 'feat/inout-po-weight-meet-borders' 2026-10-19 12:08:46 +09:00
king c1b3d7af59 feat(inout,project): 발주 메일 전체 무게·PP 사용량(kg) · 회의록 구역 굵은 선·줄 사이 회색 선
[입출고]
- 발주 메일 표: PP(g/개) → 전체 무게(kg) = 개당 무게 × 수량
- PP 사용량(kg) 열 추가(은 함유량 왼쪽) = 전체 무게 − 은 무게
- 은 함유량 괄호 = 전체 무게 × %(kg), 합계·요약·글 본문도 kg

[프로젝트]
- 주간 회의록 표: 구역(구분) 처음·끝 가로선 굵은 검정, 구역 안 줄 사이 가로선 회색
- 구역 끝에 닿는 칸(병합 포함)은 markMeetSecEnds 로 아래선 정리

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:08:32 +09:00
king e64612a8d9 Merge branch 'feat/project-dnd-perf-unit' 2026-10-19 10:46:13 +09:00
king 62c345bbb5 feat(project,performance): 보드 카드 끌기 실시간 미리보기 · 회의록 항목 끌어 옮기기·검정 테두리 · 실적 매출 단위·광고비(ROAS%) 줄
[프로젝트]
- 보드 카드 끌기: 기울어진 끄는 모양 + 점선 자리 표시가 카드 사이로 FLIP 애니메이션, 놓은 자리 그대로(다른 섹션도 순서 저장)
- 컬럼 dragenter 도 허용 — 자리 표시가 들어온 직후 놓을 때 drop 이 거부되던 문제
- 끄는 동안 실시간 동기화가 보드를 다시 그리지 않음
- 주간 회의록 항목 칸을 끌어 위아래로 이동(묶인 줄·세로 병합째, 같은 구역) — POST meeting-items/{id}/move-to
- 주간 회의록 표 테두리 모두 검정
- 도움말·모듈 문서 갱신

[실적]
- 설정의 쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교 카드 삭제(서버 API 는 유지)
- 보기 설정: 매출 단위 원·천원·백만원(이 브라우저 쿠키 perf_unit)
- 매출 실적 표 매출 칸 아래 광고비(ROAS%) 줄(광고비 색), 카페24 는 구글·메타 두 줄

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:44:24 +09:00
king ee728ed006 Merge branch 'docs/slim-claude-md' 2026-10-18 02:41:28 +09:00
king 619f95b7f4 docs: split CLAUDE.md into per-module CLAUDE.md to cut token use
Root CLAUDE.md (loaded every conversation) shrank from 34KB to ~8KB.
Module details moved verbatim-in-substance to app/modules/<mod>/CLAUDE.md,
which Claude Code loads only when working in that folder.

- [모듈명] prefix → module table (folder, DB, perm key, docs, static files)
- shared docs read only per task type (old "read 4 docs first" rule dropped)
- large docs: read TOC via grep, then only the needed section
- cross-module dependency list kept in root

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:41:26 +09:00
king fa7c55dee5 Merge branch 'feat/inout-super-delete' 2026-10-17 01:44:19 +09:00
king 215b937f1e feat(inout): 수퍼관리자 발주 삭제(발주 목록)
- 발주 목록 줄 끝 휴지통 — 수퍼관리자에게만 보이고 서버도 수퍼관리자만 허용(ERP 관리자도 403)
- 확인 창 후 품목·입고 기록·입고증 사진·발주 메일 기록까지 완전히 삭제(CASCADE), 서버 로그에 남김
- 지운 뒤 보던 목록(거르기 그대로)으로 — 다른 사이트 주소는 무시

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:44:18 +09:00
king f1e8dd5bf5 Merge branch 'feat/inout-all-received-dates' 2026-10-17 01:37:17 +09:00
king fde37515c8 feat(inout): 전체 입고 완료 표기 · 날짜 서식 yyyy.mm.dd(요일)
- 모든 품목이 입고완료·초과입고면 목록·발주서 머리에 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함")
- 화면·메일·메일 기록 날짜를 모두 2026.10.17(토) / 2026.10.17(토) 15:14 로(ymd·ymdhm 매크로, store.fmt_date·fmt_datetime)
- 발주서 품목 합계 줄 왼쪽 여백

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:37:15 +09:00
king f3b33d4084 Merge branch 'fix/erp-confirm-over-modal' 2026-10-17 01:08:50 +09:00
king 86ea9a11d4 fix(erp-dialog): 모달 팝업 안에서 확인 창이 뒤에 깔려 안 보이던 문제
입출고 옵션(상품 정보) ✕ 지우기 등 모달 <dialog>(showModal) 안에서 erpConfirm 을 부르면
body 에 붙인 확인 창이 브라우저 맨 위 층 뒤에 깔려 보이지도 눌리지도 않았다.
모달이 열려 있을 때만 확인 창을 모달 <dialog> 껍데기로 감싸 그 위에 띄운다(Esc = 취소). 평소엔 예전 그대로.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:08:49 +09:00
king b5bdf99069 Merge branch 'feat/inout-products' 2026-10-17 00:59:47 +09:00
king a475f0b2f6 feat(inout): 옵션 상품 정보 탭 — 단가·무게(PP)·은 함유량, 발주서·메일 금액, 입고 담당 화면 줄이기
- 마이그레이션 004: inout_products(단가·개당 무게 g·은 함유량 %), inout_products_excluded(지운 단품),
  inout_order_lines 에 발주할 때 값 사본(unit_price·weight_g·silver_pct)
- 옵션 → 상품 정보: [단품 불러오기](값을 넣은 상품은 그대로, 지운 단품은 다음에도 빠짐), 바뀐 줄만 저장,
  은 g = 무게 × % 자동, 지우기·되살리기
- 상품 정보가 있으면 발주서 제품은 그 목록에서(단가 함께), 금액 = 수량 × 단가 실시간 합계
- 발주서 화면(발주 담당)·발주 메일에 단가·금액·PP(g/개)·은 함유량과 합계(금액·PP kg·은 g)
- 입고 담당(발주 담당 아님)은 품목을 제품 이름·발주 수량(+ 이번 입고)만, 입고 기록 칩도 이름
- 고침: 그날 100번째 발주서부터 번호가 겹치던 문제(순번 숫자 비교), 시각을 DB 시간대와 무관하게 KST 로 읽음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:59:45 +09:00
king dcc6cd27b6 Merge branch 'fix/inout-gmail-connect-hint' 2026-10-16 16:59:15 +09:00
king 12f1d455b9 fix(inout): 메일 창 — 연결 전 아래 줄 숨김, redirect_uri_mismatch 대비 등록할 주소 안내
- .io-dlg-footbar 의 display:flex 가 hidden 속성을 덮어써 연결 전에도 [메일 발송]·[연결 끊기]가 보이던 문제
  → .io/.io-dlg/.io-viewer 안의 [hidden] 은 늘 숨김.
- 구글이 redirect_uri_mismatch 로 막으면 ERP 로 돌아오지 않으므로, 연결 안내에 구글 클라우드
  "승인된 리디렉션 URI"에 넣을 정확한 주소(callback_url)를 미리 보여 준다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:59:14 +09:00
king 9429485236 Merge branch 'feat/inout-mail-photos' 2026-10-16 16:41:30 +09:00
king 451b37955e feat(inout): 발주 메일(발주 담당 본인 Gmail) · 공장 이메일 · 입고증 사진
- inout_db 003: 공장 이메일, 사람별 Gmail 연결(갱신 토큰 암호문만), 발주 메일 기록, 입고증 사진(bytea). init 에도 같게.
- 발주 메일: 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 HTML + 글 본문) → 사람이 [메일 발송]을
  눌러야 Gmail API(gmail.send)로 본인 Gmail 에서 발송. [Gmail 연결]은 사람마다 1회 — 고른 구글 계정 = ERP 계정 확인,
  APP_ENCRYPTION_KEY(AES-GCM, AAD inout:gmail:{email})로 암호화 저장. 보낸 기록, 재발송은 확인 후(resend),
  연결 끊김(invalid_grant)은 토큰 삭제 후 재연결 안내.
- 입고증 사진: 입고 저장 때 첨부(브라우저가 긴 변 2000px JPEG 로 줄임 — 7.9MB → 0.8MB), 10장·10MB, 파일 머리로 형식 검사,
  입고와 한 트랜잭션. 썸네일·크게 보기(←/→)·나중에 더하기·지우기, 보기는 nosniff·CSP sandbox. 초과 확인은 브라우저가 먼저(사진 유지).
- 테스트: 메일 본문·escape·받는 주소·Gmail 연결 검사·토큰 갱신/발송(가짜 구글)·암호화, 사진 검사, 실제 PostgreSQL 저장,
  실제 앱 흐름(사진 업로드·보기 헤더·권한, 메일 미리보기·연결·발송·재발송·끊김). 실제 브라우저로 팝업·사진·축소 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:41:28 +09:00
king 2ed275cd80 Merge branch 'fix/inout-over-button' 2026-10-16 16:06:25 +09:00
king 5d7862515f fix(inout): [초과 입고로 저장] 버튼을 진한 빨강 바탕·흰 글씨로 — 분홍 안내 상자 위에서 잘 안 보이던 문제
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 16:06:24 +09:00
king 6121a27454 Merge branch 'feat/inout-options-popup' 2026-10-16 15:45:55 +09:00
king 4c17158753 feat(inout): 옵션을 톱니 팝업으로, 겹치던 옵션 화면 정리, 공장 담당자·연락처 분리
- 옵션 탭 → 상단 오른쪽 톱니(관리자) → 팝업(탭: 담당자·공장). 내용은 /inout/settings?panel=1,
  저장은 팝업 안에서(X-Inout-Options: 1 → JSON, 같은 탭 그대로 다시 그림), 바뀌면 닫을 때 새로고침.
  예전 /inout/settings 주소는 목록으로 가서 팝업 열기(?options=1).
- 겹침 원인: 공용 .erp-input(min-width 240px + content-box)이 좁은 칸에서 옆 칸을 덮고,
  .erp-table-wrap(카드 그림자·둥근 모서리)이 카드 안에서 상자를 겹쳐 보이게 함 → .io/.io-dlg 안에서만 바로잡음.
  공장 표는 진짜 <table> + 입력칸 form 속성으로 열 맞춤(줄 선·배경 어긋남 없음).
- 공장 담당자·연락처 분리: inout_db 002(manager 열, 이름만 있던 연락처는 담당자로). 발주서 화면에 공장 담당자·연락처.
  002 미적용이어도 발주서 화면은 열리고 공장 저장만 안내.
- 테스트: 팝업·JSON 저장·예전 주소·권한, 담당자/연락처, 002 전후. 실제 브라우저로 겹침 0·줄 맞춤 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:45:53 +09:00
king 586a14f7f9 Merge branch 'fix/inout-dsn-doc' 2026-10-16 15:28:27 +09:00
king 65a1fd1991 docs(inout): DB 생성 명령 — 비밀번호 URL 인코딩·.env 줄 붙음 방지·실제 연결 확인
비밀번호의 @ 등 특수문자가 DSN 을 깨뜨려 /inout/ 이 30초 뒤 500(PoolTimeout)이 된 운영 사례(2026-10-16).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:28:26 +09:00
king e722d8ba1b Merge branch 'feat/inout-module' 2026-10-16 15:21:06 +09:00
king 6f3bffd840 feat(inout): 입출고 관리 모듈 — 공장 제작 발주 · 물류 입고 · 미입고/초과 관리
- 새 모듈 app/modules/inout(/inout/, 권한키 inout) + 새 DB inout_db(사용자 승인, scripts/sql/inout_db_init.sql — 멱등).
- 발주 담당이 공장에 발주서(PO-YYMMDD-NN, 제품 = itemcode_db 단품만 — 검색 + 저장 때 서버 재확인),
  입고 담당이 물류에 들어온 수량을 여러 번 나눠 입력 → 품목별 발주·입고·미입고, 진행률, 입고 예정일 지연.
- 미입고 현황: 제품별 합계 · 발주별(예정일 순) · 초과 입고. 잔량 종결/풀기, 입고 없는 발주 취소, 입고 기록 지우기.
- 초과 입고: 확인 화면(409, 입력 유지) 후 [초과 입고로 저장] — 트랜잭션 안에서 발주서 잠그고 판단, Enter 는 일반 저장.
- 옵션(ERP 관리자): 공장 목록, 발주 담당·입고 담당 지정(inout_roles). 관리자는 둘 다.
- 상태는 저장하지 않고 누적 입고로 계산(store.order_status). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고.
- 테스트: 순수 로직, 실제 PostgreSQL(앱 계정 inout_app — 권한 포함), 실제 앱 화면 흐름(권한별). 문서 INOUT_MODULE.md 등.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:21:05 +09:00
king 80b7becd45 Merge branch 'fix/meta-ads-no-vat' 2026-10-16 14:04:58 +09:00
king 8051e7f207 fix(performance): 메타 광고비에 부가세 1.1 곱하지 않음
- 메타 지출 금액은 이미 부가세 포함(사용자 확인) — 광고비 = 지출 금액 그대로(외화 계정은 × 그날 환율만).
  × 1.1 은 비용이 부가세 별도인 구글만 그대로.
- 일자별 표: "광고비(부가세 포함)"·"지출 금액(부가세 별도)" 두 열 → "지출 금액(부가세 포함)" 한 열.
- 설정·광고비 탭 안내 문구, 문서, 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:04:57 +09:00
king 7933f163b4 Merge branch 'feat/meta-ads-usd-fx' 2026-10-16 13:59:50 +09:00
king 0836d6a926 feat(performance): 메타 외화(USD) 광고 계정 — 그날 환율로 원화 환산
- 예전엔 원화가 아닌 계정이면 "원화 계정만" 오류로 저장 안 함 → 이제 지출 금액·구매 전환값을 그날 환율로 원화 환산해
  다른 계정과 합산(광고비 = 지출 × 환율 × 1.1, ROAS 는 비율이라 그대로).
- fx.py: Frankfurter v2(키 없음, 중앙은행 고시 환율 종합, 매일)에서 기간 환율 한 번에, 빈 날은 앞 가장 가까운 날,
  못 구하면 그 회차 저장 안 함, 지난 날 환율은 프로세스 캐시.
- 계정 탭에 지출 금액(USD)·적용 환율(원)(합계 = 광고비 가중 평균), 연결 테스트·설정 안내 문구 갱신.
- 테스트: 혼합 계정 환산·빈 날 환율·환율 장애·캐시·환율 합계, 실제 Frankfurter 응답으로 파싱 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:59:49 +09:00
king 36b1f49340 Merge branch 'feat/meta-ads-account-tabs' 2026-10-16 13:38:18 +09:00
king b2710a0831 feat(performance): 메타 광고 상세보기 [합계 | 계정별] 탭
- 가져올 때 그날 메타 행 metrics 에 계정별 값(_accounts: 이름·광고비·ROAS·항목, insights account_name)을 함께 저장
  — 새 마이그레이션 없음. "_" 키는 일자별 표 열·합계·화면 값에서 제외.
- ad_spend.detail_tabs: 합계 탭 + 계정 탭(그 계정이 광고 낸 날만, 광고비 큰 계정부터), 계정별 값 없는 날 수 안내.
- 상세보기 창: 탭(주황 강조, 계정 ID 말풍선), 계정 탭은 1원 반올림 차이 안내. 네이버·구글은 그대로 표 하나.
- 테스트: 계정별 변환·탭 순서/이름/가중 ROAS·옛 자료 안내·API 응답, jsdom 탭 전환.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:38:17 +09:00
king 8bbb1f9ab2 Merge branch 'fix/meta-ads-diagnosis-cut' 2026-10-16 13:26:50 +09:00
king 8a597007cb fix(performance): 메타 연결 테스트 진단이 잘리던 문제
- 비밀값 가림(redact_text)의 기본 300자 한도에서 긴 메타 원문·안내 뒤의 [진단]이 "[진…"으로 잘렸다.
- 연결 테스트 문구를 [진단] 먼저 + 메타 원문(긴 안내 주소 제거) 뒤로 바꾸고,
  광고 연동 오류 문구 한도를 ad_sync.AD_MESSAGE_MAX(1200자)로.
- 테스트: 설정 연결 테스트 경로(AdSyncService)에서 진단 전체·순서·주소 제거·토큰 미포함 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:26:49 +09:00
king dc54553d2f Merge branch 'fix/meta-ads-permission-diagnosis' 2026-10-16 13:21:51 +09:00
king 527ec83b30 feat(performance): 메타 광고 권한 오류(#200) 원인 진단
- 연결 테스트가 권한 오류를 받으면 메타에 debug_token(권한·대상 계정·만료, 안 되면 me/permissions)과
  me/adaccounts(보이는 계정)를 물어 원인 하나를 짚는다: ads_read 없음 / 계정 미배정 / 권한이 다른 계정에만 / 앱 쪽.
- 광고비 탭 불러오기의 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내. 진단 문구에도 토큰 미포함.
- 테스트 7개 추가(원인별 결론·폴백·안내 위치).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:21:50 +09:00
king abf03f0a80 Merge branch 'feat/meta-ads-api' 2026-10-16 13:09:44 +09:00
king b397bdf83b feat(performance): 메타 광고 API 연동 — 광고비·구매 ROAS 자동 가져오기
- ad_sources/meta_ads.py + registry 한 줄: Meta Marketing API Insights(기본 v26.0),
  level=account·하루 단위, 광고 계정 여러 개를 날짜별로 합산, paging.next 따라감(graph.facebook.com 밖 주소 거부).
- 설정(실적 설정 → 광고 API 연동): 광고 계정 ID(여러 개)·액세스 토큰(암호화)·앱 시크릿(선택, appsecret_proof)·API 버전.
- 광고비 = 지출 금액 × 1.1(부가세 포함, 구글과 같은 기준), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS).
  구매 값은 omni_purchase → purchase → 픽셀 구매 중 처음 있는 것 하나(겹친 값 더하지 않음). 원화 계정만.
- 메타 오류 코드 안내(토큰 만료 190·권한 200·계정 ID 100·호출 한도), 오류 문구에 토큰·주소 미포함.
- 메타 머리글 = 일자별 보고서 표(DETAIL_CHANNELS), 화면 안내 문구·문서 갱신. 새 마이그레이션·환경변수 없음.
- 테스트: test_meta_ads.py(가짜 메타 서버, 실제 fetch_days → AdSyncService), 메타 연동 반영해 기존 테스트 기대값 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:09:43 +09:00
king 32457e4ce8 Merge branch 'feat/project-options-system' 2026-10-16 10:29:39 +09:00
king 94fac65238 feat(project): Project 옵션 시스템 전체 적용 + 모달 안 말풍선 가림 수정
- 프로젝트 화면(처음 여는 탭)·보드(카드 표지)는 서버 저장(project_db.project_options, 마이그레이션 029)
  → 수퍼관리자·Admin 이 바꾸면 모든 사용자에게 적용. 일반(폰트)은 그대로 이 브라우저(localStorage).
- GET/PUT /project/api/options(쓰기는 Admin 이상, 보낸 키만, 029 미적용 503). 검사·기본값은
  store.normalize/validate_project_options 한 곳. 프로젝트 화면은 data-default-view·data-board-cover 로 받음
  (읽기 실패해도 기본값으로 열림).
- 옵션 창: 열 때 서버 최신값 읽기(실패 시 시스템 칸 잠금·폰트만 저장), 바뀐 키만 PUT, 실패면 창 유지.
  분류 제목 옆 적용 범위 배지(이 브라우저에만 / 모든 사용자에게).
- 공용 말풍선: 모달 대화창(showModal) 안에서는 popover(top layer)로 띄워 대화창 뒤에 가려지지 않게.
- 테스트: tests/test_project_options_api.py, jsdom 옵션 테스트 갱신. 도움말·문서·DEPLOYMENT(029) 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:29:37 +09:00
king 1cabad8e3b Merge branch 'feat/project-options-admin' 2026-10-16 10:11:46 +09:00
king e753e55aa1 feat(project): Project 옵션 — 처음 여는 탭·보드 표지를 Admin 에게도
- 프로젝트 화면·보드 분류: 수퍼관리자 → 수퍼관리자·Admin(pj_admin / project.js isPAdmin).
- 관리자(긴급 공지) 분류는 그대로 수퍼관리자만(공지 화면이 수퍼관리자 전용).
- Pro user·User 는 폰트만, 브라우저에 남은 첫 탭·표지 값은 무시(기본값).
- Admin 테스트 추가, 도움말·문서 갱신, project.js 캐시 버전 올림.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:11:45 +09:00
king 31db917eb8 chore(notice): project.js 캐시 버전 맞춤(20261016b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:08:41 +09:00
king 59dd7e2ef9 Merge branch 'feat/project-options-super-only' 2026-10-16 10:08:22 +09:00
king 30b0366818 feat(project): Project 옵션 — 폰트만 모두에게, 처음 여는 탭·보드 표지·관리자는 수퍼관리자만
- 옵션 창의 프로젝트 화면·보드 분류를 수퍼관리자에게만 렌더(관리자 분류와 같은 조건).
- 수퍼관리자가 아니면 project.js 가 브라우저에 남은 pj_default_view·pj_board_cover 를 무시하고
  기본값(보드·표지 켬)으로 동작. 일반 사용자 저장은 pj_font 만 씀.
- 테스트: 수퍼관리자 렌더(project_super_render.html) 추가, 일반 사용자 경우 테스트. 도움말·문서 갱신.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:08:21 +09:00
king d6b15a6aec Merge branch 'feat/project-options-dialog' 2026-10-16 10:03:33 +09:00
king ed7b2ef3ca feat(project): Project 옵션 창 개편 — 분류별 설정 + 보드 카드 표지·처음 여는 탭
- 옵션 창을 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정 구조로 개편,
  아래 [기본값으로]·취소·저장(한꺼번에 저장). 폰트·긴급 공지(수퍼관리자)는 그대로.
- 보드: 카드 표지 이미지 켜기/끄기(localStorage pj_board_cover, 기본 켬) — 저장하면 보던 보드에 바로 반영.
- 프로젝트 화면: 처음 여는 탭(pj_default_view — 보드·목록·캘린더·타임라인·대시보드).
  달력 월 이동 복원·전체 보기(대시보드)·업무 창 패널(embed)은 기존 동작 유지.
- 도움말·docs/PROJECT_MODULE.md·CLAUDE.md 갱신, jsdom 테스트 추가, 정적 파일 버전 올림.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:03:32 +09:00
king 70743394d8 Merge branch 'fix/code-review-2026-10-15' 2026-10-15 18:54:19 +09:00
king c7cc94a09c fix: 2026-10-15 코드 검토 F01~F10 — 수집 실패 전파·트랜잭션 경계·저장 실패·공지 버전/확인 조건·테스트 체계
- F01 쿠팡: HTTP 200 비JSON·data 목록 없음은 수집 실패(기간 교체 안 함), 정상 빈 목록과 구분
- F02 회의록 [적용]: 업무 INSERT 와 줄 연결을 한 연결·한 트랜잭션(_insert_task), 확인은 잠그기 전·알림/메일은 커밋 뒤, 줄 바뀜 409
- F03 업무 등록 표: persist 실패 전파, 미저장이면 [적용] 중단, 초안 유지·다시 저장·이탈 경고
- F04 인증정보 변경 시 내부 토큰 삭제 + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음, GS샵 방식 캐시도 키 지문 기준
- F05 쪽 수 상한·커서 반복 = 실패(쿠팡은 구간을 하루까지 나눠 재시도), 네이버·카카오·토스·GS샵 동일 기준
- F06 [중지] 확인과 저장 시작을 같은 잠금(begin_saving), 저장 시작 뒤 중지 불가
- F07/F08 긴급 공지: 내용 version·고친 공지 다시 그리기·확인에 version(409), 확인은 행 잠금 트랜잭션에서 수신자·표시 시각·취소 검증
- F09 쇼핑몰 연결 테스트도 clear 처리·저장 안 한 시험은 상태 유지(광고 테스트와 같은 계약)
- F10 DB 테스트 skip·가짜 app.main/time.sleep 파일 범위 fixture, 오래된 기대값 갱신, pytest.ini·requirements-dev·tests/js/package.json·docs/TESTING.md
- 결과·후속 과제: docs/CODE_REVIEW_2026-10-15_RESULT.md (마이그레이션·환경변수 변경 없음)

Python 440 passed/63 skipped(DB 없음), 503 passed(로컬 PostgreSQL), jsdom 7종·Edge 6종 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:41:42 +09:00
king edd5a97a9b Merge branch 'fix/cafe24-portrait-layout' 2026-10-15 16:50:18 +09:00
king 5a4ceead3e fix(cafe24): 세로 모니터에서 상품관리 화면이 겹치던 문제
- 한 줄(≤1100px): ≤1360 의 행 틀이 남아 목록이 24px 로 눌리고 편집기(56vh)가 아래 정보 패널과 겹쳤음
  → 화면 높이에 가두지 않고 칸마다 제 높이로 쌓아 페이지가 스크롤(grid-template-rows 초기화)
- 세로 화면은 1600px 이하에서 2분할(정보 패널을 편집기 아래로) — 1440폭(2560×1440 세로)에서 편집기가 288px 였음
- 3분할 목록 칸은 편집기 640px 를 남기도록 먼저 줄어듦(320~460px) — 가로 1366~1600 편집기도 넓어짐
- 2분할 편집기 칸 높이 = 화면 − 정보 패널(38vh) − 머리, 메모·버튼 줄 줄바꿈([카페24에 적용] 잘림 방지)
- 1080·1200·1440 세로, 1366~2560 가로 9가지 크기에서 겹침·버튼 잘림 없음 확인(Edge)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:50:17 +09:00
king fa6bb33f11 Merge branch 'feat/google-ads-vat' 2026-10-15 15:47:58 +09:00
king 5eaeee2f57 feat(performance): 구글 광고비를 부가세 포함(비용 × 1.1)으로 저장
- 광고비 = cost_micros ÷ 10^6 × 1.1 원 반올림(쿠팡 청구금액과 같은 부가세 포함 기준)
- ROAS 는 구글 화면 값 그대로(전환 가치 ÷ 부가세 별도 비용), 일자별 표에 광고비(부가세 포함)·비용(부가세 별도) 둘 다
- 설정·광고비 화면 안내와 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:47:57 +09:00
king 2e428aa07f Merge branch 'fix/google-ads-login-cid' 2026-10-15 15:24:48 +09:00
king 4eda10df00 fix(performance): 구글 광고 INVALID_LOGIN_CUSTOMER_ID 안내 + 저장된 일반 칸을 비우면 지워지게
- 로그인 고객 ID(MCC) 오류에 "직접 추가했다면 칸을 비우고, MCC 면 서비스 계정을 추가한 그 MCC 번호" 안내
- API 설정 창: 저장값이 보이던 일반(비밀 아님) 선택 칸을 비우면 [저장] 때 지우고(clear), [연결 테스트]도 빈 값으로 시험
  (예전엔 빈 칸 = 기존 값 유지라 한 번 넣은 MCC 번호를 지울 수 없었음)
- performance.js 20261015b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:24:47 +09:00
king 42d2671f80 Merge branch 'fix/google-ads-no-dev-token' 2026-10-15 15:20:22 +09:00
king 66a99e2733 fix(performance): 구글 광고 — 개발자 토큰 입력칸·머리글 제거(구글 2026-09-09 폐지)
- 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙는다 — 토큰 입력 불필요
- developer-token 머리글은 무시되고 다음 큰 버전부터 거부 예정이라 보내지 않음
- CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION·AUTHORIZATION_ERROR 안내 추가, 설정 창 안내 문구·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:20:21 +09:00
king 3ead7aa9f6 Merge branch 'feat/google-ads-api' 2026-10-15 15:10:04 +09:00
king e7b1e17579 feat(performance): 광고비 탭 구글 광고비·ROAS 를 Google Ads API 로 가져오기 + 설정에서 키 입력
- 실적 설정 "광고 API 연동" 카드: 개발자 토큰·고객 ID·로그인 고객 ID(MCC)·서비스 계정 JSON·API 버전(기본 v26)
  → 쇼핑몰과 같은 마스터 키로 암호화(perf_ad_credentials, AAD perf:ad:…), 연결 테스트·상태(perf_ad_source_status)
- ad_sources/(채널 하나 = 파일 하나) + google_ads.py: 서비스 계정 JWT 토큰(httpx) → REST searchStream GAQL,
  비용(cost_micros 원 반올림, 부가세 별도)·ROAS(전환 가치÷비용)·노출·클릭·전환 항목, KRW 계정만, 오류 코드별 안내
- ad_sync.py: 기간 한 트랜잭션 저장(source='api', 안 준 날은 예전 API 값만 지움), 같은 채널 동시 실행 차단, 비밀값 가림
- 광고비 탭 [구글 광고 불러오기](보는 기간, 92일 넘으면 관리자) + 매출 자동 업데이트 회차에 함께, API 값 초록 숫자,
  구글 머리글 = 일자별 항목 표
- 마이그레이션 007, 테스트 test_google_ads.py(가짜 구글 서버) — performance 테스트 83개 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:10:03 +09:00
king cd33c67df9 Merge branch 'feat/dbx-side-and-content' 2026-10-15 13:26:12 +09:00
king 0bb23c32de feat(project): 성공하기 버튼을 사이드바 프로젝트 목록 위로 + dbx.html 탭 순서·강조
- [성공하기] 수신함 머리 → 왼쪽 사이드바 프로젝트 목록 위(_side.html, 모든 Project 화면), 아이콘 120%
- 창 여는 코드는 project.js 문서 단위 클릭 위임(팝업 막힘 안내)
- dbx.html: "DBX 존재이유 / 일하는 법", 형광 노랑 <mark>, 탭 순서 변경, 일 잘한다·의문 줄 굵게, 마지막 질문 굵게+형광
- project.css 20261015d, project.js 20261015b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:26:11 +09:00
king f0aae513af Merge branch 'fix/desc-image-copy' 2026-10-15 13:04:01 +09:00
king 8ad8242c41 fix(project): 설명란 이미지 복사 — Ctrl+C·보기 창 [복사] 로 PNG 그림만 클립보드에
- 원인: 설명란 이미지 "선택"은 편집기 표시라 기본 Ctrl+C 로는 아무것도 복사되지 않았고,
  브라우저 "이미지 복사"는 <img src=첨부 주소> HTML 을 같이 넣어 로그인 없는 프로그램(카카오톡·한글 등)엔 빈칸
- copyImageToClipboard: 캔버스로 PNG 변환 → navigator.clipboard.write(ClipboardItem, Promise)
- 설명란 고른 이미지 Ctrl+C(한글 입력 상태 e.code), 글자를 골라 둔 상태면 기본 복사 그대로
- 이미지 보기 창: 아래 막대 [복사] 버튼 + Ctrl+C, 위쪽 알림
- tests/js/image_copy.browser.test.js (Edge 로 9항목 통과), project.js 버전 20261015a, 도움말·문서

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:04:00 +09:00
king 32877b1ce8 Merge branch 'feat/inbox-dbx-left' 2026-10-15 12:33:26 +09:00
king 1550b5bb51 feat(project): 수신함 [성공하기] 버튼을 머리 줄 맨 왼쪽으로
- 머리 줄 = [성공하기] | 제목(정가운데·굵게) | 버튼들, project.css 버전 20261015c

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:33:25 +09:00
king 35c05e1b81 Merge branch 'feat/inbox-title-dbx-tabs' 2026-10-15 12:31:45 +09:00
king 8b5498bc19 feat(project): 수신함 제목 가운데·굵게 + 성공하기 창 탭에 미끄러지는 사각형 하이라이트
- 수신함 머리 1fr|제목|1fr 격자 — 제목 정가운데·700, [성공하기]는 제목 오른쪽(절대 배치)
- dbx.html 탭: Project 뷰 탭처럼 옅은 보라 사각형(.tab-hl)이 고른 탭으로 이동(줄 바뀜도 따라감)
- project.css 버전 20261015b

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:31:44 +09:00
king bdd03a9ea4 Merge branch 'feat/dbx-news-title' 2026-10-15 12:25:51 +09:00
king 0396cd6639 feat(project): 성공하기 창 — 신문 링크 아래에 기사 제목·부제·출처를 크게
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:25:50 +09:00
king f1f0db1bbe Merge branch 'feat/dbx-marketing-photo' 2026-10-15 12:24:37 +09:00
king 3061d44236 feat(project): 성공하기 창 — 마케팅 "2. 키컬러 폰트의 적절함" 아래 바로척병원 외벽 사진
- app/static/dbx/inline.jpg (JPEG 105KB, 원본 PNG 880KB 변환), 창 폭에 맞게 줄어듦

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:24:36 +09:00
king 5e70ec1819 Merge branch 'feat/inbox-dbx-popup' 2026-10-15 12:19:29 +09:00
king e5d6a1188c feat(project): 수신함 [성공하기] 별도 창(dbx.html) + 모두 확인/읽음 아이콘 버튼 + PC 알림 프로그램 설치
- GET /project/dbx: 모듈 폴더 dbx.html 을 그대로(로그인·project 권한), 수신함 제목 옆 버튼 → 닫기만 있는 팝업 창
- 태그 모두 확인·알림 모두 읽음은 아이콘만(title 말풍선), [PC 알림] → [PC 알림 프로그램 설치]
- project.css 버전 20261015a, 도움말·PROJECT_MODULE.md 6-21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:19:25 +09:00
king c23d1e3ce5 Merge branch 'fix/coupang-ad-skip-empty' 2026-10-14 17:43:00 +09:00
king bab495d9f2 fix(performance): 쿠팡 광고 보고서 — 청구금액이 없는 날짜·파일은 오류 없이 넘어감
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:42:59 +09:00
king bbe27eac8b Merge branch 'fix/coupang-ad-report-rows' 2026-10-14 17:38:09 +09:00
king 53896f0425 fix(performance): 쿠팡 광고 보고서 = 1열에 날짜가 있는 줄의 19열 값(빈 줄 건너뜀, 같은 날 합산)
쿠팡(윙) 보고서는 캠페인 줄에도 날짜가 있고 19열이 비어 있어 "청구금액이 비어 있습니다" 오류로 전부 막혔다.
금액이 한 줄도 없던 날은 업로드 창에 알려 준다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:38:08 +09:00
king db73faf270 Merge branch 'feat/ad-upload-multi' 2026-10-14 17:32:02 +09:00
king e3bc9d518d feat(performance): 광고비 파일 여러 개 업로드(같은 날짜는 최신 파일) + 끝나면 창 닫기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:32:01 +09:00
king 15a5eddf20 Merge branch 'feat/ad-naver-upload' 2026-10-14 17:23:14 +09:00
king e9fb1c3407 feat(performance): 네이버 광고 보고서 업로드(ROAS·보고서 항목) + 머리글 클릭 일자별 상세
- 네이버 업로드: 3열 기간·4열 총비용(광고비)·12열 구매완료 광고수익률(ROAS), 나머지 항목은 metrics(JSONB)
- 네이버·구글·메타 칸 ROAS = 보고서 값(여러 날은 광고비 가중 평균), 쇼핑몰 매출로 계산하지 않음
- 네이버 머리글 클릭 → 지금 기간 일자별 보고서 표 + 합계(GET /api/ad-spend/naver/details)
- performance_db 마이그레이션 006: perf_ad_spend.roas·metrics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:23:11 +09:00
king 240d61c903 Merge branch 'fix/overdue-close-tooltip' 2026-10-14 16:09:47 +09:00
king e645f4beef style(project): 마감 지난 업무 알림 닫기 버튼 말풍선 삭제
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:09:46 +09:00
king 4466601c58 Merge branch 'fix/overdue-close-label' 2026-10-14 15:39:07 +09:00
king c3cab212b6 style(project): 마감 지난 업무 알림 닫기 버튼 글자 "(1시간 뒤 다시)" 삭제
1시간 뒤 다시 알리는 동작·말풍선 안내는 그대로.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:39:06 +09:00
king b61c0897cc Merge branch 'fix/project-pages-login-redirect' 2026-10-14 12:48:00 +09:00
king 5c05f471b3 fix(project): 로그인 전 화면 주소는 오류 JSON 대신 로그인 화면 → 원래 주소로
공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열면 {"detail":"로그인이 필요합니다."} 가 보이던 문제.
내 업무·프로젝트·휴지통·도움말·수신함·목표·회의록 화면은 /login?next= 로 보낸다. API 는 그대로 401.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 12:47:59 +09:00
king 4e159e94e7 Merge branch 'fix/ad-roas-no-google-meta' 2026-10-14 11:10:10 +09:00
king db05538664 fix(performance): 광고비 구글·메타는 ROAS 계산 안 함(따로 입력 예정)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:10:09 +09:00
king ea7817752d Merge branch 'feat/project-subtask-ux-ad-roas' 2026-10-14 10:57:32 +09:00
king 67001f0a6e feat: 세부 업무 자동 협업자 없음·마감일 아이콘·담당자별 패널 날짜 + 광고비 13채널·ROAS
[Project]
- 세부 업무를 만들 때 만든 사람을 자동 협업자로 넣지 않음(고른 협업자만), 메인 업무는 그대로
- 업무 창 세부 업무 줄의 빈 마감일 아이콘을 협업자 아이콘처럼 늘 옅게
- 대시보드 담당자별 합계 패널 날짜 mm/dd(요일), 마감 지난 미완료는 빨간 굵은 글씨

[실적 — 광고비]
- 열: 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰
- 칸 = 광고비(ROAS%), ROAS = 그 쇼핑몰 매출 ÷ 광고비(구글·메타 = 카페24), 월/연 누적에도 ROAS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:57:30 +09:00
king c30ef72c6e Merge branch 'feat/performance-ad-wing-upload' 2026-10-14 09:57:06 +09:00
king 581e0cf325 feat(performance): 쿠팡(윙) 광고비도 파일 업로드(로켓과 같은 광고 보고서 양식)
- 업로드 창 채널 = 쿠팡(윙) · 쿠팡(로켓), 1열 날짜 · 19열 청구금액(+부가가치세)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:57:02 +09:00
king e6b2812624 Merge branch 'feat/workload-avatar' 2026-10-13 23:43:23 +09:00
king 30fd2c5470 feat(project): 대시보드 담당자별 합계 이름 왼쪽에 프로필 아이콘
사진이 있으면 구글 프로필 사진, 없으면 기본 사람 아이콘(avatarHtml 공용).
정적 파일 캐시 키 20261013i.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:43:22 +09:00
king 2df86983da Merge branch 'fix/dashboard-card-fade' 2026-10-13 23:37:04 +09:00
king 90332bcb59 fix(project): 대시보드 다시 그릴 때 카드 페이드인 반복 제거
카드·숫자 타일의 등장 애니메이션(opacity 0 → 1)이 다시 그릴 때마다
재생돼 업무 창을 닫으면 그래프가 잠깐 사라졌다 나타났다(실제 크롬에서
프레임별 opacity 측정으로 확인). 등장 애니메이션은 대시보드 탭에 들어올
때만(.pj-dash-intro) 켠다. 정적 파일 캐시 키도 올림(20261013h).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:37:04 +09:00
king 1c42ed5dd3 Merge branch 'fix/dashboard-no-flicker' 2026-10-13 23:30:40 +09:00
king 779cc79a87 fix(project): 대시보드 다시 그릴 때 깜박임 제거
업무 창을 닫으면 대시보드를 통째로 다시 그리면서 숫자·막대·도넛이 0부터
다시 차오르고, 담당자별 업무 목록 패널을 닫았다 새로 열어 어두운 배경이
꺼졌다 켜졌다.

- 열린 목록 패널은 재사용해 내용만 교체(스크롤·고른 줄 유지)
- 숫자·막대·도넛은 마지막 값에서 시작, 바뀐 값만 애니메이션
  (0부터는 대시보드 탭에 들어올 때만)
- 카드 안 스크롤 위치 유지, 같은 세부 업무 목록으로 중복 그리기 생략

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:30:36 +09:00
king 1ba494dab8 Merge branch 'feat/performance-ad-spend' 2026-10-13 18:20:45 +09:00
king ef38140673 feat(performance): 광고비 탭(구글·메타·쿠팡 윙/로켓) + 탭 개편·설정 톱니
- 탭: [매출 실적](검정) · [광고비](주황) 큰 탭 + 맨 오른쪽 설정 톱니(Material Symbols settings)
- /performance/ads: 연·월·일 표(채널 × 날짜)·추이·비중·월/연 누적, 매출 대비 광고비 KPI
- 날짜 칸 직접 입력(PUT /api/ad-spend/{channel}/{day}), 쿠팡(로켓) 광고 보고서 업로드
  (CSV/엑셀, 1열 날짜·19열 청구금액(+부가가치세), 잘못된 줄 있으면 전부 거절)
- performance_db 마이그레이션 005 perf_ad_spend
- 설정 화면 쇼핑몰 순서 jsdom 기대값을 003 열 순서로 갱신(기존 실패)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:20:44 +09:00
king 099271fdb2 Merge branch 'feat/performance-kakao-adapter' 2026-10-13 16:11:29 +09:00
king e6d38f342f feat(performance): 카카오쇼핑 Open API 매출 수집(결제일 기준)
- kapi.kakao.com, Authorization(앱 어드민 키)·Target-Authorization(판매자 API 인증키)·channel-ids 헤더
- 결제일시 기준 주문내역(paidAt, 하루씩·token 페이징) → 주문정보(order_id)로 금액
- 결제(paymentId) 하나 = SALE, (상품가+옵션가)×수량 − 할인, 배송비 제외, 미결제만 제외
- 인증 오류(-2·-401·대행사 매핑) 안내, 개인정보는 받자마자 지움, 원본 데이터 확인 지원

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:11:28 +09:00
king f8245b4499 Merge branch 'feat/card-follower-hover' 2026-10-13 14:48:54 +09:00
king 9a8aea6435 feat(project): 보드 카드에 마우스를 올리면 협업자 추가 아이콘(담당자 오른쪽)
- 누르면 협업자를 받아 멤버 메뉴, 고르면 바로 저장하고 카드에 표시(담당자는 후보에서 뺌)
- 테스트: 메뉴의 문서 Esc 처리기가 붙기 전에 Esc 를 보내던 타이밍 문제 수정(wait 후 Esc)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:48:49 +09:00
king eab6b836d2 Merge branch 'feat/main-task-add-followers' 2026-10-13 14:40:18 +09:00
king deb5bfb9a1 feat(project): 보드 메인 업무 추가 카드에 협업자 아이콘(담당자 옆)
- 고른 협업자는 만들 때 followers 로 같이 저장, 담당자는 후보에서 빼고 담당자로 고르면 협업자에서 뺌

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:40:17 +09:00
king 4d3b747ab7 Merge branch 'fix/subtask-add-icons' 2026-10-13 14:30:41 +09:00
king 5471cbc32b fix(project): 세부 업무 추가 칸 아이콘을 보드 카드 새 줄과 같게(마감일·담당자·협업자, 24px)
- 업무 창 세부 업무 추가 칸 순서를 마감일 → 담당자 → 협업자로, 빈 협업자는 점선 원 두 사람 아이콘
- 세 아이콘 크기를 24px 로 통일(담당자만 18px 로 작게 보이던 것 수정)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:30:40 +09:00
king 4c94bf1293 Merge branch 'feat/project-followers-rules' 2026-10-13 14:24:52 +09:00
king f36f7d3ad4 feat(project): 담당자는 협업자에서 제외·세부 업무 추가 칸 아이콘·내 업무 오른쪽 창
- 협업자 = 담당자 외의 멤버: add_followers 가 담당자를 거르고, 담당자 지정 시 같은 트랜잭션에서 협업자에서 뺌, 담당자 협업자 추가는 400
- 마이그레이션 028: 이미 겹친 task_followers 행 정리(스키마 변경 없음, 멱등)
- 업무 창 세부 업무 추가 칸: 담당자·협업자·마감일을 동그라미 아이콘 버튼으로, 제목 칸을 넓게
- 내 업무 화면: 줄 클릭 시 화면 이동 없이 오른쪽 업무 창(iframe), 닫으면 목록 다시 받기
- 대시보드 "미완료 업무 합계(섹션별)" 카드 삭제

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:24:51 +09:00
king 5bd0a5c406 Merge branch 'feat/project-move-task-drag' 2026-10-13 13:34:53 +09:00
king c317d7bb5d feat(project): 업무를 왼쪽 프로젝트로 끌어 다른 프로젝트로 이동(섹션 선택 창)
- 보드 카드를 사이드바 프로젝트 줄에 놓으면 섹션 선택 창 → POST /api/tasks/{id}/move-project
- 세부 업무(모든 단계)까지 한 트랜잭션으로 이동, 섹션 기본 담당자·완료 섹션 규칙, 대상 쪽 연결 정리
- 원 소속 권한 + 대상 프로젝트 멤버만, 대상 프로젝트를 볼 수 없는 담당자·협업자는 화면에 안내

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:34:51 +09:00
king 941b35a7a6 Merge branch 'feat/project-followers-overdue' 2026-10-13 13:10:59 +09:00
king ecc6405299 feat(project): 세부 업무 협업자 등록·대시보드 프로젝트별·마감 지난 업무 알림
- 세부 업무를 만들 때 협업자도 같이(업무 창 추가 칸·보드 카드 새 줄) — POST tasks 의 followers, 비멤버면 400
- 보드 카드 세부 업무 줄에도 협업자 아이콘, 업무 창 줄의 빈 협업자 아이콘은 늘 보이게
- 협업자 메뉴는 고를 때마다 다시 열려 여러 명을 이어서 지정(openFollowerMenu 공용)
- 대시보드 "업무 합계(프로젝트별)" 카드 — 완료 상태별 카드 왼쪽, 프로젝트별 완료/전체·완료율
- 마감 지난 내 업무 위쪽 알림(ERP 모든 화면, erp-overdue.js, GET /project/api/my-overdue) — 닫으면 1시간 뒤 다시, 새로 지난 업무는 바로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:10:57 +09:00
king 028831694a Merge branch 'feat/project-terms-ux' 2026-10-13 11:27:46 +09:00
king 542e7fb7d1 feat(project): 용어 "업무" 통일·섹션 담당자 바로 지정·세부 업무 협업자·반응 알림
- 화면·메시지·알림 제목·도움말의 "작업" → "업무"(조사 포함). 큰 알림 팝업·PC 알림 소스는 예전 "작업 배정:" 접두어도 뗀다
- 보드·목록 섹션 제목 오른쪽 담당자 아이콘을 눌러 기본 담당자를 그 자리에서 지정
- 섹션을 접으면 제목 보통 굵기, 펼치면 다시 굵게
- 업무 창 세부 업무 줄 담당자 오른쪽에 협업자 지정(subtasks[].followers, list_followers_of)
- 댓글 이모티콘 반응을 켜면 댓글 쓴 사람에게 어떤 이모티콘인지 수신함 알림(type=reaction)
- 왼쪽 전체 보기의 기본 보기는 대시보드
- 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에 열림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:27:38 +09:00
king ac0f48bfce Merge branch 'fix/probe-range-notice' 2026-10-13 06:08:22 +09:00
king 68bf43ea2f fix(performance): raw-data check shows the period it actually queried
The settings raw-data check queries at most 31 days; a longer range was
silently cut to the first 31 days, so a "1 year" check looked successful.
Now the result starts with the queried period and, when cut, a warning that
points to [과거 매출 가져오기] for long ranges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 06:08:22 +09:00
king cf7c44ce49 fix(performance): coupang 504 timeouts shrink the query window instead of failing
A 31-day FINAL_DELIVERY ordersheet query times out at Coupang's gateway
(504 "Request timed out"). On 502/503/504 or a client timeout the window
is halved (31 -> 15 -> 7 -> 3 -> 1 day) and retried; the shrunk size is
kept for the same status's next windows. Rocket Growth orders do the same.
A 1-day window that still times out is retried twice (3s, 6s) then fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:53:07 +09:00
king db3b7d500d Merge branch 'fix/coupang-error-span' 2026-10-13 05:49:18 +09:00
king d5fd617425 fix(performance): coupang API errors name the failing period and status
Long updates are split into 31-day (seller) / 30-day (Rocket Growth)
calls; the error now says which window failed so long-range failures can
be diagnosed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:49:17 +09:00
king bed3d4fc89 Merge branch 'feat/perf-auto-sync' 2026-10-13 05:28:48 +09:00
king 822c955bb6 feat(performance): automatic sales update every 30 min, 09:00-19:00 KST
A daemon thread started in the web lifespan runs the same update as the
[매출 업데이트] button at :00 and :30 from 09:00 to 19:00 (21 runs a day),
fetching the last 10 days including today. It runs as a progress job
(user "자동 업데이트", trigger 'schedule'), so a user clicking the button
meanwhile sees the running job. A slot is skipped when another update is
running; overrun slots are not replayed; the slot at server start is not run.

Env: PERFORMANCE_AUTO_SYNC (false = off), PERFORMANCE_AUTO_SYNC_DAYS (10),
PERFORMANCE_AUTO_SYNC_HOURS (9-19).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:28:47 +09:00
king 20a79f5719 Merge branch 'style/perf-delta-blue' 2026-10-13 05:21:53 +09:00
king b4edc16785 style(performance): KPI change colors - good = blue, bad = red
Commission keeps its inverted meaning (a drop is good).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:21:52 +09:00
king 66db501170 Merge branch 'style/perf-upload-btn-excel' 2026-10-13 05:17:49 +09:00
king ac01a33c47 style(performance): Excel-green upload button (same as cupang Excel download)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 05:17:48 +09:00
king 513aece27e Merge branch 'feat/perf-manual-upload' 2026-10-13 04:58:29 +09:00
king 1d3573a44a feat(performance): upload manual-input sales from an Excel file
- [엑셀 업로드] button on the daily x marketplace table opens a popup with
  a sample download (module upload_sample.xlsx) and a file picker
- Format: column 1 = date, columns 2+ = marketplace names as headers
  (setting name / short name / code, spaces and case ignored)
- Only filled cells of marketplaces with manual input ON are saved
  (overwrite same day, blank cells keep existing values); other columns
  are skipped and reported
- Any bad cell (not a number, unreadable/future date, duplicate day) rejects
  the whole file with cell references; saving is one transaction
- Ignore Excel lock files (~$*)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 04:58:00 +09:00
king 410d4fe05c Merge branch 'fix/cupang-box-table-width' 2026-10-13 03:10:33 +09:00
king c15a746ae4 style(cupang): box list table right edge lines up with the summary cards
The scroll area reserved a 10px scrollbar gutter + 2px padding inside the card
content width, so the table was 12px narrower than the KPI cards. Move that
space into the card's 16px padding (margin-right: -12px); reset on narrow
screens where the list does not scroll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:10:32 +09:00
king da46abd678 Merge branch 'feat/cupang-box-table-align' 2026-10-13 03:06:51 +09:00
king d38d00b4d2 style(cupang): box list total spans 3 columns, center-aligned cells, 20px gap above table
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 03:06:51 +09:00
king 8201fde606 Merge branch 'feat/perf-naver-name' 2026-10-13 02:55:34 +09:00
king 70bf263a80 feat(performance): rename 네이버 스마트스토어 to 네이버 (migration 004)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 02:55:34 +09:00
king 5a2c6ba2ad Merge branch 'feat/perf-marketplace-order' 2026-10-13 02:35:19 +09:00
king 6ebf705e27 feat(performance): new marketplace order, 쿠팡(윙) rename, manual-only 쿠팡(로켓)·애터미아자몰
- Column order: 카페24 · 네이버 · 쿠팡(윙) · 쿠팡(로켓) · 오늘의집 · G마켓 · 카카오 ·
  GS샵 · 11번가 · 롯데ON · 토스 · 애터미아자몰 (registry + migration 003 sort_order)
- Existing coupang (WING API) renamed to 쿠팡(윙)
- New manual-only marketplaces coupang_rocket / atomy (adapters/manual.py,
  manual_only flag): skipped by sync_all, no credentials / connection test in
  settings, status "수동 입력", manual input always on (API refuses turning it off)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 02:35:18 +09:00
king 22490664d6 Merge branch 'feat/cupang-box-total' 2026-10-12 20:58:08 +09:00
king 0c6dacb824 feat(cupang): shipment box list shows weights in kg with a totals row
Box weights on the shipment detail screen are now shown in kg, rounded
half-up to one decimal. A footer row sums quantity and weight (marks
"일부 미입력" when some product weights are missing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:57:56 +09:00
king 6345b69816 Merge branch 'feat/meeting-label-groups' 2026-10-12 20:28:29 +09:00
king 3882836fd5 feat(project): meeting rows added from the task cell stay in the same item cell (migration 027), in-place redraw with animation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:28:24 +09:00
king 59add598fa Merge branch 'fix/perf-manual-cell-width' 2026-10-12 17:31:12 +09:00
king ca2821464f fix(performance): manual input overlays the cell so the column no longer widens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:31:07 +09:00
king 24950c94ce Merge branch 'feat/perf-manual-input' 2026-10-12 17:27:03 +09:00
king 454b3cc700 feat(performance): per-shop manual sales input, column order, bold centered table headers (migration 002)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:26:57 +09:00
king dd1bc310dc Merge branch 'feat/perf-coupang-sales' 2026-10-12 17:07:45 +09:00
king 53bead6691 feat(performance): coupang sales - seller-delivery ordersheets + Rocket Growth orders by payment date, reconcile candidates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:07:41 +09:00
king 36283ae265 Merge branch 'feat/meeting-quick-compact' 2026-10-12 16:49:05 +09:00
king 89d204b2fe feat(project): meeting task table - drop header hint, check icon only, icons in one row
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:49:01 +09:00
king 724b590868 Merge branch 'feat/meeting-quick-parent-task' 2026-10-12 16:35:23 +09:00
king e130bbe577 feat(project): meeting task table - pick an existing task to add a subtask; title opens task panel
- New "작업" column (migration 026 parent_task_id): empty = new task in the section,
  chosen task = register as its subtask (candidates = open main tasks of that section)
- Server validates the task belongs to the project, clears it when the project changes,
  and rejects apply if the chosen task was deleted/moved
- Removed the in-table subtask rows (hover button, Tab/Shift+Tab, right-click) from UI/API
- Registered row title opens the task editor on the right (iframe ?embed=1, waits for the
  task window to save before switching/closing, like the inbox panel)
- Help + docs (DEPLOYMENT 026); tests (real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:35:18 +09:00
king bc62e53270 Merge branch 'feat/meeting-quick-subtasks' 2026-10-12 16:20:10 +09:00
king 6fd01314d5 feat(project): subtask rows and a wide view for the meeting task table
- Subtask rows (one level, parent_id): hover button / right-click to add, Tab to make a row the
  subtask of the row above, Shift+Tab to move it back; inherits the parent's project, no section
- Apply on a subtask row creates the task under the parent row's task (server-checked)
- "크게 열기" moves the same table into a wide window (same rows and saves), Esc/x to close
- Server: PUT parent_id with one-level rules; add rejects grandchildren
- Help + docs; tests (real PostgreSQL rules + parent apply, jsdom rows/Tab/wide view)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:20:05 +09:00
king 1bdcd59287 Merge branch 'fix/meeting-quick-shared' 2026-10-12 16:06:28 +09:00
king b7c0f28ad2 fix(project): meeting task table shared per week on the server (others' rows were invisible)
- Cause: the table lived only in each browser's localStorage
- project_db migration 025 goal_meeting_tasks (week_start, parent_id for subtask rows, task_id)
- API list/add/update/delete + apply; apply locks the row and creates the task once via the
  same helper as the task window (_create_task_for: membership, assignee check, notifications)
- Non-members see other people's rows with project/section/task hidden; only member projects
  can be picked; completed meeting is read-only (409)
- Client saves per field, refreshes every 30s / on focus, uploads rows left in this browser once
- Docs (DEPLOYMENT 025, PROJECT_MODULE, help, CLAUDE.md); tests (real PostgreSQL incl. 4
  concurrent applies -> one task, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:06:23 +09:00
king 4320766abd Merge branch 'feat/meeting-quick-hide-done' 2026-10-12 15:13:43 +09:00
king e934dd6abf feat(project): hide completed projects and done sections in meeting task pickers
- Project picker skips status=completed; section picker skips is_done_stage
- Auto-selected first section skips done sections
- Help + docs; jsdom test data covers both

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 15:13:38 +09:00
king 18ac8f0761 Merge branch 'feat/meeting-quick-per-week' 2026-10-12 15:09:59 +09:00
king b5be26089d feat(project): meeting task table kept per week, titled "N주차 작업 등록"
- localStorage key now includes the week start; each week shows only its own rows
- Old per-person rows move into the current week the first time it is opened
- Heading shows the week number; help + docs; jsdom tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 15:09:54 +09:00
king 3a9a94f97b Merge branch 'feat/notice-project-parts' 2026-10-12 14:44:38 +09:00
king c69bc0e9f3 feat(notice): reuse project editor, date popup and member picker on the notice page
- Notice body uses the task description editor (createDescEditor, shared toolbar partial
  project/_desc_fmtbar.html): bold/italic/underline/strike, text color/size, lists, checklist,
  quote, link, clear format, image button/paste with resize; images upload to /notice/api/images
- Show date uses the project date popup (enhanceDateInput) plus a time field
- Recipients rendered like the project member picker (icon + name + check)
- project.js exposes window.PJLib; PJ_LIB_ONLY runs only shared tooltips on non-project pages
- Centered notice renders checklist/quote/list styles outside project pages too
- Task window editor behavior unchanged (jsdom + Chrome regressions pass)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:44:33 +09:00
king 833dbb5fdf Merge branch 'feat/urgent-notice' 2026-10-12 14:07:15 +09:00
king 2aa6b6efae feat(notice): urgent notices centered on every ERP screen until acknowledged
- Super admin only: /notice/ page (title, body with images, show time KST, all or picked people,
  preview, edit with optional re-show, cancel/undo, per-person acknowledgement status)
- Shown on every ERP page (erp_base, main, admin) dead center; [확인] only (no Esc/backdrop close),
  queue in order, ack failure keeps the dialog, closes when acked/cancelled elsewhere
- project_db migration 024 (urgent_notices, targets, acks, images as bytea); shares ProjectStore.pool
- Body sanitized like task descriptions, images restricted to /notice/images/{id}, type sniffed
- Entry points: ERP sidebar foot and Project options dialog (super admin)
- Docs (NOTICE_MODULE, DEPLOYMENT 024, overview, CLAUDE.md); tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:07:10 +09:00
king 1759e00213 Merge branch 'feat/meeting-tips-quick-create' 2026-10-12 13:52:38 +09:00
king fa6e7066ae feat(project): tooltips stay above the cursor; create project/section from meeting task table
- Hover tips: keep above the cursor even near the top edge (tighter tail gap); flip below only
  when there is no room, 28px under the cursor so the pointer never covers the text
- Meeting task table: "new project" (Pro user+) and "new section" at the top of the pickers,
  created by name and selected right away
- Help + docs; jsdom tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:52:34 +09:00
king 7cdca852bd Merge branch 'feat/meeting-section-move' 2026-10-12 13:29:58 +09:00
king ee09e8bfd1 feat(project): move whole meeting sections up/down from the 구분 column
- 구분 cell: right-click or ⋯ menu → 구역 위로 / 구역 아래로 / 구역 끝에 줄 추가
- POST /api/goals/meeting-items/{id}/move-section swaps the contiguous section block
  with its neighbour under the meeting lock (row order and merges follow; 409 after completion)
- Next meetings inherit the new order; help + docs; tests (DB-less, real PostgreSQL, jsdom)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 13:29:53 +09:00
king ae6b6ec603 Merge branch 'feat/project-review-fixes-1012' 2026-10-12 13:23:18 +09:00
king 89ad338024 fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
  old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
  my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
  header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
  read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:08:56 +09:00
king c07a3466a0 Merge branch 'feat/project-role-tiers' 2026-10-12 01:10:33 +09:00
king 5d054e59b6 feat(project): 4-tier roles (super/admin/pro/user), meeting header 구분
- app.store: role "pro" (ROLES, ROLE_LABELS); admin page grade select
  Admin / Pro user / User, super admin fixed to one account.
- project.access: role_of, is_pro, is_project_admin.
- router: _require_admin -> _require_pro (goals, meetings complete/delete,
  members, reorder, trash restore, assignable users); new project and
  project edit/owner change need Pro user+; task delete open to any member;
  project/section delete = Admin+ or creator; comment edit/delete of others
  and workload summary = Pro user+. Templates get pj_pro / pj_admin.
- Weekly meeting table first header "구역" -> "구분".
- Docs (CLAUDE.md, PROJECT_MODULE 6-14, overview, help page) and tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 01:10:25 +09:00
king 061f18d081 Merge branch 'feat/workload-nested-subtasks' 2026-10-08 16:57:40 +09:00
king ee9c04147a feat(project): workload chart counts nested subtasks
subtasks-summary now returns every level under the scope's main tasks
(recursive CTE, depth <= 20) with root_task_id and parent_title; the
dashboard groups by root_task_id. Also fix drawer header '세부 작업 작업'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:57:36 +09:00
king 6a1c437635 Merge branch 'feat/inbox-click-terms-boardcopy' 2026-10-08 16:03:03 +09:00
king 8045d06362 feat(project): click-to-open inbox, 세부 작업 terms, board link copy
- Inbox lists only unread notifications / unchecked mentions; no
  [확인] button: clicking a row marks it (and same-task rows) seen and
  opens the task side panel; picking another row switches the panel and
  removes the previously seen rows; closing removes them too
- Project module wording: 하위 작업 -> 세부 작업, 작업 추가 -> 메인 작업 추가;
  dashboard workload bars "메인 작업" / "세부 작업"
- Meeting: link icon next to 회의록 보드 copies the board URL
- Bump project asset versions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 16:02:58 +09:00
king 85e91ca882 Merge branch 'feat/project-ui-batch-1008' 2026-10-08 13:22:40 +09:00
king 11e9803965 feat(project): asana icons, 12-col colors, bold sections, all-view menu, desc text color/size
- Project edit modal: color palette 12 columns; icon tabs [기본 아이콘] /
  [아사나 아이콘] (33 filled icons, value "asana:<name>", 6KB subset font
  material-symbols-asana.woff2)
- Section names bold (board column, list group, rename input)
- Inbox: clicking the left inbox area closes the task side panel
- Replace top-right scope toggle with admin-only sidebar "전체 보기"
  (?scope=all, switches in place on project pages)
- Description editor: text color and size; server keeps only validated
  color / font-size on plain spans (desc_inline_style)
- Fix goals_meeting_ui [2e] for manual monthly target; bump asset versions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:22:35 +09:00
king 90fb06c48c Merge branch 'feat/login-orbit-sparkle' 2026-10-08 12:32:50 +09:00
king ac3b90f2be feat(login): orbit names sparkle like King
Same glow keyframes as King (text-shadow only, depth opacity stays in
script), random start offset per name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:32:46 +09:00
king a664c4a9fc Merge branch 'feat/login-orbit-size' 2026-10-08 12:30:10 +09:00
king 64aabdfbda feat(login): orbit names up to 80% of King size
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:30:05 +09:00
king 98fda9923e Merge branch 'feat/login-orbit-names' 2026-10-08 11:47:25 +09:00
king 53c7c85caf feat(login): 100px logo, user ids orbit around King
Login brand panel logo is 100px wide (height by ratio). Registered user
ids (email local part, no full email/real name) float around the King
label on random tilted, wobbling elliptical paths; respects
prefers-reduced-motion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:47:21 +09:00
king c380b5e411 Merge branch 'feat/notifier-silence-web' 2026-10-08 11:35:19 +09:00
king 84113d1fd7 feat(project): silence web alert popup while PC notifier is running
If the user has a non-revoked notifier token seen in the last 3 minutes,
/api/notifications/alerts returns only the baseline with desktop=true;
the web marks it seen so alerts resume on the web after the app stops.
A failing check keeps the web popup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:35:14 +09:00
king 4715de9b5b Merge branch 'feat/notifier-in-inbox' 2026-10-08 11:13:31 +09:00
king d7d4f61bfb feat(project): move PC notifier entry into inbox header
Sidebar 'PC 알림' item removed; inbox header gets a [PC 알림] button,
and the notifier page keeps the inbox highlighted with a breadcrumb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:13:27 +09:00
king 69e594ac54 Merge branch 'feat/home-remove-tiles' 2026-10-08 10:40:51 +09:00
king f69219919d feat(home): remove default shortcut/notice tiles from ERP home
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:40:46 +09:00
king 972c94d86c docs(notifier): correct exe size in README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:22:15 +09:00
king f4606bddc6 Merge branch 'feat/pc-notifier' 2026-10-08 10:22:02 +09:00
king 06af036f86 feat(project): PC tray notifier for mentions and assignments
Windows tray app (desktop/notifier, C# .NET Framework 4.8 WinForms,
single exe, no installer/admin) that shows the same big alert popup as
the web even when the browser is in the background: layered topmost
window that does not steal focus, blinking border, open/close actions,
sound, autostart toggle, DPAPI-encrypted token.

Server side (project_db migration 023):
- notifier_links / notifier_tokens (SHA-256 hashes only)
- device link flow: link/start -> browser approve at /project/notifier
  -> link/poll issues token once
- Bearer API for alerts/read/logout reusing _alerts_payload; token
  re-checks current user record and project permission each call
- /project/notifier page (approve, connected PCs, revoke, download)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:21:58 +09:00
king 8f46d6c13a Merge branch 'feat/week-target-month-manual' 2026-10-08 09:20:17 +09:00
king 701f43a1f8 feat(project): manual monthly sales target with weekly diff
Week target popup now has its own "month total" input at the top; the
monthly target is saved as entered instead of being the sum of weeks.
Bottom shows week sum and diff (month target - week sum), colored
for remaining / over / even. Requests without `month` (stale cached JS)
still fall back to the week sum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:20:07 +09:00
king 9eea1a073a Merge branch 'feat/stage-color-alerts-meeting-lock' 2026-10-07 17:37:28 +09:00
king 5278d568de feat(project): weekly meetings editable by anyone, admin completes to lock
Meeting write APIs now accept any project user; deleting a meeting and the
new POST /api/goals/meetings/{week}/complete (complete/reopen) stay admin
only. A completed meeting (migration 022: completed_at, completed_by)
rejects edits with 409; last-week result fields follow the next meeting's
lock instead. The page shows a complete button / locked badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:37:23 +09:00
king 21fc78adb9 feat(project): blinking popup for new mentions and task assignments
Project pages poll GET /api/notifications/alerts every 20s (and when the
tab becomes visible). New unread mention/assigned notifications show in a
large blinking popup at the bottom center until closed; closing in one tab
closes it in the others. A new browser starts from the latest id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:30:15 +09:00
king 4bdab1de3d feat(project): uniform #f3f3f3 section headers, remove section color picker
Stored stage colors are ignored; timeline rows use the project color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:27:59 +09:00
king f90884e028 Merge branch 'feat/quick-task-delete' 2026-10-07 16:57:02 +09:00
king 6959941128 feat(project): delete registered tasks from the meeting task table
Registered rows get a delete button that, after confirmation, deletes the
task from its project (trash). Unapplied rows get an x to drop the row.
Registered rows now stay in the browser list so they can be deleted later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:56:57 +09:00
king 18dd9531ad Merge branch 'fix/member-modal-height' 2026-10-07 16:53:22 +09:00
king 28d56fc3c5 fix(project): member dialog grows to fit everyone instead of scrolling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:53:18 +09:00
king b8d944b3ef Merge branch 'feat/meeting-units-members' 2026-10-07 16:50:46 +09:00
king a0722f26ca feat(project): meeting numbers in sales unit, member add/remove, quick-task polish
- Header numbers use the goal table sales unit (e.g. 백만원); exact won
  amounts in tooltips.
- Notes title: 결정사항 : 진행상황 수시 공유 및 완료 되어야 함.
- Member dialog shows current members checked: check to add, uncheck to
  remove (owner locked); member APIs also require project access.
- Quick task table: centered bold headers, assignee shown as avatar + name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:50:42 +09:00
king 261267a523 Merge branch 'feat/meeting-top-areas' 2026-10-07 16:24:27 +09:00
king da27c9990a feat(project): meeting header with plan, notes and quick task table
Three header areas that stay visible while the table scrolls:
month plan with the four numbers in one compact line, decisions/notes,
and a task table (title, assignee, project, section) whose cells open
pick lists; Apply creates the task in that project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:24:23 +09:00
king 50153139fc Merge branch 'feat/member-no-role' 2026-10-07 15:49:59 +09:00
king c4fb7761ad feat(project): drop member role from assignment
The role select (member/manager) had no effect on permissions; every
assigned member can view and edit the project. Remove it from the
assign dialog and avatar tooltip; new assignments are always member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:49:54 +09:00
king fb7b25ba2c Merge branch 'fix/asset-monitor-same-model' 2026-10-07 15:14:27 +09:00
king e9be17faab fix(asset): allow registering a monitor of an already-registered model
Registration was blocked whenever same-model candidates existed, so a
second monitor of the same model (e.g. dual monitors) could not be added.
Now only an existing asset with the same serial blocks a new one; the
UI tells serial and model candidates apart and hides 'register' only
for serial matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 15:14:22 +09:00
king 133df472d1 Merge branch 'fix/dash-workload-bar-ratio' 2026-10-07 14:43:27 +09:00
king 569b33ece4 fix(project): workload bars fill by completion rate, not task count
Bar height was scaled to the largest count, so 9/13 looked nearly empty
and 1/1 short. Each bar is now the whole set; green fill = done ratio,
with count and percent above.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:43:21 +09:00
king 452e8a9093 Merge branch 'feat/dash-workload-bars' 2026-10-07 14:24:07 +09:00
king 1cfcec2bef feat(project): workload as vertical bars with task list drawer
Per assignee, main and subtask bars (height = count, green = done).
Clicking a bar slides in a right-side panel listing those tasks;
clicking an item opens the task editor. Closing the editor refreshes
the counts. Subtask summary API now returns id, title, due date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:24:02 +09:00
king 2d638804d1 Merge branch 'feat/project-members-only' 2026-10-07 14:16:41 +09:00
king b6dc82c0b3 feat(project): projects visible to members only, admins included
Admins no longer see projects they are not owner/member of: sidebar list,
project list API, project pages, search, inbox, notifications, reminders
and trash all follow access.visible_project_ids. Only the super admin
still sees every project. Member assignment stays admin-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:16:36 +09:00
king 2a01d97dd0 Merge branch 'feat/dash-assignee-workload' 2026-10-07 14:09:11 +09:00
king fc3a2d0b9b feat(project): dashboard workload by assignee with subtasks and completion
Replace the scheduled-tasks bar chart with a table of all tasks assigned
per person in scope (no due date needed, filters ignored): main tasks,
subtasks (new GET /api/projects/{id}/subtasks-summary), done counts and
completion rate, plus a total row. Admin only, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:09:06 +09:00
king c766af691a Merge branch 'feat/goals-no-cell-move' 2026-10-07 14:03:34 +09:00
king b7c24c07e7 feat(project): remove drag-to-move for annual goal cells
Goal text cells no longer get move borders or drag handling; clicking a
cell still highlights it. The weekly meeting table keeps its move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 14:02:51 +09:00
king fbb6c648a5 Merge branch 'feat/board-btn-color' 2026-10-07 13:58:18 +09:00
king 8b664fc216 style(project): pastel PowerPoint colors for meeting board button
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:58:14 +09:00
king 5f10f9ce45 Merge branch 'fix/board-refresh-error-code' 2026-10-07 12:59:38 +09:00
king 46dc038e26 fix(project): show OAuth error code when meeting board token refresh fails
RefreshError showed only a generic message; include Google's error code
and explain client ID/secret mismatch (unauthorized_client).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:59:33 +09:00
king c0b742af8a Merge branch 'fix/authorize-port-18765' 2026-10-07 12:50:19 +09:00
king 80c9904771 fix(scripts): move OAuth callback port to 18765
8765-8767 are taken by local preview servers on the dev PC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:50:14 +09:00
king 8885bbce6b Merge branch 'fix/authorize-fixed-port' 2026-10-07 12:42:30 +09:00
king e9618d93d6 fix(scripts): use fixed OAuth callback port 8765 for token issue
A web-application OAuth client needs the exact redirect URI registered;
a random port made that impossible (redirect_uri_mismatch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:42:26 +09:00
king cbf59d9bf0 Merge branch 'feat/meeting-board-slides' 2026-10-07 12:04:14 +09:00
king c9d5e6e017 feat(project): meeting board button opens a blank Google Slides deck
A "회의록 보드" button next to attendees opens the week's Google Slides
deck in its own window. The deck is found (Drive appProperties) or
created in the shared drive MEETING_BOARD_FOLDER_ID as one BLANK slide,
named like "10월 2주차 (10/5~10/11)". Needs a token with Drive and
Slides scopes; the authorize script now requests them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:04:09 +09:00
king 15e84ba5bc Merge branch 'feat/meeting-autofit-on-load' 2026-10-07 11:43:57 +09:00
king 3045944200 feat(project): auto-fit all meeting columns on load
The weekly meeting table always starts with "fit all columns" instead of
the widths saved in the browser; it refits once fonts load unless the
user already resized a column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:43:53 +09:00
king e1f50e0ca5 Merge branch 'feat/meeting-amount-text' 2026-10-07 11:40:36 +09:00
king 9528f735b8 feat(project): allow text in meeting target/result cells; fix result note save
- Target and result cells accept text such as "20개". Values that parse
  as amounts still go to the integer columns; anything else goes to the
  new target_text/result_text columns (migration 021).
- Fix: PUT /api/goals/meeting-items/{id} dropped result_note, so the
  last-week result text was never saved.
- Update meeting nav test to the month-bounded week numbering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:40:30 +09:00
king 7417e661e0 Merge branch 'feat/week-target-labels' 2026-10-07 11:30:54 +09:00
king 38d0a87d6b feat(project): show weekday and day count in weekly target popup
Each week reads like "11/1(일)~11/8(일) 8일".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:30:49 +09:00
king cd3577b299 feat(project): month-bounded meeting weeks, weekly sales targets, sticky header
- Weeks stay inside the month: week 1 starts on the 1st (through the next
  Sunday if the 1st is a weekend); a trailing Mon/Tue joins the last week.
  "Last week" is the previous period.
- Prev-week review columns: 전주 업무 | 결과(text, new result_note) |
  전주 목표 | 결과(amount).
- Header now shows month target, cumulative weekly target, month-to-date
  sales and gap (amount + %), with decisions/notes beside it; the area
  stays fixed while scrolling.
- Goals board: the monthly sales target is entered per week; the sum
  becomes the month target.
- Migration 020: result_note, goal_week_targets, drop Monday-only check,
  move absorbed Monday meetings to the new week start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:24:41 +09:00
king 9194487217 Merge branch 'feat/meeting-columns' 2026-10-06 17:27:08 +09:00
king e958743e65 feat(project): rename meeting columns and drop rate/evaluation
Headers: 주요 업무 / 결과 / 전주 목표 / 정량 목표. The achievement-rate
and evaluation columns are removed from the weekly meeting table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 17:27:04 +09:00
king 85cf0a28b1 Merge branch 'feat/meeting-no-week-sales' 2026-10-06 16:01:52 +09:00
king 39dcda66b4 feat(project): remove per-row this-week sales in weekly meetings
Drop the "이번주 실적" line under each row's target and the now-unused
shop link menu. Performance sales stay only in the header cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 16:01:47 +09:00
king f09b8fa2f9 Merge branch 'feat/meeting-no-auto-result' 2026-10-06 15:52:15 +09:00
king df36a5a917 feat(project): drop auto last-week results in weekly meetings
Last-week result is always entered by hand; remove shop sales auto-fill
and the 자동입력 / 실적 미사용 badges next to item names. This-week sales
under the target stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:52:05 +09:00
king d18e801e08 feat(asset): animate asset detail drawer 2026-10-06 02:39:03 +09:00
king b576dd1a38 feat(asset): add photos, monitor links and deletion
Apply asset_db_002_photos_monitors.sql before rebuilding web.

Restrict soft deletion to the super admin; retain reports and audit.
2026-10-06 02:29:19 +09:00
king bd0c47e6fc feat(asset): add inventory and HWiNFO reports
Requires asset_db initialized with scripts/sql/asset_db_init.sql and ASSET_DB_URL configured before enabling storage.
2026-10-06 02:09:10 +09:00
king 75c0370e54 fix(project): shift goal years left by 35px 2026-10-04 14:54:48 +09:00
king a2a39671b9 feat(project): collapse meeting months by year 2026-10-04 14:40:58 +09:00
king 2a1a3e7bd9 fix(project): keep sidebar on week navigation 2026-10-04 14:14:25 +09:00
king 5bf8c9c160 feat(project): add monthly meeting menu tree 2026-10-04 13:45:22 +09:00
king 86622cc4dd fix(project): retain monthly plan text styles 2026-10-04 13:30:36 +09:00
king ed7da57066 feat(project): compact links and add file icons 2026-10-04 13:17:22 +09:00
king e2fc14a584 fix(project): center weekly meeting labels 2026-10-03 18:45:27 +09:00
king d89875db7e fix(project): restore smooth quarter toggles
Hide monthly content until column widths settle to prevent numeric shifts during expansion.
2026-10-03 18:09:10 +09:00
king 321bf11f65 fix(project): stop quarter reveal numeric drift 2026-10-03 17:53:16 +09:00
king 3e4c6dfad3 fix(project): center annual goal labels 2026-10-03 17:18:32 +09:00
king d3c1ca12e9 fix(project): grow cells and repair Enter 2026-10-03 17:04:02 +09:00
king 090e508bf3 feat(project): add meeting cell editing
Apply project_db migration 019 to enable vertical cell merges. Other cell editing remains available before migration.
2026-10-03 15:11:41 +09:00
king 193da56edf fix(project): fit meeting rows and inline badges 2026-10-03 14:26:36 +09:00
king cd0a509215 feat(project): add help search and detailed guides 2026-10-03 09:41:09 +09:00
king 7647e4b20f feat(project): add cell moves and width menus 2026-10-03 08:55:15 +09:00
king 2c8542339d fix(project): fit goal rows to text height 2026-10-03 07:59:22 +09:00
king b32f2ac3a3 feat(project): auto-fit goal column widths 2026-10-03 06:55:00 +09:00
king e726f986db perf(project): smooth sidebar resizing
Batch drag updates per frame and defer full layout recalculation until release. Cover resize edge cases and retain goals review records.
2026-10-03 06:45:56 +09:00
king 36a6866b96 style(project): compact toolbar and reset icon 2026-10-03 06:29:50 +09:00
king db39d3b383 fix(project): anchor toolbar above selected cell 2026-10-03 06:23:03 +09:00
king dc2008c5b3 feat(project): add Excel font controls and reflow 2026-10-03 05:47:57 +09:00
king 494d84f7c2 feat(project): add group collapse and UI polish 2026-10-03 05:26:41 +09:00
king 44f6ca4ef7 style(project): reduce board column and card corner radius 2026-10-02 18:02:40 +09:00
king 7f9c7a24d3 style(project): change board column background to ececec 2026-10-02 17:58:19 +09:00
king 22af196d56 feat(project): add Asana-style board completion checks 2026-10-02 17:55:31 +09:00
king 20232baf06 feat(project): add font options and selected goal text formatting
Restore the board header add button to the task side panel while keeping footer quick entry. Add safe, persisted goal text formatting and self-hosted Project font preferences with shared help updates and regression coverage.
2026-10-02 17:28:54 +09:00
king 035cb83d6f feat(project): add inline board tasks and reorder subtasks 2026-10-02 16:38:01 +09:00
king 114af59b26 fix(project): show completed subtasks with filled green checks 2026-10-02 16:13:52 +09:00
king 6a38fdb06a feat(project): match Asana typography sizes and weights 2026-10-02 16:03:52 +09:00
king d387048ebf feat(project): apply Asana system fonts to Project screens
Override the font token only on Project pages, preserve icon and monospace fonts, and update CSS/JS cache versions. Match the image viewer font stack as well.
2026-10-02 15:15:46 +09:00
king 71516713c5 Merge branch 'feat/cupang-box-weight' — 쿠팡 밀크런 상자별 무게 합계 2026-10-02 14:24:08 +09:00
king d21670f6af feat(cupang): 출고 상세 상자 목록에 상자별 무게 합계
- 상자마다 무게 칸 = 상자에 든 제품 수량 × 포장무게(설정(제품명)의 지금 값) 합계, 상자번호처럼 상자 단위 한 칸
- 무게가 없는 제품이 섞이면 아는 무게만 더하고 "일부 미입력"(말풍선에 빠진 코드), 모두 없으면 —
- 상자 목록 엑셀에도 무게(g) 열(혼합 상자는 세로 병합)
- 포장무게 칸(마이그레이션 007)이 없으면 무게 칸·열 없이 예전 그대로
- tests/test_cupang_weight.py: 상자 무게 계산 + 엑셀 무게 열

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 14:23:56 +09:00
king 2434bce35e Merge branch 'feat/cupang-product-weight' — 쿠팡 밀크런 제품 포장무게(g) 2026-10-02 13:43:30 +09:00
king f02742497a feat(cupang): 제품 설정에 포장무게(g) — 수기 추가·수정 입력, 목록 표시·정렬
- cupang_products.weight_g (마이그레이션 007, NULL = 미입력, 0~1,000,000 CHECK)
- 초기 무게 39건 시드(cupang_products_weight_seed.sql) — 무게가 비어 있는 행만 채움, 실행 전 값 백업
- 수기 추가에 포장무게(g) 칸(1,070·1070g 허용, 비우면 기존 무게 유지), 수정 팝업에서 수정·지우기
- 등록 목록에 포장무게 열(1,070g, 숫자 정렬, 무게 없는 줄은 맨 뒤)
- 007 미적용이면 무게 칸·열을 숨기고 저장 SQL 에서도 뺌(기존 동작 그대로)
- tests/test_cupang_weight.py: 입력 읽기 + 무게 칸 유무별 등록·수정 SQL

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 13:43:17 +09:00
king 968892d811 feat(project): 회의록 이번주↔지난주 순서 바꾸기(사람별 기억), 목표 줄·영역 바로 추가, 보드 카드 100px·표지 이미지
- 주간 회의록: 표 왼쪽 위 [순서 바꾸기] — 이번주(2칸)·지난주 리뷰(5칸) 묶음 순서 교체, 로그인 이메일별로 브라우저에 기억
- 연간 목표: 업무 영역 추가·줄 추가(1열·2열 메뉴)는 이름을 묻지 않고 바로 만들고 새 이름 칸을 바로 입력 상태로
- 보드 카드: 높이 100px 고정(제목 2줄까지), 담당자·날짜 글자·아이콘 10% 크게,
  설명의 첫 이미지를 카드 위 표지로(아사나식)
- project.css/js 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:38:27 +09:00
king a3a9444c3b feat(project): 설명란 이미지 더블클릭 = 별도 창 보기, 댓글 Shift+Enter 줄바꿈, 메뉴 이름 Project
- 설명란 이미지 더블클릭 → 별도 브라우저 창(원본 크기, 휠 확대·축소, 끌어서 이동, −/+ · 1:1 · 맞춤 막대, 키 + − 0 1 Esc)
- 댓글 입력칸·댓글 대화창·답글 입력칸을 여러 줄 입력칸으로 — Enter 등록, Shift+Enter 줄바꿈, 줄 수만큼 늘어남
- ERP 메뉴·홈 카드 이름 "프로젝트 관리" → "Project"
- project.css/js 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:50:30 +09:00
king e1006c63de fix(project): 목표·주간 회의록 저장 손실·지난주 연결·실적 미확인 수정 (점검 9건)
- 칸별 자동 저장 createFieldSaver: 같은 칸 요청 직렬화, 보낸 값만 saved,
  늦은 응답이 새 초안을 덮지 않음, 실패 시 초안·dirty 유지(빨간 테두리),
  localStorage 초안 백업·되살리기, 페이지 떠남 keepalive + 이탈 경고
- 목표 표: 저장 실패면 영역·줄·병합 작업과 표 교체 중단, 받는 사이 입력 보호
- 회의록: 금주 목표 저장 뒤 새로고침 대신 숫자 칸만 다시(차례 번호로 옛 응답 버림),
  이번주 실적 %는 서버 확정 목표로 즉시 재계산
- 지난주 = 정확히 7일 전 주의 같은 연결키 줄(line_key, 마이그레이션 018),
  역순 생성·이름 변경·삭제 후 재생성에도 연결, 이름 추정 연결 없음
- 실적 조회 장애를 0원 대신 미확인으로(목록·매출·부분 실패 구분)
- 구역·항목 ⋮ 메뉴 버튼(키보드·터치), 메뉴 키보드 탐색·포커스 복귀
- 매출 갱신 실패·일부 실패 안내 + 재시도, 서버 기록 갱신 시각, 권한 없으면 호출 안 함
- 테스트: Python 통합(역순 생성·실적 장애), 018 백필, jsdom UI 106건

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:14:10 +09:00
king 21981eb946 style(project): 연간 목표 분기 구분 — 분기별 색 띠·열 음영, 접기 아이콘은 엑셀식 −/+
- 분기마다 차분한 색(파랑·청록·보라·남색): 머리 위 색 띠(월 3px · 분기 6px), 분기 열 전체 옅은 음영,
  분기 칸 오른쪽 2px 경계, 분기 머리 글자·아이콘은 분기 색
- 접기 아이콘: 네모 안 −(펼침) / +(접힘), 90° 돌며 세로 막대가 자라고 줄어드는 애니메이션
- project.css 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:39:32 +09:00
king ac4f2653af feat(project): 빈 카드 하위 작업 추가 버튼, 분기 머리 칸 전체 클릭 접기 + 회전 아이콘, 달력 회의록 점 안쪽으로
- 보드: 하위 작업이 없는 카드에도 하위 작업 토글(카드 hover 때 보임) — 누르면 펼쳐지며 바로 이름 입력 줄
- 연간 목표: 분기 머리 칸 아무 곳이나 눌러 접기/펴기(너비 조절 직후 클릭은 무시),
  꺽쇠 대신 SVG →|← / ←|→ 아이콘, 화살표가 반 바퀴 돌며 바뀜, 접힌 분기 머리는 강조색
- 회의록 작은 달력: 회의록 있음 점을 달력 테두리 안으로
- project.css/js 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:18:47 +09:00
king 51727e419a feat(project): 연간 목표 상·하반기 → 1~4분기, 주간 회의록 머리·표 다듬기
연간 목표 표
- 3·6·9·12월 오른쪽에 1~4분기 칸(글 칸 13=1분기·15=2분기·14=3분기·16=4분기 — 예전 반기 칸 번호를 이어 써서
  글 옮기기 없음, 예전 상반기 글은 1분기·하반기 글은 3분기에 보임)
- 분기 합계·달성률·로아스 가중 평균, 분기 접기(pj_goal_fold_q), 열 너비 키 q1~q4
- 가로 병합은 같은 분기 월 칸 안에서만(서버·화면·DB CHECK), 분기를 넘는 예전 병합은 잘라서 그림
- 마이그레이션 017: goal_cells 월 칸 0~16, 분기를 넘는 병합은 분기 끝까지로 줄임(글 유지),
  회의록 줄 이름 "메타(숫자)" → "메타". 미적용이면 2·4분기 칸 읽기 전용 + 503

주간 회의록
- 달력 폭 줄이고(174px) 글자·칸 5% 키움, 주차 탭은 달력 바로 왼쪽
- 지난주 리뷰 머리에 지난주 기간, "목표 금액" → "정량 목표", "목표 표에서 보기" 삭제
- 첫 회의록 기본 줄 "메타(숫자)" → "메타"

도움말·문서·테스트 갱신, project.css/js 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 16:30:24 +09:00
king b791f7be68 style(project): 주간 회의록 머리 정리 — 주차 탭은 제목 줄 끝 작은 탭, 이 달 계획은 그 아래(달력 앞까지), 달력 90% 축소
- 주차 탭: 한 줄짜리(1주차 10/5~11, 같은 달이면 끝 월 생략, 전체 기간은 말풍선), 회의록 있음 점은 왼쪽 위
- 이 달 계획 카드를 머리 왼쪽(주차 탭 자리)으로 옮겨 너비를 달력 앞까지
- 작은 달력 212px → 191px(글자·칸 높이도 같이)
- project.css 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:32:25 +09:00
king 334b83c973 feat(project): 주간 회의록 위에 이 달 계획 카드, 숫자 영역은 한 줄 막대로 축소
- 연간 목표 표의 그 달 열 글을 업무 영역별 카드로 표시(router._month_plan) — 빈 칸 제외,
  가로 병합 칸 글은 범위(9~10월) 표시, 묶인 줄은 묶음 항목 이름, 목표 표 미적용이면 숨김
- 머리 숫자 9칸을 한 줄 막대(.pj-meet-kpibar)로 — 값 15px, 설명 문구는 말풍선
- project.css 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:21:17 +09:00
king 6ea4a2e0f9 feat(project): 목표 표 가로 스크롤 3열(연간)까지 고정, 연간·반기 달성률 = 기간 목표 합계 대비 실적
- 연간 열 sticky(left = 1열 + 2열 너비), 경계 그림자 — 머리·지표(틀 고정 줄)·업무 영역 칸 모두
- 매출 달성률 연간·상·하반기 = 입력된 실적 합계 ÷ 그 기간 목표 합계 전체(예: 2,910 ÷ 3,313 = 87.8%),
  예전 '실적이 있는 달의 목표만' 기준에서 변경, 말풍선 "연간 목표 합계 대비 실적"
- 캐시 버전 20261001v, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:10:22 +09:00
king ec5d7e2efe style(project): 프로젝트 관리 모든 화면 위쪽 여백 줄임(상단 바~제목 36px → 6px)
- .erp-page:has(> .pj-wrap / .pjh) 위 여백 24px → 6px, .pj-wrap·제목 줄(.pj-section-head·회의록 머리) 위 여백 0
- 다른 모듈의 .erp-page 여백은 그대로, 캐시 버전 20261001u, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 15:01:42 +09:00
king 737191c170 feat(project): 주간 회의록 참석자를 전체 멤버에서 고르기
- 자유 입력 칸 대신 멤버 칩(사진·이름·×) + [참석자] 고르기 창(찾기·전원 선택·모두 해제·체크), 바뀔 때마다 저장
- 후보 = project 권한 보유 등록 사용자(_meet_members), 저장은 이메일 쉼표 목록(예전 글자는 칩으로 유지, _parse_attendees)
- 참석자 길이 제한 500 → 3000자, 캐시 버전 20261001t, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:59:52 +09:00
king f199eda322 style(project): 목표·회의록 제목 2배(32px) 굵게, 회의록 → 연간 목표 큰 깃발 버튼
- h2.pj-goal-title 32px·800 — 연간 목표·주간 회의록 제목
- 회의록의 ← 화살표 대신 [깃발 {연도}년 목표] 강조 버튼(.pj-meet-goalbtn), 인쇄에선 숨김
- 캐시 버전 20261001s, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:55:56 +09:00
king 9161e0901f fix(project): 주간 회의록 1주차 = 그 달 첫 월요일이 있는 주(월간 목표·누적은 1일~말일)
- store.month_weeks: 주는 월요일이 속한 달의 것 — 예) 2026년 10월 = 10/5·12·19·26, 9/28~10/4 는 9월 마지막 주
- 다른 달의 주(?week=)를 열면 그 달 회의록으로 303
- 작은 달력은 그 달 날짜가 든 주 전부(store.calendar_weeks) — 앞 달 주는 흐리게, 누르면 그 달 회의록
- 월 누적·주당 필요 매출은 그대로 1일~말일 기준(1주차면 첫 월요일 전날까지 누적), 캐시 버전 20261001r, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:54:30 +09:00
king 5460c7f676 feat(project): 목표 표 1·2열 마우스 오버 도구 막대 제거 → 우클릭 메뉴로
- 1열(구역) 우클릭: 색 바꾸기(색 창은 우클릭 자리)·위로·아래로·줄 추가(구역 맨 아래)·영역 삭제 — goalAct 로 정리
- 2열(항목) 우클릭: 기존 줄 추가·삭제·항목 칸 나누기 + 위로·아래로(묶이지 않은 칸)
- 도구 막대 템플릿·JS(placeTools)·CSS 제거, 영역 색은 tbody[data-color], 캐시 버전 20261001q, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:49:43 +09:00
king 2a9f6f5628 fix(project): 목표 표 도구 막대가 오른쪽에 고정돼 누를 수 없던 버그 — 커서 오른쪽 위로
- 커서 오른쪽(같은 높이)에 두니 옆 칸으로 가로질러 갈 때 막대에 걸려 옆 칸 막대가 안 뜨고,
  칸 오른쪽 끝에서 들어오면 막대가 칸 밖에 떠서 가는 중에 사라졌다
- 이제 커서 오른쪽 위: 가로 이동은 막대 밑으로 지나가고, 막대는 오른쪽 위로 가서 누름
- 커서가 멀어질 때(왼쪽·아래)만 따라오고 막대 쪽으로 갈 땐 그대로, 시작점은 이름 칸 안, 작은 호버 다리
- 캐시 버전 20261001p, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:17:03 +09:00
king 58dbb7ef3e fix(project): 목표 표 영역·줄 도구 막대를 마우스 커서 오른쪽에
- 이름 칸 아래 가운데(왼쪽 고정 열이라 잘림) 대신 커서 오른쪽에 — 들어온 자리 기준 가로 고정, 세로는 커서를 따라감
  (가로까지 따라가면 막대를 누르러 갈 때 도망감), 커서가 막대 위면 그대로, 화면 배율 보정
- 캐시 버전 20261001n, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:10:01 +09:00
king 75b82024de fix(project): 입력 중 테두리를 칸 전체로, 고른 칸 Del 로 내용 지우기(Ctrl+Z 되돌리기)
- 목표 표·회의록: 입력 중 보라 테두리·밝은 배경을 입력칸(글 높이) 대신 칸 전체(td:focus-within)에
- 끌기·Shift+클릭으로 고른 칸에서 Del → 글 지우고 칸마다 저장, Ctrl+Z 로 바로 직전 지우기 되돌림
  (입력 중일 때의 Del·Ctrl+Z 는 평소 글자 편집), 우클릭 메뉴 "내용 지우기 (Del)"
- 캐시 버전 20261001m, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:03:57 +09:00
king 4af1ad8848 fix(project): 목표 표·회의록 — 칸 아무 곳이나 눌러 입력(엑셀처럼), 우클릭 메뉴 아이콘
- 칸이 세로로 길면 위쪽(글 높이)만 눌러야 입력되던 것: 글/금액 칸 아무 곳이나 누르면 그 칸 입력, 커서는 글 끝,
  칸 전체 글 입력 마우스 모양, Shift+클릭·끌기 선택은 그대로
- 우클릭 메뉴 왼쪽 아이콘(menuIcon): 줄 추가 위/아래·줄 삭제·셀 병합·병합 해제·항목 칸 나누기, 회의록 위로/아래로·쇼핑몰 연결
- goals.html 항목 칸 rowspan 계산이 값 없을 때도 안전하게, 캐시 버전 20261001l, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 13:52:30 +09:00
king 164153dc9c feat(project): 목표 표 3열에서 줄 추가 = 같은 항목 칸(2열) 안에 — 항목 칸 묶음
- goal_rows.label_cont(마이그레이션 016): 바로 위 줄 항목 칸에 묶임, 이름은 묶음 첫 줄, 2열 rowspan(_goal_label_spans)
- 3열 우클릭 위/아래에 줄 추가 → same_label: 같은 항목 칸 안(이름 묻지 않음), 첫 줄 위면 새 줄이 첫 줄로 이름 넘겨받음
- 2열 메뉴·+ 줄 추가는 묶음 밖(묶음 맨 위/맨 아래 기준), 묶인 2열 우클릭 → 항목 칸 나누기(split-label)
- 묶음 첫 줄 삭제 → 다음 줄이 첫 줄·이름 넘겨받음, 묶인 줄 이동 400, 새 연도 복사에 묶음 유지
- 캐시 버전 20261001k, DB 회귀 test_goal_label_groups, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 13:37:40 +09:00
king ac0672bc11 fix(project): 목표 표 병합·줄 추가/삭제 때 새로고침 대신 제자리 다시 그리기 + 애니메이션, 3열 줄 메뉴
- 병합 때 표가 줄었다 늘어나고 줄 추가/삭제 때 깜박이던 것: 새로고침(열 너비가 늦게 적용) 대신 페이지를 다시 받아
  업무 영역 tbody 만 교체(refreshTable) — 열 너비·반기 접기 다시 적용, 새 글 칸 연결
- 애니메이션: 지운 줄 흐려지며 사라짐, 남은 줄 미끄러져 이동(FLIP), 새 줄 위에서 등장 + 강조, 병합/해제 칸 테두리 강조
- 3열(연간 칸) 우클릭에도 위/아래에 줄 추가·줄 삭제(병합 메뉴가 있으면 그 아래에)
- 영역 추가·삭제·이동, 줄 이동도 같은 방식, 캐시 버전 20261001j, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 13:30:37 +09:00
king 24dd3acd09 fix(project): 목표 표 월 머리 — 주간 회의록 링크를 글자 대신 칸 전체로
- a.pj-goal-mlink 를 칸 전체(absolute inset 0)로, 마우스를 올리면 칸 전체 강조
- 오른쪽 끝 너비 조절 손잡이는 링크 위에 남아 그대로 끌 수 있음, 이번 달 밑줄 유지
- 캐시 버전 20261001i, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 13:06:03 +09:00
king 4efe7cef58 fix(project): 회의록 머리 배치 — 인쇄·삭제는 제목 옆, 달력은 오른쪽 위 90% 크기, 매출 갱신 상태 줄 제거
- 인쇄·회의록 삭제 버튼을 제목 줄(‹이전 달·다음 달› 뒤)로
- 작은 달력을 오른쪽 위(예전 버튼 자리)로 올리고 90% 크기(212px)
- 매출 자료 갱신 상태 줄·[매출 갱신] 버튼 제거 — 주차를 열면 표시 없이 다시 받아 숫자만 갱신(10분에 한 번)
- 캐시 버전 20261001h, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:13:57 +09:00
king 2dab20f718 feat(project): 주간 회의록 작은 달력 — 보고 있는 주 영역 표시, 주 줄을 누르면 그 주 회의록
- 주차 탭 오른쪽에 그 달 월요일 시작 달력(주 = 월~일 한 줄)
- 보고 있는 주 영역 표시, 오늘 동그라미, 토 파랑·일/공휴일 빨강, 다른 달 날짜 흐리게, 회의록 있는 주 점
- 줄(주)을 누르면 그 주 회의록(?week=), 인쇄에선 숨김, 좁은 화면은 아래로
- 캐시 버전 20261001g, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:07:21 +09:00
king be298777af feat(project): 회의록 주차를 열면 매출 자료를 쇼핑몰에서 한 번 더 받아 숫자 갱신
- 실적 모듈 매출 업데이트(POST /performance/api/sync, background)를 지난주 월요일 ~ 이번 주 오늘 기간으로 실행,
  진행 상황(쇼핑몰 n/m·받은 자료)을 상태 줄에 표시
- 끝나면 화면을 서버에서 다시 받아 숫자 칸만 교체(머리 카드·자동 결과·달성률·이번주 실적), 입력 중인 칸은 그대로
- 같은 주는 10분에 한 번만 자동(새로고침마다 쇼핑몰 API 를 부르지 않게), [매출 갱신] 버튼은 언제나,
  다른 업데이트가 돌면 그 작업을 기다림, 실적 권한 없음·실패 쇼핑몰 안내
- project.css/js 캐시 버전 20261001f, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:04:14 +09:00
king 45a671940b feat(project): 연간 목표 로아스 연간·상반기·하반기 목표/실적 계산
- 기간 로아스 = 기간 매출 ÷ 기간 광고비 — 월 광고비를 매출 ÷ 로아스로 환산해 합친 매출 가중 평균
  (목표는 매출 목표, 실적은 매출 실적으로), 매출이 없는 달이 섞이면 단순 평균. 말풍선에 방식·개월 수
- 화면 계산(저장 안 함), 숫자 칸을 고치면 바로 다시 계산. 캐시 버전 20261001e, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:58:03 +09:00
king 601971d43d fix(project): 회의록 쇼핑몰 연결 결과 — 진행 전 주·실적 미사용 쇼핑몰을 0 대신 구분, 이번주 실적 표시
- 지난 회의록 주가 아직 시작 전이면 자동 0 대신 "진행 전"
- 실적 모듈에서 사용 중이 아닌 쇼핑몰(사용 OFF·없는 코드)에 연결된 줄은 "실적 미사용" 표시 + 결과 직접 입력
- 자동 결과 말풍선에 쇼핑몰·기간, 0 이면 매출 업데이트 안내
- 쇼핑몰 연결 줄의 목표 금액 아래에 이번주 실적(월요일~오늘, 목표 대비 %)
- project.css/js 캐시 버전 20261001d, 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:54:06 +09:00
king c9bce7c976 feat(project): 연간 목표 엑셀식 칸 병합(끌어 고르기·우클릭 병합/해제) + 월별 주간 회의록
엑셀식 칸 병합 (예전 Shift+클릭·병합 버튼·오른쪽/왼쪽 칸 병합 메뉴 대체)
- 글 칸을 마우스로 끌어(또는 Shift+클릭) 사각형 선택 → 우클릭 "셀 병합 (N줄 × M칸)" / "병합 해제"
- 같은 업무 영역 안 세로(row_span) + 같은 반기 월 칸 가로, 연간·상·하반기 칸은 세로로만
- 걸친 병합은 엑셀처럼 범위를 넓혀 흡수, 글은 왼쪽 위부터 이어 왼쪽 위 칸에, 해제하면 왼쪽 위 칸에 남음
- POST /api/goals/areas/{id}/merge {row_from,row_to,col_from,col_to} (db.merge_goal_rect), router._goal_area_layout(colspan·rowspan)
- 가려진 칸 저장 거절(세로 포함), 병합 안쪽 줄 끼우기 +1 / 가려진 줄 지우기 -1, 세로 병합에 걸린 줄 이동 거절

주간 회의록 (/project/goals/{연도}/meetings/{월}, 목표 표 월 머리 클릭)
- 주(월~일) 탭, 주마다 회의록: 이번주 할 일·목표 금액 | 지난주 할 일·목표·결과·달성률·평가
- 앞선 회의록 줄 이어받기(carry_from), 처음이면 목표 표 업무 영역 + 기본 양식 줄(유통 줄 쇼핑몰 연결 추측)
- 머리: 월 목표·지난주까지 누적·주당 필요 매출(페이싱)·전주 목표/결과/달성률·금주 목표/현재 실적
- 쇼핑몰 연결 줄의 결과·누적·주간 매출은 실적 모듈 performance_store 읽기 전용(없으면 직접 입력)
- 금액 입력 120만·1.5억·3천만·1억2천만, 참석자·결정 사항 메모, 줄 메뉴(추가·순서·쇼핑몰 연결·삭제), 인쇄

마이그레이션 015(project_db): goal_cell_merges.row_span + CHECK 교체, goal_meetings, goal_meeting_items
캐시 버전 20261001c, 테스트(DB 회귀 test_goal_rect_merges·test_goal_meetings)·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:46:25 +09:00
king 614747ffca fix(performance): 주문 내역 창 가로 스크롤 없애기 — 넓은 창(최대 1640px) + 상품명만 줄바꿈
- openModal opts.wide → .perf-modal-card.is-wide(min(1640px, 100%)), 금액 클릭 주문 내역 창에 사용
- 상품명 열(.perf-ev-name)만 줄바꿈(최소 220px), 나머지 열은 한 줄 그대로
- css·js 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:39:24 +09:00
king 931cc0d1d9 fix(performance): 토스쇼핑 환불 건별 표에 주문일을 메모가 아닌 별도 열로
- 원본 데이터 확인 → 환불 출처별 비교 건별 표: 환불일 · 주문일 · 주문번호 · 주문상품 · 금액 · 메모
  (예: 9/5 주문을 9/6 취소 → 환불일 9/6, 주문일 9/5), 메모에는 취소/반품·클레임 상태만
- 저장되는 환불 사건의 order_date(대시보드 금액 클릭 상세의 주문일 열)를 테스트로 확인
- performance.js 캐시 버전 20261001f

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:36:51 +09:00
king b6b4f8c360 feat(performance): 수수료 설정 일반 사용자에게 열기 · 매출 업데이트 쇼핑몰별 [중지](다음 쇼핑몰로 계속)
- 설정 화면을 실적 권한자 누구나 — 일반 사용자는 탭 "수수료 설정", 쇼핑몰 표에 쇼핑몰·수수료율·마지막 동기화만
  (사용·집계 토글·API 설정·연결 상태·아래 카드는 관리자만), 수수료율 API(조회·변경·이력 삭제)만 모듈 권한으로
- 쇼핑몰별 [중지]: POST /api/sync/jobs/{id}/shops/{code}/stop — 그 쇼핑몰만 다음 API 호출 직전에 멈추고 저장 안 함,
  업데이트는 다음 쇼핑몰로 계속. 차례 전 중지는 차례에 건너뜀, 저장 중·끝난 쇼핑몰은 409, 실행 기록 "쇼핑몰 중지"
- 진행 창 쇼핑몰 이름 옆 [중지] 버튼, 결과 요약에 "중지됨" 구분, css·js 캐시 버전 올림
- 테스트(test_sync_job_stop_shop)·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:30:46 +09:00
king ff81d80cf9 fix(performance): 토스쇼핑 환불 = 클레임 환불 완료 + 클레임 없는 결제취소(환불일) — 9/6 실데이터 11,900 일치
- 9/6: 9/5 주문(276435356)을 9/6 취소 11,900 — 클레임 refundedDt·canceledAt 둘 다 일치, 정산 REFUND 에는 없음
- merge_refunds: 클레임(CANCEL·RETURN, isRefunded, refundedDt) + 클레임 없는 CANCELED_PAYMENT(canceledAt),
  주문상품마다 한 번(toss:R{orderProductId}), 금액 = 주문상품 price(없으면 클레임 order.price), 교환·미환불 제외
- 수집 때 기간 앞 90일 주문도 불러 다른 날 주문의 환불을 잡는다, collect 직접 구현(정산 건별은 수집에 안 씀)
- 원본 데이터 확인: 환불 출처별 비교 첫 열 = 적용 규칙, 날짜별 표의 환불 = 저장되는 값
- performance.js 캐시 버전 20261001d, 테스트·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:21:36 +09:00
king 01000757f3 feat(performance): 토스쇼핑 원본 데이터 확인에 환불 후보 3가지(정산 REFUND·주문 취소 시각·클레임 환불 완료)
- 9/6 실데이터: 매출 29,600 일치, 환불 11,900 은 정산 건별 REFUND 에 없음(다른 날 주문을 9/6 에 환불)
- 후보 ① 정산 REFUND(현재 규칙) ② orders/v2 canceledAt(기간 90일 전 주문까지) ③ claims refundedDt(isRefunded)
  — 날짜별 합계를 나란히 + 건별(주문번호·금액·메모), 화면 숫자와 같은 후보로 규칙을 정한다
- 클레임 목록 개인정보(연락처·수거 주소·요청 사유·사진) 값·합계 숨김, 송장번호 합계도 숨김
- performance.js 캐시 버전 20261001c, 테스트·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:16:29 +09:00
king d75dec2a50 feat(performance): 토스쇼핑 매출 = 순 거래액(매출 − 환불) — 정산 건별 REFUND 를 환불일에 차감
- 사용자 지정: 토스쇼핑 파트너스 "순 거래액" 기준(9/6 화면 매출 29,600 − 환불 11,900 = 17,700)
- 환불: GET /settlement-steps dateCondition=TRANSACTION_DATE 의 stepType=REFUND 상품 줄 → CANCEL 사건,
  날짜 = transactionTs 한국 날짜, 금액 = -|orderProductPrice|, 배송비 줄 제외, 31일 구간 + nextToken
  (클레임 목록은 날짜로 거를 수 없고 결제완료 단계 고객 취소가 안 잡혀 정산 쪽을 사용)
- 원본 데이터 확인: 날짜별 매출(주문일)·환불(환불일)·순 거래액 + 정산 stepType 별 항목 합계
- 원본 확인 표의 매출 열 이름도 day_cols 로 바꿀 수 있게(performance.js), 캐시 버전 20261001b
- 테스트·문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 10:12:07 +09:00
king a45f78217c feat(performance): 토스쇼핑 매출 수집 — OAuth 토큰·주문 내역 조회(31일·커서)·원본 데이터 확인
- 인증: Access Key·Secret Key → POST oauth2.cert.toss.im/token(client_credentials, scope toss-shopping-fep:write),
  토큰(약 1년) 암호화 저장·재사용, 401 이면 한 번 새로 발급. 키 발급 때 등록한 IP 에서만 호출됨
- 입력칸 라벨을 Access Key / Secret Key 로(키 이름 api_key·api_secret 그대로 — 저장값 유지), 판매자 ID 칸 제거
- 수집: GET /api/v3/shopping-fep/orders/v2 31일 구간 + nextCursor, HTTP 200 + resultType FAIL 도 오류 처리
- 잠정 매출 규칙: 주문 단위(toss:{orderId}), 주문일(한국 날짜), price 합(할인 전·배송비 제외), 결제 전만 제외
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 토스쇼핑 — 상태별 항목 합계·날짜별 현재 규칙 매출(개인정보 숨김)
- 테스트 3개 추가(토큰·연결·오류, 수집 규칙·구간·커서, 원본 확인 개인정보), 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:36:42 +09:00
king d3761183c3 feat(project): 연간 목표 모든 열 너비 조절·지표 줄 틀 고정·항목 줄 위/아래 추가·삭제
- 연간·1~12월·상/하반기 열도 머리 칸 오른쪽 끝을 끌어 너비 조절(더블클릭 = 기본), localStorage pj_goal_col_w
  에 기본값과 다른 칸만 저장. 반기 접기 애니메이션의 안쪽 고정 폭은 --fold-w(병합 칸 = 걸친 월 너비 합)
- 세로 스크롤 틀 고정: 머리 줄 + 매출·로아스 지표 줄까지 sticky(줄마다 --kpi-top, stickKpi)
- 항목 칸 도구 막대에 + (아래에 줄 추가) 항상 표시, 우클릭 메뉴로 위/아래 줄 추가·줄 삭제
- POST /api/goals/areas/{id}/rows 에 ref_row_id·place(above|below) — 기준 줄 위/아래에 넣고 순서 다시 매김
- project.css/js 캐시 버전 20261001b, 문서·회귀 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 09:11:55 +09:00
king 5d07770ce2 feat(project): 연간 목표 상·하반기 칸·반기 접기·이름 바로 수정·월 칸 병합·로아스 %
- 6월·12월 오른쪽에 상반기·하반기 칸 추가. 매출 목표·실적은 반기 합계,
  달성률은 연간과 같은 규칙, 업무 영역 글 칸은 month 13·14 로 저장
- 반기 칸 머리 버튼으로 1~6월 / 7~12월 칸을 접었다 펴기(너비 애니메이션,
  localStorage pj_goal_fold). 표를 width:1px + table-layout:fixed 로 바꿔
  펼칠 때도 애니메이션이 적용되게 함
- 업무 영역·줄 이름을 눌러 그 자리에서 수정(✎ 버튼 제거)
- 월 칸 가로 병합(goal_cell_merges, 반기 안에서만): Shift+클릭 선택 후
  병합 버튼, 우클릭 메뉴로 좌/우 병합·해제. 병합 시 글은 월 순서대로 첫 칸에 모음
- 로아스 목표·실적 칸 % 표기
- 마이그레이션 014 (goal_cells month CHECK 0~14, goal_cell_merges)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 08:24:13 +09:00
307 changed files with 52800 additions and 2704 deletions
+23
View File
@@ -43,6 +43,16 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
#
# 주간 회의록 "회의록 보드"(주차마다 빈 Google 슬라이드) — 위 Google 인증을 같이 쓴다.
# OAuth 토큰은 Drive·Slides 권한까지 필요: scripts/google_sheets_authorize.py 로 다시 발급(시트 권한도 함께 들어감)
# Cloud Console 에서 Google Drive API·Google Slides API 사용 설정. 서비스 계정이면 공유 드라이브 콘텐츠 관리자로 추가.
# GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN=replace-me # 비우면 GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN 사용
# MEETING_BOARD_FOLDER_ID=0AGF3CIEboPQiUk9PVA # 보드를 만들 공유 드라이브(폴더) ID — 비우면 이 기본값
#
# Project 업무 파일 → 구글 드라이브(설명란·보드 카드·세부 업무에 파일 끌어 놓기) — 위 Google 인증(Drive 권한)을 같이 쓴다.
# 그 아래 프로젝트/섹션/업무/세부 업무 폴더를 자동으로 만든다. 서비스 계정이면 공유 드라이브 폴더여야 올라간다.
# PROJECT_DRIVE_FOLDER_ID=1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG # 업무 파일 최상위 폴더 ID — 비우면 이 기본값
# ─── 휴가 관리 모듈 (vacation_db) ───
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
@@ -138,6 +148,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
# ─── 입출고 관리 모듈 (inout_db) — app/modules/inout ───
# 본사 → 공장 발주, 물류 입고, 미입고 관리. 미설정 시 "설정 필요" 안내만.
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
# 미설정 시 검색 비활성 → 수동 등록만 가능.
@@ -163,3 +178,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# APP_ENCRYPTION_KEY_V1=
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
# PERFORMANCE_SYNC_DAYS=7
# 매출 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 매일 09:00~19:00 정각·30분마다 오늘 포함 최근 10일.
# PERFORMANCE_AUTO_SYNC=false # 끄기
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
# ASSET_DB_URL=postgresql://asset_app:replace-me@postgres-db:5432/asset_db
+3
View File
@@ -16,3 +16,6 @@ PUBLIC_BASE_URL=http://localhost:8080
CS_ORDER_URL=https://cs.example.com
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
# 자산관리 개발용 DB (사용자가 직접 생성). 운영 DB 접속정보를 사용하지 마세요.
# ASSET_DB_URL=postgresql://asset_app:replace-me@host.docker.internal:5432/asset_db
+11
View File
@@ -24,3 +24,14 @@ __pycache__/
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
docs/samples/
tests/js/.out/
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
KING-DESKTOP.XML
# Excel 가 파일을 열 때 만드는 잠금 파일
~$*
# 테스트 도구(docs/TESTING.md)
.pytest_cache/
tests/js/node_modules/
tests/js/package-lock.json
+7 -2
View File
@@ -36,10 +36,15 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
- 말레이시아 창고 재고관리 (`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) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 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)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
상세는 `docs/PROJECT_OVERVIEW.md`.
- 자산관리 (`app/modules/asset/`, `asset_db`) — 사무집기·전산장비 등록/배정/반납/상태·구매/보증·이력.
HWiNFO XML 분석·사양 조회·이전 보고서와 원본 보존. 권한키 `asset`, 환경변수 `ASSET_DB_URL`.
사진 등록/갤러리·모니터 자산 조회/등록/연결·수퍼 관리자 삭제(이력/원본 보존). 기존 설치는 마이그레이션 `asset_db_002_photos_monitors.sql` 필요.
DB 미설정 시 저장 비활성, XML 분석 미리보기 가능. DB 생성은 사용자가 서버 명령으로 직접 진행. 상세 `docs/ASSET_MODULE.md`.
---
## 개발 원칙
@@ -47,7 +52,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
- 신규 DB가 필요하면 **서버에서 실행할 명령을 제공하고 생성은 사용자가 직접 진행한다** (사용자 지시: 2026-10-06). DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`). 대상 서버·현재 DB·백업 상태와 생성 후 스키마·앱 계정 권한·연결 확인 명령을 함께 제공한다. 기존 DB 삭제·덮어쓰기 등 위험 명령은 아래의 별도 승인 원칙을 그대로 따른다.
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
---
+67 -34
View File
@@ -1,56 +1,84 @@
# main-app ERP 프로젝트 작업 기준
> 이 문서는 Claude Code가 이 저장소에서 작업할 때 가장 먼저 확인하는 기준 문서입니다.
> 작업 시작 전, 아래 "반드시 먼저 읽을 문서"를 모두 확인한 뒤 작업을 시작합니다.
> 이 문서는 Claude Code가 이 저장소에서 작업할 때 **매 대화 자동으로 읽는** 기준 문서다.
> 토큰 절약을 위해 짧게 유지한다. 모듈별 상세 규칙은 각 모듈 폴더의 `CLAUDE.md` 와 `docs/*_MODULE.md` 에 둔다.
> **이 파일에 모듈 상세 설명을 다시 쌓지 말 것** — 새 기능 설명은 그 모듈의 `CLAUDE.md`(요약)·`docs/*_MODULE.md`(상세)에 쓴다.
---
## 반드시 먼저 읽을 문서
## 작업 시작 규칙 — 필요한 것만 읽는다
Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아래 문서를 순서대로 읽고 맥락을 확보**한 뒤 작업한다.
사용자는 요청 앞에 **`[모듈명]`** 을 붙인다(예: `[휴가] 반차 버튼 색 변경`).
1. `docs/PROJECT_OVERVIEW.md` — 프로젝트 정의, 기능 범위, 연동 대상
2. `docs/SERVER_ARCHITECTURE.md` — 서버 구성도와 네트워크 흐름
3. `docs/DATABASES.md` — PostgreSQL DB 구성과 명명 규칙
4. `docs/DEPLOYMENT.md` — 배포 경로, 서비스 실행 방식, 복구 절차
1. `[모듈명]` 으로 아래 표에서 모듈을 찾는다.
2. 그 모듈의 `app/modules/<폴더>/CLAUDE.md` 를 먼저 읽는다(요약·핵심 규칙).
3. 코드는 그 모듈 폴더 + 표의 정적 파일만 본다. 다른 모듈 폴더는 **연결이 확인될 때만** 연다.
4. 상세 문서(`docs/*_MODULE.md`)는 요약으로 부족할 때만 — 큰 문서는 `grep -n '^#' <문서>` 로 목차를 보고 **필요한 절만** offset/limit 으로 읽는다.
5. 큰 코드 파일도 통째로 읽지 말고 Grep 으로 위치를 찾은 뒤 그 부분만 읽는다.
6. `[모듈명]` 이 없거나 표에 없으면 어느 모듈인지 짧게 묻는다(뻔하면 추정하고 진행).
문서 간 내용이 충돌하면 위의 우선순위(1 → 4)를 따른다.
공통 문서는 **작업 종류에 해당할 때만** 읽는다(예전 "4개 필독" 규칙 폐지):
| 작업 종류 | 추가로 읽을 문서 |
| --- | --- |
| DB 테이블·마이그레이션·새 DB | `docs/DATABASES.md` (해당 DB 절만) |
| 배포·서버·Docker·복구 | `docs/DEPLOYMENT.md`, `docs/SERVER_ARCHITECTURE.md` |
| 여러 모듈에 걸친 작업·새 모듈 추가·전체 구조 질문 | `docs/PROJECT_OVERVIEW.md` |
| 화면 디자인 공통(ERP 셸·공용 CSS) | `docs/DESIGN.md` |
| 테스트 방법 | `docs/TESTING.md` |
문서끼리 충돌하면 PROJECT_OVERVIEW → SERVER_ARCHITECTURE → DATABASES → DEPLOYMENT 순으로 우선한다.
---
## 모듈 표
| `[모듈명]` | 폴더 (`app/modules/`) | DB | 권한키 | 상세 문서 | 정적 파일 (`app/static/`) |
| --- | --- | --- | --- | --- | --- |
| `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` |
| `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` |
| `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` |
| `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` |
| `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` |
| `[배송]` `[말레이시아배송]` | `dispatch/` | `dispatch_db` | `dispatch` | `docs/DISPATCH_MODULE.md` | `dispatch/` |
| `[말레이시아재고]` `[말레이시아]` | `malaysia/` | `malaysia_stock_db` | `malaysia` | `app/modules/malaysia/README.md` | `malaysia*.js` |
| `[휴가]` | `vacation/` | `vacation_db` | `vacation`, `vacation_approver` | (모듈 CLAUDE.md) | `vacation.*` |
| `[경비]` `[개인경비]` | `expense/` | `expense_db` | `expense` | (모듈 CLAUDE.md) | — |
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
외부 쇼핑몰 연동(사방넷·네이버 등)·주문관리·상품코드 매칭·재고·CS·반품은 허브 담당 영역 — `docs/PROJECT_OVERVIEW.md` 참고.
### 모듈 사이 연결 (이것을 바꾸면 상대 모듈도 확인)
- `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한).
- `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터).
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
- `app/mail.py`: 프로젝트 알림 메일.
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
---
## 프로젝트 한 줄 정의
`main-app`은 DBX ERP 시스템의 **메인 프로젝트(허브)** 이다.
담당 영역:
- 주문관리
- 상품코드 매칭
- 재고관리
- CS관리
- 반품관리
- 외부 쇼핑몰 API 연동 (카페24, 네이버 스마트스토어, 사방넷 등)
- 개인경비 (`app/modules/expense/`, `expense_db`)
- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/상자 계산, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트). 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일, 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷 — 혼합 상자 내용물·상자 종류 표시용) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 양식 생성은 `app/modules/cupang/export.py` 한 곳에서 만들어 xlsx·구글시트가 공유. `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시 확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip). 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트를 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제(문서에 시트가 하나뿐이면 내용만 비움). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 로켓 매출(`/cupang/sales`, `cupang_sales`·`cupang_sales_weekly`) — 발주 라인별 공급가·원가·물류비·마진 표. 기간/센터/유형/검색 조회, 행 CRUD, 구글 시트 양식 xlsx·csv 업로드(같은 발주번호+SKU+출고일+센터+수량은 덮어씀), 엑셀 다운로드. 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관하고 순마진은 화면에서 계산. 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 상자 계산·자동 배분
- 휴가 관리 (`app/modules/vacation/`, `vacation_db`) — 월간 달력(구글식 bar)/연차·반차 신청/승인 워크플로/공휴일·연차 설정. 권한키 `vacation`·`vacation_approver`
- 말레이시아 창고 재고관리 (`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`). 권한은 **지금 기준 공통 모듈 `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`
상세는 `docs/PROJECT_OVERVIEW.md`.
`main-app`은 DBX ERP 시스템의 **메인 프로젝트(허브)** 이다. 상세는 `docs/PROJECT_OVERVIEW.md`.
---
## 개발 원칙
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다(범위는 위 "작업 시작 규칙").
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
- 새 모듈을 만들면: `app/modules/<폴더>/CLAUDE.md`(요약) + 필요 시 `docs/<이름>_MODULE.md` + 위 모듈 표에 한 줄.
---
@@ -92,7 +120,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
- `.env`, `.env.local`, `.env.production` 은 **Git에 절대 커밋하지 않는다**.
- 예시 파일(`*.example`)만 커밋한다.
- 비밀값 유출이 의심되면 즉시 회전(rotate)을 권고한다.
- 신규 환경변수 추가 시 `*.example` 파일과 본 문서(또는 `docs/DEPLOYMENT.md`)에 변수 설명을 함께 갱신한다.
- 신규 환경변수 추가 시 `*.example` 파일과 `docs/DEPLOYMENT.md`(또는 그 모듈 CLAUDE.md)에 변수 설명을 함께 갱신한다.
---
@@ -101,8 +129,13 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
```
Main-app/
├─ app/ FastAPI 앱 소스
├─ docs/ 운영/설계 문서 (작업 전 필독)
├─ scripts/ 배포·유지보수 스크립트
│ ├─ modules/<모듈>/ 모듈별 코드 + templates/ + CLAUDE.md(모듈 요약)
│ ├─ integrations/ 외부 API 공통 계층(cafe24, google_sheets, google_slides)
│ ├─ static/ 정적 파일(모듈별 js/css)
│ └─ templates/ ERP 공통 셸·로그인·관리자
├─ desktop/notifier/ PC 알림 트레이 프로그램(C#, Windows exe)
├─ docs/ 운영/설계 문서 (필요한 것만 읽기)
├─ scripts/ 배포·유지보수 스크립트, sql/ 마이그레이션
├─ skills/ Claude Code 규칙/스킬
├─ docker-compose.yml 운영 컴포즈
├─ docker-compose.local.yml 로컬 컴포즈
+10 -3
View File
@@ -85,10 +85,17 @@ def read_text_file(config: Cafe24FtpConfig, path: str) -> str:
def temp_names(path: str, tag: str) -> tuple[str, str]:
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식."""
"""(임시 업로드 이름, 원본을 잠시 비킬 이름) — 같은 폴더, 원본 이름 + 표식.
⚠️ 원래 확장자를 **맨 끝에 그대로** 둔다. 카페24 디자인 FTP 는 허용된 확장자(.js·
.html·.css 등)만 받는다 — 예전 이름 `product-swiper.js.cf24tmp-…` 는 확장자가 바뀌어
STOR 가 `550 Operation not permitted` 로 거부됐다(실물). 그래서
`product-swiper_cf24tmp_<tag>.js` 모양으로 만든다(점·하이픈 대신 밑줄).
"""
folder, name = posixpath.split(path)
return (posixpath.join(folder, f"{name}.cf24tmp-{tag}"),
posixpath.join(folder, f"{name}.cf24old-{tag}"))
stem, ext = posixpath.splitext(name)
return (posixpath.join(folder, f"{stem}_cf24tmp_{tag}{ext}"),
posixpath.join(folder, f"{stem}_cf24old_{tag}{ext}"))
def write_text_file(
+209
View File
@@ -0,0 +1,209 @@
"""Google 드라이브 — 업무 파일 올리기(설명란·보드 카드·세부 업무에 파일 끌어 놓기, 2026-10-19).
인증은 google_slides 와 같은 설정(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함)을 쓴다.
- 최상위 폴더 `PROJECT_DRIVE_FOLDER_ID`(기본 = 업무 파일 폴더). 그 아래 `프로젝트/섹션/업무/세부 업무` 폴더를 이름으로
찾고 없으면 만든다(휴지통 폴더 제외). 같은 경로를 두 사람이 동시에 만들지 않게 폴더 찾기·만들기는 한 번에 하나씩.
- 올린 파일은 appProperties `dbxTaskId` = 업무 id — 설명란에서 링크를 지우면 **우리가 올린 파일만** 휴지통으로 보낸다
(다른 사람이 붙여 넣은 드라이브 링크는 건드리지 않음). 링크를 되살리면(되돌리기·잘라 붙이기) 휴지통에서 꺼낸다.
휴지통 파일은 드라이브가 30일 뒤 지운다.
- 서비스 계정은 내 드라이브 저장 용량이 없어 "공유 드라이브" 폴더여야 올라간다(OAuth 토큰이면 그 사용자 드라이브도 됨).
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
"""
from __future__ import annotations
import os
import re
import threading
from typing import Any, BinaryIO, Iterable
from app.integrations.google_slides import GoogleSlidesClient, _friendly
DEFAULT_FOLDER_ID = "1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG"
FOLDER_MIME = "application/vnd.google-apps.folder"
TASK_KEY = "dbxTaskId"
CHUNK = 8 * 1024 * 1024
# 설명란 링크에서 드라이브 파일 id — 우리가 넣는 링크 모양(https://drive.google.com/file/d/<id>/view)
FILE_LINK_RE = re.compile(r"https://drive\.google\.com/file/d/([A-Za-z0-9_-]{10,})")
# 폴더 찾기·만들기는 한 번에 하나(같은 폴더가 두 개 생기지 않게). 파일 올리기·휴지통은 호출마다 따로 만든
# 서비스 객체로(googleapiclient 의 HTTP 는 스레드 안전하지 않다) — 큰 파일이 다른 사람 업로드를 막지 않게.
_FOLDER_LOCK = threading.Lock()
class GoogleDriveError(RuntimeError):
"""화면에 보여도 되는 사유(비밀값 없음)."""
def root_folder_id() -> str:
return (os.getenv("PROJECT_DRIVE_FOLDER_ID") or "").strip() or DEFAULT_FOLDER_ID
def file_url(file_id: str) -> str:
return f"https://drive.google.com/file/d/{file_id}/view"
def file_ids_in(html: str) -> set[str]:
"""설명 HTML 안의 드라이브 파일 링크 id 들."""
return set(FILE_LINK_RE.findall(html or ""))
def folder_name(name: Any) -> str:
"""폴더 이름 — 앞뒤 공백·줄바꿈 정리, 너무 길면 자름, 비면 "(이름 없음)"."""
s = re.sub(r"\s+", " ", str(name or "")).strip()[:120]
return s or "(이름 없음)"
def _q(value: str) -> str:
"""Drive 검색어 따옴표 안 글자(역슬래시·작은따옴표 이스케이프)."""
return value.replace("\\", "\\\\").replace("'", "\\'")
class GoogleDriveFiles(GoogleSlidesClient):
"""google_slides 의 인증(서비스 계정·OAuth)을 그대로 쓰고 Drive 만 연다."""
def __init__(self) -> None: # noqa: D107 — 부모 __init__ 대신(Slides 서비스는 만들지 않음)
self.enabled = False
self.reason = ""
self.auth_mode = ""
self._creds: Any = None
try:
import googleapiclient.discovery # noqa: F401
import googleapiclient.http # noqa: F401
except ImportError:
self.reason = "google-api-python-client 미설치"
return
creds = self._service_account_creds()
if creds is None:
creds = self._oauth_creds()
if creds is None:
if not self.reason:
self.reason = "Google 인증 미설정(GOOGLE_SHEETS_CREDENTIALS 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 필요)"
return
self._creds = creds
self.enabled = True
def _service(self) -> Any:
from googleapiclient.discovery import build
return build("drive", "v3", credentials=self._creds, cache_discovery=False)
def _check(self) -> None:
if not self.enabled:
raise GoogleDriveError(self.reason or "Google 드라이브 연동이 꺼져 있습니다.")
# ────────────────────────────────────────────────
def ensure_folder_path(self, names: Iterable[str], *, root: str | None = None) -> str:
"""root 아래 names 순서대로 폴더를 찾거나 만들고 마지막 폴더 id."""
self._check()
parent = root or root_folder_id()
with _FOLDER_LOCK:
try:
drive = self._service()
for raw in names:
name = folder_name(raw)
q = (f"'{_q(parent)}' in parents and name = '{_q(name)}' and mimeType = '{FOLDER_MIME}' "
"and trashed = false")
res = drive.files().list(
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
corpora="allDrives", orderBy="createdTime",
).execute()
found = res.get("files") or []
if found:
parent = found[0]["id"]
continue
parent = drive.files().create(
body={"name": name, "mimeType": FOLDER_MIME, "parents": [parent]},
fields="id", supportsAllDrives=True,
).execute()["id"]
except GoogleDriveError:
raise
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
return parent
def upload(self, *, folder_id: str, name: str, stream: BinaryIO, mimetype: str, task_id: int) -> dict[str, Any]:
"""폴더에 파일 하나 → {id, name, url}. 이름은 원래 파일 이름.확장자 그대로."""
self._check()
from googleapiclient.http import MediaIoBaseUpload
try:
media = MediaIoBaseUpload(stream, mimetype=mimetype or "application/octet-stream", chunksize=CHUNK,
resumable=True)
meta = {"name": name, "parents": [folder_id], "appProperties": {TASK_KEY: str(int(task_id))}}
f = self._service().files().create(body=meta, media_body=media, fields="id,name",
supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
return {"id": f["id"], "name": f.get("name") or name, "url": file_url(f["id"])}
def ours(self, file_id: str) -> dict[str, Any] | None:
"""우리가 올린 파일이면 {trashed, task_id}, 아니면(남의 파일·없는 파일·권한 없음) None."""
self._check()
try:
f = self._service().files().get(fileId=file_id, fields="trashed,appProperties",
supportsAllDrives=True).execute()
except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다
return None
tid = (f.get("appProperties") or {}).get(TASK_KEY)
if not tid:
return None
return {"trashed": bool(f.get("trashed")), "task_id": tid}
def move_to(self, file_id: str, folder_id: str, *, task_id: int) -> bool:
"""그 업무가 올린 파일(appProperties dbxTaskId == task_id)이면 folder_id 로 옮긴다 — 옮겼으면 True.
남의 파일·다른 업무가 올린 파일(링크만 붙여 넣은 것)·이미 그 폴더에 있는 파일은 그대로 둔다."""
self._check()
try:
drive = self._service()
f = drive.files().get(fileId=file_id, fields="parents,appProperties",
supportsAllDrives=True).execute()
except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다
return False
if (f.get("appProperties") or {}).get(TASK_KEY) != str(int(task_id)):
return False
parents = [p for p in (f.get("parents") or []) if p]
if parents == [folder_id]:
return False
try:
drive.files().update(fileId=file_id, addParents=folder_id,
removeParents=",".join(p for p in parents if p != folder_id),
fields="id", supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
return True
def set_trashed(self, file_id: str, trashed: bool) -> None:
self._check()
try:
self._service().files().update(fileId=file_id, body={"trashed": bool(trashed)},
supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
def _friendly_drive(exc: Exception) -> str:
status = getattr(getattr(exc, "resp", None), "status", None)
text = str(exc)
if "storageQuotaExceeded" in text or "do not have storage quota" in text:
return ("서비스 계정은 내 드라이브에 파일을 올릴 수 없습니다 — 업무 파일 폴더를 공유 드라이브에 두거나 "
"OAuth 토큰(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN)을 쓰세요.")
if status == 404:
return "업무 파일 폴더를 찾을 수 없습니다(PROJECT_DRIVE_FOLDER_ID·폴더 공유 권한 확인)."
if status == 403 and "insufficient" not in text.lower():
return "Google 드라이브 접근이 거부되었습니다(폴더 편집 권한·Drive API 사용 설정 확인)."
return _friendly(exc).replace("Google 슬라이드 처리 실패", "Google 드라이브 처리 실패")
_CLIENT: GoogleDriveFiles | None = None
_CLIENT_LOCK = threading.Lock()
def get_client() -> GoogleDriveFiles:
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
global _CLIENT
with _CLIENT_LOCK:
if _CLIENT is None or not _CLIENT.enabled:
_CLIENT = GoogleDriveFiles()
return _CLIENT
+184
View File
@@ -0,0 +1,184 @@
"""Google 슬라이드(회의록 보드) 공통 계층 — 공유 드라이브 폴더에 빈 슬라이드를 만들거나 찾는다.
인증은 google_sheets 와 같은 설정을 쓰되 권한 범위(scope)가 다르다(Drive + Slides).
설정된 쪽을 자동 선택(서비스 계정 우선).
1) 사용자 OAuth 리프레시 토큰
· `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` — 없으면 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`
토큰은 Drive·Slides 권한까지 받아야 한다: `python scripts/google_sheets_authorize.py`(스프레드시트·Drive·Slides 한 번에)
· `GOOGLE_SHEETS_OAUTH_CLIENT_ID` / `..._SECRET`(없으면 로그인용 `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`)
2) 서비스 계정 JSON — `GOOGLE_SHEETS_CREDENTIALS` / `GOOGLE_SHEETS_CREDENTIALS_JSON`
서비스 계정 이메일을 대상 공유 드라이브의 **콘텐츠 관리자** 이상으로 추가해야 한다.
- 회의록 보드 폴더: `MEETING_BOARD_FOLDER_ID`(기본 = 회의록 보드 공유 드라이브).
- 같은 주차 보드를 다시 누르면 새로 만들지 않고 Drive 파일 appProperties(`dbxMeetingWeek` = 주차 시작일)로 찾는다
— 파일 이름을 바꿔도 같은 보드가 열린다. 휴지통에 버리면 다음에 새로 만든다.
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
"""
from __future__ import annotations
import json
import os
import re
import threading
from typing import Any
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations"]
TOKEN_URI = "https://oauth2.googleapis.com/token"
DEFAULT_BOARD_FOLDER_ID = "0AGF3CIEboPQiUk9PVA"
PRESENTATION_MIME = "application/vnd.google-apps.presentation"
WEEK_KEY = "dbxMeetingWeek"
# googleapiclient 의 HTTP 클라이언트는 스레드 안전하지 않고, 같은 주차를 두 사람이 동시에 누르면
# 보드가 두 개 생길 수 있으므로 찾기·만들기는 한 번에 하나씩.
_LOCK = threading.Lock()
class GoogleSlidesError(RuntimeError):
"""화면에 보여도 되는 사유(비밀값 없음)."""
def board_folder_id() -> str:
return (os.getenv("MEETING_BOARD_FOLDER_ID") or "").strip() or DEFAULT_BOARD_FOLDER_ID
def board_url(file_id: str) -> str:
return f"https://docs.google.com/presentation/d/{file_id}/edit"
class GoogleSlidesClient:
def __init__(self) -> None:
self.enabled = False
self.reason = ""
self.auth_mode = ""
self._drive: Any = None
self._slides: Any = None
try:
from googleapiclient.discovery import build
except ImportError:
self.reason = "google-api-python-client 미설치"
return
creds = self._service_account_creds()
if creds is None:
creds = self._oauth_creds()
if creds is None:
if not self.reason:
self.reason = "Google 인증 미설정(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 또는 GOOGLE_SHEETS_* 설정 필요)"
return
try:
self._drive = build("drive", "v3", credentials=creds, cache_discovery=False)
self._slides = build("slides", "v1", credentials=creds, cache_discovery=False)
except Exception as exc: # noqa: BLE001 — 사유만(비밀값 미출력)
self.reason = f"Google 클라이언트 생성 실패: {type(exc).__name__}"
return
self.enabled = True
# ── 인증(google_sheets 와 같은 설정, 범위만 Drive·Slides) ──
def _service_account_creds(self) -> Any:
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
if not raw and not path:
return None
try:
info = json.loads(raw) if raw else json.loads(open(path, encoding="utf-8").read())
from google.oauth2.service_account import Credentials
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
except Exception as exc: # noqa: BLE001
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
return None
self.auth_mode = "service_account"
return creds
def _oauth_creds(self) -> Any:
token = (os.getenv("GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN") or os.getenv("GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN") or "").strip()
if not token:
return None
cid = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_ID") or os.getenv("GOOGLE_CLIENT_ID") or "").strip()
secret = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET") or os.getenv("GOOGLE_CLIENT_SECRET") or "").strip()
if not cid or not secret:
self.reason = "GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET 미설정"
return None
try:
from google.oauth2.credentials import Credentials
creds = Credentials(token=None, refresh_token=token, token_uri=TOKEN_URI,
client_id=cid, client_secret=secret, scopes=SCOPES)
except Exception as exc: # noqa: BLE001
self.reason = f"OAuth 자격 생성 실패: {type(exc).__name__}"
return None
self.auth_mode = "oauth"
return creds
# ────────────────────────────────────────────────
def open_week_board(self, *, folder_id: str, week_key: str, title: str) -> dict[str, Any]:
"""그 주차 보드(빈 슬라이드)를 찾고, 없으면 폴더에 만든다 → {id, url, created}."""
if not self.enabled:
raise GoogleSlidesError(self.reason or "Google 슬라이드 연동이 꺼져 있습니다.")
with _LOCK:
try:
found = self._find(folder_id, week_key)
if found:
return {"id": found, "url": board_url(found), "created": False}
file_id = self._create_blank(folder_id, week_key, title)
except GoogleSlidesError:
raise
except Exception as exc: # noqa: BLE001
raise GoogleSlidesError(_friendly(exc)) from None
return {"id": file_id, "url": board_url(file_id), "created": True}
def _find(self, folder_id: str, week_key: str) -> str | None:
q = (f"'{folder_id}' in parents and trashed = false and mimeType = '{PRESENTATION_MIME}' "
f"and appProperties has {{ key='{WEEK_KEY}' and value='{week_key}' }}")
res = self._drive.files().list(
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
corpora="allDrives",
).execute()
files = res.get("files") or []
return files[0]["id"] if files else None
def _create_blank(self, folder_id: str, week_key: str, title: str) -> str:
meta = {"name": title, "mimeType": PRESENTATION_MIME, "parents": [folder_id],
"appProperties": {WEEK_KEY: week_key}}
file_id = self._drive.files().create(body=meta, fields="id", supportsAllDrives=True).execute()["id"]
# 새 프레젠테이션의 첫 장은 "제목·부제목" 틀(TITLE 레이아웃) — 틀 없는 빈 장(BLANK) 하나만 남긴다
pres = self._slides.presentations().get(presentationId=file_id, fields="slides.objectId").execute()
reqs: list[dict[str, Any]] = [{"createSlide": {"insertionIndex": 0, "slideLayoutReference": {"predefinedLayout": "BLANK"}}}]
reqs += [{"deleteObject": {"objectId": s["objectId"]}} for s in pres.get("slides") or []]
self._slides.presentations().batchUpdate(presentationId=file_id, body={"requests": reqs}).execute()
return file_id
def _friendly(exc: Exception) -> str:
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
status = getattr(getattr(exc, "resp", None), "status", None)
text = str(exc)
# 토큰 갱신 실패(RefreshError) — Google 이 준 OAuth 오류 코드(비밀값 아님)를 보여 원인을 바로 알 수 있게
m = re.search(r"\b(invalid_scope|invalid_grant|invalid_client|unauthorized_client|deleted_client|access_denied|invalid_request)\b", text)
code = m.group(1) if m else ""
if code in ("unauthorized_client", "invalid_client", "deleted_client"):
return (f"Google 토큰 갱신 실패({code}) — 토큰을 발급한 OAuth 클라이언트와 서버 .env 의 "
"GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET(없으면 GOOGLE_CLIENT_ID/SECRET)이 다릅니다.")
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
if "invalid_grant" in text:
return "Google 토큰이 만료·폐기되었습니다. 토큰을 다시 발급해 주세요."
if status == 404:
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
if status == 403:
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''}{f' {code}' if code else ''})."
_CLIENT: GoogleSlidesClient | None = None
_CLIENT_LOCK = threading.Lock()
def get_client() -> GoogleSlidesClient:
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
global _CLIENT
with _CLIENT_LOCK:
if _CLIENT is None or not _CLIENT.enabled:
_CLIENT = GoogleSlidesClient()
return _CLIENT
+70 -4
View File
@@ -15,6 +15,8 @@ from pydantic import BaseModel
from starlette.middleware.sessions import SessionMiddleware
from .modules.cafe24 import build_cafe24_store
from .modules.asset import build_asset_store
from .modules.asset import router as asset_router
from .modules.cafe24 import router as cafe24_router
from .modules.cupang import build_cupang_store, build_itemcode_reader
from .modules.cupang import router as cupang_router
@@ -22,8 +24,12 @@ from .modules.dispatch import build_dispatch_store
from .modules.dispatch import router as dispatch_router
from .modules.expense import CategoryStore, build_expense_store
from .modules.expense import router as expense_router
from .modules.inout import build_inout_items, build_inout_store
from .modules.inout import router as inout_router
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
from .modules.malaysia import router as malaysia_router
from .modules.notice import build_notice_store
from .modules.notice import router as notice_router
from .modules.performance import build_performance_store
from .modules.performance import router as performance_router
from .modules.project import build_project_store
@@ -33,6 +39,8 @@ from .modules.vacation import router as vacation_router
from .store import (
APPROVER_KEYS,
MODULE_KEYS,
ROLE_LABELS,
ROLES,
SUPER_ADMIN_EMAIL,
UserStore,
allowed_modules,
@@ -52,6 +60,8 @@ MODULE_LABELS: dict[str, str] = {
"project": "프로젝트 관리",
"cafe24": "카페24 상품관리",
"performance": "실적",
"asset": "자산관리",
"inout": "입출고 관리",
"expense_approver": "개인경비",
"vacation_approver": "휴가",
}
@@ -110,10 +120,14 @@ def build_google_oauth() -> OAuth:
async def _lifespan(app_: FastAPI): # noqa: ANN201
"""앱 시작 시 백그라운드 작업 시작.
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
start_reminder_thread(getattr(app_.state, "project_store", None))
start_auto_sync_thread(app_.state)
yield
@@ -140,6 +154,9 @@ _MODULE_TEMPLATE_DIRS = [
BASE_DIR / "modules" / "project" / "templates",
BASE_DIR / "modules" / "cafe24" / "templates",
BASE_DIR / "modules" / "performance" / "templates",
BASE_DIR / "modules" / "asset" / "templates",
BASE_DIR / "modules" / "notice" / "templates",
BASE_DIR / "modules" / "inout" / "templates",
]
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
templates.env.loader = ChoiceLoader(
@@ -202,6 +219,13 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
app.state.notice_store = build_notice_store(app.state.project_store)
# 입출고 관리(본사 → 공장 발주, 물류 입고, 미입고): INOUT_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용.
app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None)
app.state.inout_items = build_inout_items()
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
app.include_router(expense_router)
@@ -212,6 +236,9 @@ app.include_router(dispatch_router)
app.include_router(project_router)
app.include_router(cafe24_router)
app.include_router(performance_router)
app.include_router(asset_router)
app.include_router(notice_router)
app.include_router(inout_router)
def public_url_for(request: Request, route_name: str) -> str:
@@ -376,7 +403,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
},
{
"key": "project",
"title": "프로젝트 관리",
"title": "Project",
"subtitle": "Projects",
"description": "프로젝트·서브프로젝트·업무를 달력/타임라인/보드로 관리합니다(아사나식).",
"url": "/project/",
@@ -404,7 +431,22 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
"status": "ready",
"category": "관리",
},
{
"key": "inout",
"title": "입출고 관리",
"subtitle": "Inbound",
"description": "본사에서 공장으로 넣은 제작 발주와 물류 입고 수량을 맞춰 보고, 미입고·초과 입고를 관리합니다.",
"url": "/inout/",
"health_url": "/inout/health",
"status": "ready",
"category": "운영",
},
]
items.append({
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
"description": "사무집기·전산장비의 배정·반납·구매 이력과 HWiNFO 컴퓨터 사양을 관리합니다.",
"url": "/asset/", "health_url": "/asset/health", "status": "ready", "category": "관리",
})
allowed = allowed_modules(user_rec)
for item in items:
item["allowed"] = item["key"] in allowed
@@ -414,6 +456,8 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
def _icon_svg(name: str) -> str:
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
paths = {
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
@@ -476,16 +520,36 @@ def build_erp_nav(
return items
def _login_orbit_names(limit: int = 40) -> list[str]:
"""로그인 화면 왼쪽 패널 — King 주위를 도는 사용자 아이디(이메일 @ 앞, 첫 글자 대문자). 이메일·실명은 내보내지 않는다."""
names: set[str] = set()
try:
users = user_store.list_all()
except Exception: # noqa: BLE001 — 장식이라 실패해도 로그인 화면은 그대로
return []
for u in users:
email = str(u.get("email") or "").lower().strip()
local = email.split("@", 1)[0]
if not local or email == SUPER_ADMIN_EMAIL:
continue
names.add(local[:1].upper() + local[1:])
return sorted(names)[:limit]
def _render_login(request: Request) -> HTMLResponse:
return render_template(request, "login.html", {"orbit_names": _login_orbit_names()})
@app.get("/", response_class=HTMLResponse)
async def home(request: Request) -> HTMLResponse:
sess = get_session_user(request)
if not sess:
return render_template(request, "login.html")
return _render_login(request)
user_rec = user_store.get(sess["email"])
if user_rec is None:
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
request.session.clear()
return render_template(request, "login.html")
return _render_login(request)
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
@@ -631,6 +695,8 @@ async def admin_page(request: Request) -> HTMLResponse:
"module_keys": list(MODULE_KEYS),
"module_labels": MODULE_LABELS,
"approver_keys": list(APPROVER_KEYS),
"roles": list(ROLES),
"role_labels": ROLE_LABELS,
"super_admin_email": SUPER_ADMIN_EMAIL,
"is_admin": True,
},
+9
View File
@@ -0,0 +1,9 @@
# [자산] 자산관리 모듈 — `app/modules/asset/`, `asset_db`
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/ASSET_MODULE.md`.
> 정적 파일: `app/static/asset.css`, `app/static/asset.js`. 템플릿: `templates/`.
- 진입 `/asset/`, 권한키 `asset`. 사무집기·전산장비 개별 자산번호 등록.
- 배정/반납/상태·구매/보증·활동 이력, HWiNFO XML 사양/보고서 보존(`hwinfo.py`), 사진 갤러리(`media.py`), 보고서 모니터 자산(`monitors.py`).
- 삭제는 수퍼관리자(`SUPER_ADMIN_EMAIL`)만 — 이력/원본 보존.
- `ASSET_DB_URL` 미설정 시 저장 비활성, XML 분석 미리보기는 가능.
+9
View File
@@ -0,0 +1,9 @@
"""Company asset management; PostgreSQL only, never creates databases at startup."""
from .router import router
def build_asset_store(*, dsn: str | None):
if not dsn:
return None
from .db import AssetStore
return AssetStore(dsn)
+282
View File
@@ -0,0 +1,282 @@
"""자산·보고서·이력을 함께 저장합니다. DB 생성은 사용자가 서버에서 SQL로 진행합니다."""
from __future__ import annotations
import uuid
from datetime import date, datetime
from decimal import Decimal
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
from .store import AssetConflict, transition
from .media import MAX_PHOTOS
from .monitors import compatible_monitor, monitor_devices
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
SORTS = {"updated": "a.updated_at DESC", "name": "a.name ASC", "tag": "a.tag ASC",
"cost": "a.purchase_cost DESC NULLS LAST", "warranty": "a.warranty_until ASC NULLS LAST"}
def serialize(row):
if row is None:
return None
return {k: (v.isoformat() if isinstance(v, (date, datetime)) else str(v) if isinstance(v, Decimal) else v)
for k, v in row.items()}
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
conditions, params = ["a.deleted_at IS NULL"], []
if q:
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
conditions.append("(concat_ws(' ',a.tag,a.name,a.model,a.serial,a.manufacturer,a.location,a.department,a.assignee_email) ILIKE %s)")
params.append(value)
for col, value in (("category", category), ("status", status), ("location", location), ("assignee_email", assignee)):
if value:
conditions.append(f"a.{col} = %s")
params.append(value)
if warranty:
conditions.append("a.warranty_until BETWEEN (now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date + 30 AND a.status <> 'retired'")
if group == "furniture":
conditions.append("a.category IN ('desk','chair','furniture')")
elif group == "computer":
conditions.append("a.category NOT IN ('desk','chair','furniture')")
return " AND ".join(conditions), params
class AssetStore:
def __init__(self, dsn):
self._pool = ConnectionPool(dsn, min_size=0, max_size=5, timeout=5, open=False,
kwargs={"row_factory": dict_row, "autocommit": True})
self._pool.open(wait=False)
def close(self):
self._pool.close()
def health(self):
with self._pool.connection(timeout=5) as conn:
conn.execute("SELECT id,deleted_at FROM assets LIMIT 1")
conn.execute("SELECT id FROM asset_photos LIMIT 0")
conn.execute("SELECT monitor_key FROM asset_monitor_links LIMIT 0")
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
where, params = filters(**kwargs)
with self._pool.connection() as conn, conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
total = conn.execute(f"SELECT count(*) AS n FROM assets a WHERE {where}", params).fetchone()["n"]
rows = conn.execute(
f"SELECT a.*,r.parsed->'summary' AS specs,r.uploaded_at AS report_at FROM assets a "
"LEFT JOIN asset_reports r ON r.id=a.latest_report_id "
f"WHERE {where} ORDER BY {SORTS.get(sort, SORTS['updated'])},a.id LIMIT %s OFFSET %s",
[*params, page_size, (page - 1) * page_size]).fetchall()
return {"items": [serialize(r) for r in rows], "total": total, "page": page, "page_size": page_size}
def dashboard(self):
with self._pool.connection() as conn, conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
totals = conn.execute("""SELECT count(*) AS total,
count(*) FILTER(WHERE status='available') AS available,
count(*) FILTER(WHERE status='in_use') AS in_use,
count(*) FILTER(WHERE status='maintenance') AS maintenance,
count(*) FILTER(WHERE status='lost') AS lost,
count(*) FILTER(WHERE status='retired') AS retired,
coalesce(sum(purchase_cost) FILTER(WHERE status<>'retired'),0) AS purchase_total,
count(*) FILTER(WHERE status<>'retired' AND warranty_until BETWEEN
(now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date+30) AS warranty_soon
FROM assets WHERE deleted_at IS NULL""").fetchone()
categories = conn.execute("SELECT category,count(*) AS count FROM assets WHERE deleted_at IS NULL GROUP BY category ORDER BY count(*) DESC,category").fetchall()
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' AND deleted_at IS NULL ORDER BY location").fetchall()
activity = conn.execute("SELECT e.*,a.tag,a.name FROM asset_events e JOIN assets a ON a.id=e.asset_id WHERE a.deleted_at IS NULL ORDER BY e.id DESC LIMIT 12").fetchall()
return {"totals": serialize(totals), "categories": categories, "locations": [r["location"] for r in locations],
"activity": [serialize(r) for r in activity]}
def detail(self, asset_id):
with self._pool.connection() as conn, conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL", (asset_id,)).fetchone()
if not asset:
raise KeyError(asset_id)
reports = conn.execute("SELECT id,filename,sha256,uploaded_at,actor,parsed->'summary' AS summary,parsed->>'scan_time' AS scan_time FROM asset_reports WHERE asset_id=%s ORDER BY uploaded_at DESC,id DESC", (asset_id,)).fetchall()
report = conn.execute("SELECT id,filename,uploaded_at,parsed FROM asset_reports WHERE id=%s AND asset_id=%s", (asset["latest_report_id"], asset_id)).fetchone() if asset["latest_report_id"] else None
events = conn.execute("SELECT * FROM asset_events WHERE asset_id=%s ORDER BY id DESC LIMIT 200", (asset_id,)).fetchall()
photos = conn.execute("SELECT id,filename,width,height,uploaded_at,actor FROM asset_photos WHERE asset_id=%s ORDER BY uploaded_at DESC,id", (asset_id,)).fetchall()
monitors = self._monitor_matches(conn, asset_id, report["parsed"]) if report else []
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports],
"events": [serialize(r) for r in events], "photos": [serialize(r) for r in photos], "monitors": monitors}
@staticmethod
def _lock(conn, asset_id, version):
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (asset_id,)).fetchone()
if not asset or asset.get("deleted_at"):
raise KeyError(asset_id)
if asset["version"] != version:
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
return asset
@staticmethod
def _event(conn, asset_id, actor, kind, note, changes):
conn.execute("INSERT INTO asset_events(asset_id,actor,kind,note,changes) VALUES(%s,%s,%s,%s,%s)",
(asset_id, actor, kind, note, Jsonb(changes)))
def create(self, payload, actor, report=None):
with self._pool.connection() as conn, conn.transaction():
return self._create(conn, payload, actor, report)
def _create(self, conn, payload, actor, report=None):
# 모니터 등록도 같은 트랜잭션 안에서 자산 생성과 연결을 함께 처리합니다.
data = payload.model_dump()
asset_id = uuid.uuid4().hex
if not data["tag"]:
data["tag"] = "AST-" + str(conn.execute("SELECT nextval('asset_tag_seq') AS n").fetchone()["n"]).zfill(6)
conn.execute(f"INSERT INTO assets(id,{','.join(FIELDS)}) VALUES({','.join(['%s'] * (len(FIELDS) + 1))})",
[asset_id, *[data[k] for k in FIELDS]])
self._event(conn, asset_id, actor, "create", "자산 등록", {"after": serialize(data)})
if report:
if data["category"] != "computer":
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
self._save_report(conn, asset_id, actor, *report)
return asset_id
def update(self, asset_id, payload, actor):
data = payload.model_dump(exclude={"version"})
with self._pool.connection() as conn, conn.transaction():
old = self._lock(conn, asset_id, payload.version)
if old["latest_report_id"] and data["category"] != "computer":
raise ValueError("사양 보고서가 연결된 자산은 컴퓨터 분류를 유지해야 합니다.")
if not data["tag"]:
data["tag"] = old["tag"]
changes = {k: {"before": serialize(old)[k], "after": serialize(data)[k]} for k in FIELDS if old[k] != data[k]}
if changes:
conn.execute(f"UPDATE assets SET {','.join(k+'=%s' for k in FIELDS)},version=version+1,updated_at=now() WHERE id=%s",
[*[data[k] for k in FIELDS], asset_id])
self._event(conn, asset_id, actor, "update", "자산 정보 수정", changes)
def action(self, asset_id, payload, actor):
with self._pool.connection() as conn, conn.transaction():
old = self._lock(conn, asset_id, payload.version)
status, assignee = transition(old, payload)
location = payload.location or old["location"]
conn.execute("UPDATE assets SET status=%s,assignee_email=%s,location=%s,version=version+1,updated_at=now() WHERE id=%s",
(status, assignee, location, asset_id))
changes = {k: {"before": old[k], "after": value} for k, value in
(("status", status), ("assignee_email", assignee), ("location", location)) if old[k] != value}
self._event(conn, asset_id, actor, payload.action, payload.note, changes)
def _save_report(self, conn, asset_id, actor, filename, raw, parsed):
# 원본과 분석 결과를 함께 저장하고 최신 보고서만 교체합니다. 이전 보고서는 남습니다.
existing = conn.execute("SELECT id FROM asset_reports WHERE asset_id=%s AND sha256=%s", (asset_id, parsed["sha256"])).fetchone()
if existing:
raise AssetConflict("이 자산에 동일한 보고서가 이미 등록되어 있습니다.")
report_id = uuid.uuid4().hex
conn.execute("INSERT INTO asset_reports(id,asset_id,filename,sha256,raw_xml,parsed,actor) VALUES(%s,%s,%s,%s,%s,%s,%s)",
(report_id, asset_id, filename, parsed["sha256"], raw, Jsonb(parsed), actor))
conn.execute("UPDATE assets SET latest_report_id=%s,version=version+1,updated_at=now() WHERE id=%s", (report_id, asset_id))
self._event(conn, asset_id, actor, "report", filename, {"report_id": report_id, "summary": parsed["summary"]})
return report_id
def attach_report(self, asset_id, version, actor, filename, raw, parsed):
with self._pool.connection() as conn, conn.transaction():
asset = self._lock(conn, asset_id, version)
if asset["category"] != "computer":
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
return self._save_report(conn, asset_id, actor, filename, raw, parsed)
def report(self, asset_id, report_id, *, raw=False):
columns = "r.filename,r.raw_xml" if raw else "r.id,r.filename,r.parsed,r.uploaded_at"
with self._pool.connection() as conn:
row = conn.execute(f"SELECT {columns} FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
if not row:
raise KeyError(report_id)
return serialize(row)
def delete(self, asset_id, version, actor, note):
# 수퍼 관리자 삭제도 이력과 원본은 보존하고 대장·다운로드에서 제외합니다.
with self._pool.connection() as conn, conn.transaction():
self._lock(conn, asset_id, version)
self._event(conn, asset_id, actor, "delete", note, {})
conn.execute("UPDATE assets SET deleted_at=now(),deleted_by=%s,version=version+1,updated_at=now() WHERE id=%s", (actor, asset_id))
def add_photo(self, asset_id, version, actor, filename, image, mime, width, height):
with self._pool.connection() as conn, conn.transaction():
self._lock(conn, asset_id, version)
count = conn.execute("SELECT count(*) AS n FROM asset_photos WHERE asset_id=%s", (asset_id,)).fetchone()["n"]
if count >= MAX_PHOTOS:
raise ValueError(f"사진은 자산당 {MAX_PHOTOS}개까지 등록할 수 있습니다.")
photo_id = uuid.uuid4().hex
conn.execute("INSERT INTO asset_photos(id,asset_id,filename,image,mime,width,height,actor) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)",
(photo_id, asset_id, filename, image, mime, width, height, actor))
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (asset_id,))
self._event(conn, asset_id, actor, "photo", filename, {"photo_id": photo_id})
return photo_id
def photo(self, asset_id, photo_id):
with self._pool.connection() as conn:
row = conn.execute("SELECT p.image,p.mime FROM asset_photos p JOIN assets a ON a.id=p.asset_id WHERE p.asset_id=%s AND p.id=%s AND a.deleted_at IS NULL", (asset_id, photo_id)).fetchone()
if not row:
raise KeyError(photo_id)
return row
@staticmethod
def _monitor_matches(conn, computer_id, parsed):
result = []
for device in monitor_devices(parsed):
linked = conn.execute("SELECT a.* FROM asset_monitor_links l JOIN assets a ON a.id=l.monitor_asset_id WHERE l.computer_id=%s AND l.monitor_key=%s AND a.category='monitor' AND a.deleted_at IS NULL", (computer_id, device["key"])).fetchone()
matches = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND lower(btrim(serial))=%s ORDER BY id LIMIT 21", (device["serial"].casefold(),)).fetchall() if device["serial"] else []
compatible = [a for a in matches if compatible_monitor(a, device)]
asset = linked or (compatible[0] if len(compatible) == 1 else None)
candidates = matches if not asset else []
# candidate_by — 후보가 같은 시리얼(같은 실물일 가능성)인지, 참고용 같은 모델·이름인지.
# 같은 모델은 여러 대일 수 있으므로(듀얼 모니터 등) 새 등록을 막지 않는다(2026-10-07).
candidate_by = "serial" if candidates else ""
if not asset and not candidates:
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
candidate_by = "model" if candidates else ""
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
"candidate_by": candidate_by,
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
return result
def report_monitors(self, asset_id, report_id):
with self._pool.connection() as conn, conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
row = conn.execute("SELECT r.parsed FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
if not row:
raise KeyError(report_id)
return self._monitor_matches(conn, asset_id, row["parsed"])
def register_monitor(self, computer_id, index, payload, actor):
with self._pool.connection() as conn, conn.transaction():
computer = self._lock(conn, computer_id, payload.version)
if computer["category"] != "computer" or computer["latest_report_id"] != payload.report_id:
raise AssetConflict("최신 컴퓨터 보고서를 다시 열고 모니터를 등록하세요.")
row = conn.execute("SELECT parsed FROM asset_reports WHERE asset_id=%s AND id=%s", (computer_id, payload.report_id)).fetchone()
devices = monitor_devices(row["parsed"]) if row else []
if index < 0 or index >= len(devices):
raise KeyError(index)
device = devices[index]
# 서로 다른 컴퓨터에서 동일 시리얼을 동시에 등록하는 경우도 중복을 막습니다.
if device["serial"]:
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))", ("asset-monitor:" + device["serial"].casefold(),))
if payload.asset_id:
target = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (payload.asset_id,)).fetchone()
if not target or target["category"] != "monitor":
raise ValueError("등록된 모니터 자산을 선택하세요.")
monitor_id = target["id"]
else:
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
# 같은 시리얼(같은 실물)만 막는다 — 같은 모델이지만 시리얼이 다른 모니터는 새 자산으로 등록된다.
if match["asset"] or match["candidate_by"] == "serial":
raise AssetConflict(f"같은 시리얼({device['serial']})의 모니터가 이미 등록되어 있습니다. 기존 자산에 연결하세요."
if device["serial"] else "이 모니터는 이미 자산에 연결되어 있습니다.")
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
monitor_id = self._create(conn, data, actor)
conn.execute("INSERT INTO asset_monitor_links(computer_id,monitor_key,monitor_asset_id,actor) VALUES(%s,%s,%s,%s) ON CONFLICT(computer_id,monitor_key) DO UPDATE SET monitor_asset_id=EXCLUDED.monitor_asset_id,actor=EXCLUDED.actor,linked_at=now()",
(computer_id, device["key"], monitor_id, actor))
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (computer_id,))
self._event(conn, computer_id, actor, "monitor", "모니터 자산 연결", {"monitor_asset_id": monitor_id, "model": device["model"]})
return monitor_id
+129
View File
@@ -0,0 +1,129 @@
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
from __future__ import annotations
import hashlib
import re
from datetime import datetime
from xml.etree.ElementTree import ParseError
from defusedxml.ElementTree import fromstring
from defusedxml.common import DefusedXmlException
MAX_REPORT_BYTES = 10 * 1024 * 1024
SECTION_LABELS = {
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
}
def _text(node, tag):
return (node.findtext(tag) or "").strip()
def _props(node):
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
def _pick(nodes, *, types=(), labels=()):
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
properties = [p for n in nodes for p in n["properties"]]
for kind in types:
for p in properties:
if p["type"] == kind and p["value"]:
return p["value"]
for label in labels:
for p in properties:
if p["label"].casefold() == label.casefold() and p["value"]:
return p["value"]
return ""
def parse_hwinfo(raw: bytes) -> dict:
if not raw or len(raw) > MAX_REPORT_BYTES:
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
try:
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
computer = root.find("COMPUTER")
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
count = 0
def walk(node, path, result, depth=0):
nonlocal count
count += 1
if count > 30000 or depth > 64:
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
name = _text(node, "NodeName")
trail = path + ([name] if name else [])
props = _props(node)
if props:
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
for child in node:
if child.tag in {"SubNodes", "SubNode"}:
walk(child, trail, result, depth + 1)
elif child.find("NodeName") is not None:
walk(child, trail, result, depth + 1)
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
"path": "시스템", "properties": _props(computer)}]
subnodes = computer.find("SubNodes")
if subnodes is not None:
for node in subnodes:
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
walk(node, [], group["nodes"])
sections.append(group)
by_key = {s["key"]: s["nodes"] for s in sections}
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
summary = {
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
}
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
summary["serial"] = ""
if not summary["memory"]:
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
if re.fullmatch(r"\d+(\.\d+)?", mb):
summary["memory"] = f"{float(mb) / 1024:g} GiB"
devices = {}
for key, types, labels in [
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
]:
devices[key] = []
for node in by_key.get(key, []):
model = _pick([node], types=types, labels=labels)
if model:
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
summary["drive_count"] = len(devices["DRIVES"])
summary["monitor_count"] = len(devices["MONITOR"])
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
scan_time = _text(computer, "ScanTime")
try:
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
except ValueError:
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}
+38
View File
@@ -0,0 +1,38 @@
"""사진을 실제 이미지로 확인하고 위치 정보 등 메타데이터를 제거합니다."""
import io
import warnings
from PIL import Image, ImageOps, UnidentifiedImageError
MAX_PHOTO_BYTES = 8 * 1024 * 1024
MAX_STORED_BYTES = 5 * 1024 * 1024
MAX_PHOTOS = 10
def prepare_photo(raw):
if not raw or len(raw) > MAX_PHOTO_BYTES:
raise ValueError("사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.")
try:
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(raw)) as source:
if source.format not in {"JPEG", "PNG", "WEBP"}:
raise ValueError("JPG, PNG, WebP 사진만 등록할 수 있습니다.")
if source.width * source.height > 20_000_000:
raise ValueError("사진은 2천만 화소 이하로 등록하세요.")
source.load()
image = ImageOps.exif_transpose(source)
image.thumbnail((2400, 2400))
transparent = "A" in image.getbands() or "transparency" in image.info
mode = "RGBA" if transparent else "RGB"
# 새 캔버스에 복사해 EXIF, GPS, 촬영기기 정보를 저장하지 않습니다.
clean = Image.new(mode, image.size)
clean.paste(image.convert(mode))
output = io.BytesIO()
clean.save(output, format="PNG" if transparent else "JPEG", **({} if transparent else {"quality": 88}))
data = output.getvalue()
if len(data) > MAX_STORED_BYTES:
raise ValueError("사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.")
return data, "image/png" if transparent else "image/jpeg", clean.width, clean.height
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
raise ValueError("사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.") from exc
+47
View File
@@ -0,0 +1,47 @@
"""이전 보고서에도 적용할 수 있도록 저장된 모니터 항목에서 식별 정보를 읽습니다."""
import hashlib
import re
def usable_serial(value):
value = value.strip()
if value.casefold() in {"", "unknown", "n/a", "none", "not specified", "serial number", "알 수 없음"}:
return ""
if re.fullmatch(r"[0\s-]+", value):
return ""
return value
def compatible_monitor(asset, device):
"""다른 제조사나 다른 모델이 같은 시리얼을 쓰면 자동 연결하지 않습니다."""
def normalized(value):
return "".join(c for c in value.casefold() if c.isalnum())
brand = normalized(asset.get("manufacturer", ""))
reported_brand = normalized(device["manufacturer"])
if brand and reported_brand and brand != reported_brand:
return False
model = normalized(asset.get("model", ""))
if not model:
return True
return any(model == value or len(model) >= 4 and model in value
for value in (normalized(device["model"]), normalized(device["name"])))
def monitor_devices(parsed):
devices = []
for index, item in enumerate(parsed.get("devices", {}).get("MONITOR", [])):
props = item.get("properties", [])
def pick(*labels, kind=""):
return next((p["value"].strip() for p in props if p.get("label", "").casefold() in
{label.casefold() for label in labels} or kind and p.get("type") == kind), "")
name = item.get("name", "모니터")
model = pick("모니터 이름(제조업체)", "Monitor Name (Manuf)", "Monitor Name (Manufacturer)") or name
serial = usable_serial(pick("일련 번호", "Serial Number", "Monitor Serial Number"))
instance = pick("디바이스 인스턴스 ID", "Device Instance ID", kind="DeviceInstanceId")
# 시리얼이 없는 장치는 모델명만으로 동일 자산이라고 판단하지 않습니다.
identity = ("serial:" + serial.casefold() + ":" + model.casefold()) if serial else (
"instance:" + instance.casefold() if instance else f"report:{parsed.get('sha256', '')}:{index}")
devices.append({"index": index, "key": hashlib.sha256(identity.encode()).hexdigest(),
"name": name, "model": model[:200], "serial": serial[:200],
"manufacturer": name.split(" ", 1)[0][:150], "properties": props})
return devices
+304
View File
@@ -0,0 +1,304 @@
from __future__ import annotations
# 화면, 권한 검사, 파일 업로드를 담당합니다. 실제 저장은 db.py에서 처리합니다.
import io
import secrets
from contextlib import contextmanager
from typing import Annotated
from urllib.parse import quote
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import RedirectResponse, Response
from openpyxl import Workbook
from pydantic import ValidationError
from psycopg import Error as DBError
from psycopg.errors import UniqueViolation
from psycopg_pool import PoolTimeout
from starlette.concurrency import run_in_threadpool
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
from .store import DeleteInput, MonitorInput
from .media import MAX_PHOTO_BYTES, prepare_photo
router = APIRouter(prefix="/asset", tags=["asset"])
def _user(request: Request):
from app.main import get_current_user_record
from app.store import has_module
user = get_current_user_record(request)
if not user:
raise HTTPException(401, "로그인이 필요합니다.")
if not has_module(user, "asset"):
raise HTTPException(403, "자산관리 권한이 없습니다.")
return user
def _write(request: Request, user=Depends(_user)):
expected = request.session.get("asset_csrf", "")
token = request.headers.get("x-asset-csrf", "")
if not expected or not secrets.compare_digest(expected, token):
raise HTTPException(403, "화면을 새로 열고 다시 시도하세요.")
return user
def _super(user):
from app.store import SUPER_ADMIN_EMAIL
return user.get("email", "").lower() == SUPER_ADMIN_EMAIL
def _super_write(user=Depends(_write)):
if not _super(user):
raise HTTPException(403, "수퍼 관리자만 자산을 삭제할 수 있습니다.")
return user
def _store(request):
store = getattr(request.app.state, "asset_store", None)
if store is None:
raise HTTPException(503, "자산관리 DB 설정이 필요합니다. 관리자에게 문의하세요.")
return store
@contextmanager
def _errors():
try:
yield
except AssetConflict as exc:
raise HTTPException(409, str(exc)) from exc
except KeyError as exc:
raise HTTPException(404, "자산 또는 보고서를 찾을 수 없습니다.") from exc
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
except UniqueViolation as exc:
raise HTTPException(409, "이미 등록된 자산번호입니다. 다른 번호를 사용하세요.") from exc
except (DBError, PoolTimeout) as exc:
# DB 오류에 접속 비밀번호가 섞일 수 있어 원문 대신 일반 안내만 보여줍니다.
raise HTTPException(503, "자산관리 DB에 연결할 수 없습니다. 설정과 초기화를 확인하세요.") from exc
@router.get("/")
def index(request: Request):
from app.main import build_erp_nav, get_current_user_record, render_template
from app.store import has_module, is_admin
user = get_current_user_record(request)
if not user:
return RedirectResponse("/login", 303)
if not has_module(user, "asset"):
return render_template(request, "denied.html", {"reason": "자산관리 권한이 없습니다.", "user": user,
"is_admin": is_admin(user)}, status_code=403)
request.session.setdefault("asset_csrf", secrets.token_urlsafe(32))
return render_template(request, "asset/index.html", {
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="asset"),
"page_title": "자산관리", "page_subtitle": "사무집기부터 컴퓨터 사양까지, 회사 자산을 한곳에서",
"categories": CATEGORIES, "statuses": STATUSES, "csrf_token": request.session["asset_csrf"],
"configured": getattr(request.app.state, "asset_store", None) is not None,
"can_delete": _super(user),
})
@router.get("/health")
def health(request: Request, user=Depends(_user)):
with _errors():
_store(request).health()
return {"ok": True}
@router.get("/api/bootstrap")
def bootstrap(request: Request, user=Depends(_user)):
from app.main import user_store
with _errors():
data = _store(request).dashboard()
data["users"] = [{"email": u["email"], "name": u.get("name") or u["email"]} for u in user_store.list_all()]
return data
def _query(q="", category="", status="", location="", assignee="", warranty=False, group=""):
if category and category not in CATEGORIES or status and status not in STATUSES:
raise HTTPException(422, "분류 또는 상태 필터가 올바르지 않습니다.")
if group not in {"", "computer", "furniture"}:
raise HTTPException(422, "자산 구분 필터가 올바르지 않습니다.")
return dict(q=q, category=category, status=status, location=location, assignee=assignee, warranty=warranty, group=group)
@router.get("/api/assets")
def assets(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
page: int = Query(1, ge=1, le=100000), page_size: int = Query(25, ge=1, le=100),
sort: str = "updated", group: str = "", user=Depends(_user)):
with _errors():
return _store(request).list_assets(page=page, page_size=page_size, sort=sort,
**_query(q, category, status, location, assignee, warranty, group))
@router.get("/api/export")
def export(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
group: str = "", user=Depends(_user)):
from app.timezone import today_kst
with _errors():
data = _store(request).list_assets(page=1, page_size=10001, **_query(q, category, status, location, assignee, warranty, group))
if data["total"] > 10000:
raise HTTPException(422, "한 번에 10,000개까지 내보낼 수 있습니다. 필터를 좁혀주세요.")
book = Workbook()
sheet = book.active
sheet.title = "자산대장"
headers = ["자산번호", "자산명", "분류", "상태", "제조사", "모델", "시리얼", "위치", "부서", "사용자", "구매일", "구매금액(원)", "구매처", "보증종료", "메모", "CPU", "메모리", "GPU", "운영체제"]
sheet.append(headers)
for row in data["items"]:
specs = row.get("specs") or {}
values = [row["tag"], row["name"], CATEGORIES[row["category"]], STATUSES[row["status"]],
*[row[k] for k in ("manufacturer", "model", "serial", "location", "department", "assignee_email", "purchased_on")],
float(row["purchase_cost"]) if row["purchase_cost"] is not None else None,
row["vendor"], row["warranty_until"], row["notes"], *[specs.get(k, "") for k in ("cpu", "memory", "gpu", "os")]]
sheet.append(values)
# =로 시작하는 자산명도 엑셀 수식 대신 일반 글자로 저장합니다.
for cell in sheet[sheet.max_row]:
if isinstance(cell.value, str):
cell.data_type = "s"
sheet.freeze_panes = "C2"
sheet.auto_filter.ref = sheet.dimensions
from openpyxl.styles import Font, PatternFill
from openpyxl.utils import get_column_letter
for cell in sheet[1]:
cell.font = Font(bold=True, color="FFFFFF")
cell.fill = PatternFill("solid", fgColor="171717")
for i in range(1, len(headers) + 1):
sheet.column_dimensions[get_column_letter(i)].width = 22 if i > 2 else 28
buffer = io.BytesIO()
book.save(buffer)
return Response(buffer.getvalue(), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": f'attachment; filename="assets-{today_kst().isoformat()}.xlsx"'})
@router.post("/api/assets")
def create(request: Request, payload: AssetInput, user=Depends(_write)):
with _errors():
asset_id = _store(request).create(payload, user["email"])
return {"id": asset_id}
@router.get("/api/assets/{asset_id}")
def detail(request: Request, asset_id: str, user=Depends(_user)):
with _errors():
return _store(request).detail(asset_id)
@router.put("/api/assets/{asset_id}")
def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_write)):
with _errors():
_store(request).update(asset_id, payload, user["email"])
return {"ok": True}
@router.delete("/api/assets/{asset_id}")
def delete(request: Request, asset_id: str, payload: DeleteInput, user=Depends(_super_write)):
with _errors():
_store(request).delete(asset_id, payload.version, user["email"], payload.note)
return {"ok": True}
@router.post("/api/assets/{asset_id}/photos")
async def add_photo(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
filename = (file.filename or "photo.jpg").replace("\\", "/").rsplit("/", 1)[-1]
try:
if len(filename) > 200 or any(ord(c) < 32 for c in filename):
raise HTTPException(422, "사진 파일 이름을 확인하세요.")
raw = await file.read(MAX_PHOTO_BYTES + 1)
finally:
await file.close()
with _errors():
image, mime, width, height = await run_in_threadpool(prepare_photo, raw)
photo_id = await run_in_threadpool(_store(request).add_photo, asset_id, version, user["email"], filename, image, mime, width, height)
return {"id": photo_id}
@router.get("/api/assets/{asset_id}/photos/{photo_id}")
def photo(request: Request, asset_id: str, photo_id: str, user=Depends(_user)):
with _errors():
row = _store(request).photo(asset_id, photo_id)
return Response(bytes(row["image"]), media_type=row["mime"],
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
@router.get("/api/assets/{asset_id}/reports/{report_id}/monitors")
def report_monitors(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
with _errors():
return {"items": _store(request).report_monitors(asset_id, report_id)}
@router.post("/api/assets/{asset_id}/monitors/{index}")
def register_monitor(request: Request, asset_id: str, index: int, payload: MonitorInput, user=Depends(_write)):
with _errors():
monitor_id = _store(request).register_monitor(asset_id, index, payload, user["email"])
return {"id": monitor_id}
@router.post("/api/assets/{asset_id}/actions")
def action(request: Request, asset_id: str, payload: ActionInput, user=Depends(_write)):
from app.main import user_store
if payload.action == "checkout" and not user_store.get(payload.assignee_email.lower()):
raise HTTPException(422, "등록된 회사 사용자를 선택하세요.")
with _errors():
_store(request).action(asset_id, payload, user["email"])
return {"ok": True}
async def _report_file(file):
filename = (file.filename or "report.xml").replace("\\", "/").rsplit("/", 1)[-1]
if not filename.lower().endswith(".xml") or len(filename) > 200 or any(ord(c) < 32 for c in filename):
raise HTTPException(422, "이름이 200자 이하인 XML 보고서를 선택하세요.")
try:
raw = await file.read(MAX_REPORT_BYTES + 1)
finally:
await file.close()
with _errors():
parsed = await run_in_threadpool(parse_hwinfo, raw)
return filename, raw, parsed
@router.post("/api/reports/preview")
async def preview(file: Annotated[UploadFile, File()], user=Depends(_write)):
filename, raw, parsed = await _report_file(file)
return {"filename": filename, "summary": parsed["summary"], "scan_time": parsed["scan_time"],
"property_count": parsed["property_count"], "warnings": parsed["warnings"]}
@router.post("/api/reports/import")
async def import_report(request: Request, file: Annotated[UploadFile, File()], payload: Annotated[str, Form(max_length=20000)], user=Depends(_write)):
with _errors():
try:
data = AssetInput.model_validate_json(payload)
except ValidationError as exc:
raise HTTPException(422, "자산명·분류·구매일·금액을 확인하세요.") from exc
report = await _report_file(file)
with _errors():
asset_id = await run_in_threadpool(_store(request).create, data, user["email"], report)
return {"id": asset_id}
@router.post("/api/assets/{asset_id}/reports")
async def attach(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
filename, raw, parsed = await _report_file(file)
with _errors():
report_id = await run_in_threadpool(_store(request).attach_report, asset_id, version, user["email"], filename, raw, parsed)
return {"id": report_id}
@router.get("/api/assets/{asset_id}/reports/{report_id}")
def report_detail(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
with _errors():
return _store(request).report(asset_id, report_id)
@router.get("/api/assets/{asset_id}/reports/{report_id}/download")
def download(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
with _errors():
row = _store(request).report(asset_id, report_id, raw=True)
return Response(bytes(row["raw_xml"]), media_type="application/octet-stream",
headers={"Content-Disposition": f"attachment; filename=hwinfo.xml; filename*=UTF-8''{quote(row['filename'], safe='')}",
"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
+106
View File
@@ -0,0 +1,106 @@
"""Asset validation and lifecycle rules, shared by API and storage."""
from datetime import date
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
CATEGORIES = {"computer": "컴퓨터", "monitor": "모니터", "mouse": "마우스", "keyboard": "키보드",
"camera": "카메라", "hub": "허브 · 네트워크", "lighting": "조명", "desk": "책상",
"chair": "의자", "furniture": "기타 사무집기", "equipment": "기타 전산장비"}
STATUSES = {"available": "사용 가능", "in_use": "사용 중", "maintenance": "수리 중", "lost": "분실", "retired": "폐기"}
class AssetInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
tag: str = Field(default="", max_length=64)
name: str = Field(min_length=1, max_length=200)
category: str
manufacturer: str = Field(default="", max_length=150)
model: str = Field(default="", max_length=200)
serial: str = Field(default="", max_length=200)
location: str = Field(default="", max_length=150)
department: str = Field(default="", max_length=100)
purchased_on: date | None = None
purchase_cost: Decimal | None = Field(default=None, ge=0, le=10**12, decimal_places=2)
vendor: str = Field(default="", max_length=200)
warranty_until: date | None = None
notes: str = Field(default="", max_length=10000)
@field_validator("category")
@classmethod
def valid_category(cls, value):
if value not in CATEGORIES:
raise ValueError("자산 분류가 올바르지 않습니다.")
return value
@model_validator(mode="after")
def valid_dates(self):
if self.purchased_on and self.warranty_until and self.warranty_until < self.purchased_on:
raise ValueError("보증 종료일은 구매일 이후여야 합니다.")
return self
class AssetUpdate(AssetInput):
version: int = Field(ge=1)
class DeleteInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
version: int = Field(ge=1)
note: str = Field(min_length=1, max_length=2000)
class MonitorInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
version: int = Field(ge=1)
report_id: str = Field(min_length=1, max_length=64)
asset: AssetInput | None = None
asset_id: str = Field(default="", max_length=64)
@model_validator(mode="after")
def require_target(self):
if bool(self.asset) == bool(self.asset_id):
raise ValueError("등록할 정보 또는 연결할 모니터 자산 중 하나를 지정하세요.")
if self.asset and self.asset.category != "monitor":
raise ValueError("모니터 분류로 등록하세요.")
return self
class ActionInput(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
version: int = Field(ge=1)
action: str
assignee_email: str = Field(default="", max_length=254)
location: str = Field(default="", max_length=150)
note: str = Field(default="", max_length=2000)
@model_validator(mode="after")
def require_reason(self):
if self.action in {"lost", "retired"} and not self.note:
raise ValueError("분실·폐기 사유를 입력하세요.")
return self
class AssetConflict(ValueError):
pass
def transition(asset, payload: ActionInput):
state = asset["status"]
if payload.action == "checkout":
if state != "available" or not payload.assignee_email:
raise ValueError("사용 가능한 자산을 선택하고 배정할 사용자를 지정하세요.")
return "in_use", payload.assignee_email.lower()
if payload.action == "checkin":
if state != "in_use":
raise ValueError("사용 중인 자산만 반납할 수 있습니다.")
return "available", ""
if payload.action == "maintenance" and state == "available":
return "maintenance", ""
if payload.action == "available" and state in {"maintenance", "lost", "retired"}:
return "available", ""
if payload.action == "lost" and state in {"available", "in_use", "maintenance"}:
return "lost", asset.get("assignee_email", "")
if payload.action == "retired" and state in {"available", "maintenance", "lost"}:
return "retired", ""
raise ValueError("현재 상태에서 처리할 수 없습니다. 배정된 자산은 먼저 반납하세요.")
@@ -0,0 +1,70 @@
{% extends "erp_base.html" %}
{% set force_sidebar_collapsed = true %}
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006c">{% endblock %}
{% block content %}
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}" data-can-delete="{{ 'true' if can_delete else 'false' }}">
<aside class="am-nav" aria-label="자산관리 탐색">
<div class="am-nav-brand"><span class="am-mark">A</span><div><strong>회사 자산</strong><small>ASSET MANAGEMENT</small></div></div>
<button class="am-nav-link is-active" data-view="all"><span>전체 자산</span><span id="am-nav-total" class="am-count">—</span></button>
<button class="am-nav-link" data-view="computer"><span>컴퓨터 · 전산장비</span></button>
<button class="am-nav-link" data-view="furniture"><span>사무실 · 집기</span></button>
<p class="am-nav-label">자산 상태</p>
{% for key,label in statuses.items() %}<button class="am-nav-link" data-state="{{ key }}"><span><i class="am-dot am-dot-{{ key }}"></i>{{ label }}</span><span class="am-count" id="am-count-{{ key }}">—</span></button>{% endfor %}
<p class="am-nav-label">확인할 항목</p>
<button class="am-nav-link" data-view="warranty"><span>보증 만료 예정</span><span class="am-count" id="am-count-warranty">—</span></button>
<div class="am-nav-foot"><strong>자산 한 개, 기록 하나</strong><p>개별 자산번호로 등록하고<br>배정부터 폐기까지 추적하세요.</p><button class="am-text-btn" id="am-help-open">사용 안내 ↗</button></div>
</aside>
<section class="am-main" aria-label="자산대장">
<div class="am-heading"><div><p class="am-eyebrow">COMPANY INVENTORY</p><h2>회사 자산 대장</h2><p>어떤 자산이, 어디에, 누구에게 있는지 확인하세요.</p></div><div class="am-heading-actions"><button class="erp-btn erp-btn-outline" id="am-import">↑ HWiNFO 보고서</button><button class="erp-btn erp-btn-primary" id="am-create" {% if not configured %}disabled{% endif %}>+ 자산 등록</button></div></div>
{% if not configured %}<div class="am-notice" role="status"><strong>자산관리 저장소 설정이 필요합니다.</strong><p>관리자가 자산관리 DB를 연결하면 등록·배정·반납을 사용할 수 있습니다. HWiNFO 보고서는 지금도 분석 결과를 미리 볼 수 있습니다.</p></div>{% endif %}
<div id="am-message" class="am-message" role="status" aria-live="polite" hidden></div>
<div class="am-kpis" aria-label="자산 현황">
<button data-kpi="all" class="am-kpi"><span>전체 자산</span><strong id="am-total">—</strong><small>회사에 등록된 자산</small></button>
<button data-kpi="in_use" class="am-kpi"><span><i class="am-dot am-dot-in_use"></i>사용 중</span><strong id="am-in_use">—</strong><small>직원에게 배정된 자산</small></button>
<button data-kpi="available" class="am-kpi"><span><i class="am-dot am-dot-available"></i>사용 가능</span><strong id="am-available">—</strong><small>새로 배정할 수 있는 자산</small></button>
<button data-kpi="maintenance" class="am-kpi"><span><i class="am-dot am-dot-maintenance"></i>수리 중</span><strong id="am-maintenance">—</strong><small>점검 · 수리 중인 자산</small></button>
<button data-kpi="warranty" class="am-kpi"><span>보증 만료 예정</span><strong id="am-warranty_soon">—</strong><small>오늘부터 30일 이내</small></button>
</div>
<div class="am-register">
<div class="am-register-head"><div><h3 id="am-list-title">전체 자산</h3><span id="am-result-count">자산을 불러오는 중</span></div><div><button class="am-text-btn" id="am-refresh" aria-label="자산 새로고침">↻ 새로고침</button><button class="erp-btn erp-btn-outline" id="am-export" {% if not configured %}disabled{% endif %}>엑셀 내보내기 ↓</button></div></div>
<form class="am-filters" id="am-filters" role="search">
<label class="am-search"><span aria-hidden="true">⌕</span><input id="am-query" type="search" maxlength="200" placeholder="자산명, 번호, 모델, 시리얼 검색" aria-label="자산 검색"></label>
<select id="am-category" aria-label="분류"><option value="">모든 분류</option>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
<select id="am-status" aria-label="상태"><option value="">모든 상태</option>{% for key,label in statuses.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
<select id="am-location" aria-label="위치"><option value="">모든 위치</option></select>
<select id="am-assignee" aria-label="배정 사용자"><option value="">모든 사용자</option></select>
<select id="am-sort" aria-label="정렬"><option value="updated">최근 변경순</option><option value="name">자산명순</option><option value="tag">자산번호순</option><option value="cost">구매금액순</option><option value="warranty">보증종료순</option></select>
<button type="button" class="am-text-btn" id="am-reset">초기화</button>
</form>
<div class="am-table-scroll"><table class="am-table"><thead><tr><th>자산</th><th>분류</th><th>상태</th><th>사용자 / 위치</th><th>구매금액</th><th>보증 종료</th><th>사양</th></tr></thead><tbody id="am-rows"><tr><td colspan="7" class="am-empty">{% if configured %}자산을 불러오는 중입니다.{% else %}등록된 자산이 여기에 표시됩니다.{% endif %}</td></tr></tbody></table></div>
<div class="am-pagination"><span id="am-page-info">—</span><div><button class="erp-btn erp-btn-outline" id="am-prev" disabled>← 이전</button><span id="am-page-number">1</span><button class="erp-btn erp-btn-outline" id="am-next" disabled>다음 →</button></div></div>
</div>
<div class="am-bottom"><section class="am-panel"><div class="am-panel-head"><h3>자산 구성</h3><span>분류별 등록 수</span></div><div id="am-breakdown" class="am-breakdown"><p class="am-muted">등록된 자산이 없습니다.</p></div><div class="am-value"><span>보유 자산 구매금액 <small>폐기 제외 · 입력된 금액 기준</small></span><strong id="am-value">—</strong></div></section><section class="am-panel"><div class="am-panel-head"><h3>최근 활동</h3><span>등록 · 배정 · 반납 · 변경</span></div><div id="am-activity" class="am-activity"><p class="am-muted">활동 이력이 여기에 표시됩니다.</p></div></section></div>
</section>
</div>
<dialog id="am-detail" class="am-drawer" aria-labelledby="am-detail-title"><div class="am-dialog-head"><div><small id="am-detail-tag">자산 상세</small><h2 id="am-detail-title">자산 정보</h2></div><button type="button" class="am-close" data-close="am-detail" aria-label="자산 상세 닫기">×</button></div><div id="am-detail-content"></div></dialog>
<dialog id="am-editor" class="am-dialog" aria-labelledby="am-editor-title"><div class="am-dialog-head"><div><small>ASSET REGISTER</small><h2 id="am-editor-title">자산 등록</h2></div><button type="button" class="am-close" data-close="am-editor" aria-label="등록 창 닫기">×</button></div><form id="am-editor-form" class="am-form"><div class="am-form-grid">
<label>자산명 <span>*</span><input name="name" maxlength="200" required placeholder="예: 디자인팀 데스크톱"></label>
<label>자산번호<input name="tag" maxlength="64" placeholder="비워두면 자동 발급 (AST-000001)"></label>
<label>분류 <span>*</span><select name="category" required>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
<label>제조사<input name="manufacturer" maxlength="150" placeholder="예: Dell, 시디즈"></label>
<label>모델<input name="model" maxlength="200"></label><label>시리얼 번호<input name="serial" maxlength="200"></label>
<label>위치<input name="location" maxlength="150" list="am-locations" placeholder="예: 본사 3층 디자인팀"></label><label>부서<input name="department" maxlength="100"></label>
<label>구매일<input type="date" name="purchased_on"></label><label>구매금액 (원)<input type="number" name="purchase_cost" min="0" max="1000000000000" step="0.01" placeholder="미입력 가능"></label>
<label>구매처<input name="vendor" maxlength="200"></label><label>보증 종료일<input type="date" name="warranty_until"></label>
<label class="am-wide">메모<textarea name="notes" maxlength="10000" rows="3" placeholder="관리에 필요한 추가 정보를 입력하세요."></textarea></label>
</div><p class="am-form-hint">같은 모델도 자산번호를 각각 발급합니다. 사용자 배정은 등록 후 상세 화면에서 진행합니다.</p><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-editor">취소</button><button type="submit" class="erp-btn erp-btn-primary">자산 저장</button></div></form></dialog>
<dialog id="am-upload" class="am-dialog am-upload-dialog" aria-labelledby="am-upload-title"><div class="am-dialog-head"><div><small>HWiNFO XML IMPORT</small><h2 id="am-upload-title">컴퓨터 보고서 가져오기</h2></div><button type="button" class="am-close" data-close="am-upload" aria-label="업로드 창 닫기">×</button></div><form id="am-upload-form" class="am-form">
<p class="am-form-hint" id="am-upload-hint">HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.</p>
<label class="am-drop" id="am-drop"><span class="am-upload-icon">↑</span><strong>XML 보고서 선택</strong><span>파일을 여기에 놓거나 클릭하세요 · 최대 10 MB</span><input type="file" id="am-report-file" accept=".xml" aria-label="HWiNFO XML 보고서 선택" required></label>
<div id="am-report-preview" hidden></div>
<div id="am-import-fields" class="am-form-grid" hidden><label>자산명 <span>*</span><input id="am-import-name" maxlength="200" required></label><label>위치<input id="am-import-location" maxlength="150" list="am-locations" placeholder="예: 본사 3층"></label></div>
<div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><span id="am-upload-status" class="am-muted"></span><button type="button" class="erp-btn erp-btn-outline" data-close="am-upload">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-import-save" disabled>자산으로 등록</button></div>
</form></dialog>
<dialog id="am-action" class="am-dialog am-action-dialog" aria-labelledby="am-action-title"><div class="am-dialog-head"><div><small id="am-action-tag"></small><h2 id="am-action-title">자산 배정</h2></div><button type="button" class="am-close" data-close="am-action" aria-label="처리 창 닫기">×</button></div><form id="am-action-form" class="am-form"><p id="am-action-hint" class="am-form-hint"></p><label id="am-action-user-label">배정할 사용자 <span>*</span><select id="am-action-user"><option value="">사용자 선택</option></select></label><label>자산 위치<input id="am-action-location" list="am-locations" maxlength="150"></label><label>처리 메모<textarea id="am-action-note" maxlength="2000" rows="3" placeholder="배정 사유, 반납 상태, 수리 내용 등을 기록하세요."></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-action">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-action-save">처리하기</button></div></form></dialog>
<dialog id="am-help" class="am-dialog" aria-labelledby="am-help-title"><div class="am-dialog-head"><h2 id="am-help-title">자산관리 사용 안내</h2><button class="am-close" data-close="am-help" aria-label="사용 안내 닫기">×</button></div><div class="am-form am-help"><h3>01. 자산 등록</h3><p>책상·의자·마우스 등은 개별 자산으로 등록합니다. 자산번호를 비워두면 자동 발급합니다. 컴퓨터는 HWiNFO 보고서를 가져오면 이름과 주요 사양을 확인하고 등록할 수 있습니다.</p><h3>02. 배정과 반납</h3><p>사용 가능한 자산을 등록된 회사 사용자에게 배정합니다. 사용 중인 자산은 반납 후 수리·폐기할 수 있습니다. 위치·사유와 처리자가 이력에 남습니다. 분실 처리 시 기존 배정 사용자도 기록됩니다.</p><h3>03. 컴퓨터 사양</h3><p>HWiNFO → 보고서 저장 → XML 형식을 선택합니다. 핵심 사양, 부품별 상세와 보고서 전체 항목을 볼 수 있습니다. 재업로드할 때 컴퓨터 이름을 확인하세요. 이전 보고서와 원본 XML은 보존됩니다.</p><h3>04. 찾기와 내보내기</h3><p>검색·분류·상태·위치·사용자 필터를 조합합니다. 엑셀 내보내기는 현재 필터에 해당하는 자산 전체를 포함하며 최대 10,000개입니다. 보증 만료 예정은 오늘부터 30일 이내입니다.</p><p class="am-form-hint">보고서에는 시리얼·MAC 주소 등 회사 장비 정보가 포함될 수 있습니다. 자산관리 권한을 가진 사용자만 조회할 수 있습니다.</p></div></dialog>
<datalist id="am-locations"></datalist>
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
{% endblock %}
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261007a" defer></script>{% endblock %}
+36
View File
@@ -0,0 +1,36 @@
# [카페24] 카페24 상품관리 모듈 — `app/modules/cafe24/`, `cafe24_db`
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
> 공통 API 계층: `app/integrations/cafe24/` — **실적 모듈 카페24 어댑터도 같은 토큰을 씀**, 바꾸면 실적 영향 확인.
> 배포 시 이 모듈 변경이면 `dbx-cafe24-worker` 도 같이 재빌드.
## 기능
- 카페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` 에 넣는 방식은 적용 안 됨.
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 코드 복사」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
- 권한키 `cafe24`(연결/해제는 admin 전용).
## 규칙
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
- 디자인 FTP(스와이프·상품상세) 쓰기는 임시 파일 → 검증 → rename. **카페24 FTP 는 허용 확장자만 받으므로 임시 이름도 원래 확장자로 끝나야 함**(`x_cf24tmp_<tag>.js`, `design_ftp.temp_names`). `x.js.cf24tmp-…` 는 `550 Operation not permitted`.
- 예약은 DB 저장 + 별도 worker(`worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다.
## 읽기 지연 ("마지막 쓰기가 권위")
- **카페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`).
- 진열/판매만 바꾼 PUT 은 `updated_date` 가 안 오를 수 있음 → **같은 시각 + 값 다름 = 지연**.
- 단건 GET 뿐 아니라 **목록·예약 미리보기도 보정** 필수(`store.overlay_product_rows`). 빠뜨리면 "진열/중지 바꿔도 반영 안 됨"으로 보임.
- 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분).
- 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다.
- API 문서 예제는 apidocs.cafe24.com 청크 JS 에서 추출(예전 `/docs/code` JSON 은 404).
+21
View File
@@ -663,6 +663,27 @@ class Cafe24Store:
return {}
return dict(row["last_write_snapshot"])
def get_recent_product_snapshots(self, grace_minutes: int) -> dict[int, dict[str, Any]]:
"""유예시간 안에 쓴 상품들의 product 스냅샷 섹션 {product_no: {"data", "written_at"}}.
목록 화면이 상품마다 따로 조회하지 않고 한 번에 지연 보정하기 위한 것이다.
섹션별 written_at 판정은 store.overlay_recent_write 가 다시 한다.
"""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT product_no, last_write_snapshot -> 'product' AS product
FROM cafe24_products
WHERE last_written_at >= now() - make_interval(mins => %s)
AND last_write_snapshot ? 'product'
""",
(max(0, int(grace_minutes)),),
).fetchall()
return {
int(r["product_no"]): dict(r["product"])
for r in rows if isinstance(r.get("product"), dict)
}
# ════════════════════════════════════════════════════════════
# 상세페이지 HTML 버전 (append-only — UPDATE/DELETE 하지 않는다)
# 쓰기 직전 BACKUP 을 남기는 것이 유일한 복구 수단이다.
+7
View File
@@ -328,6 +328,13 @@ def product_list(request: Request) -> HTMLResponse:
error = ""
try:
raw_rows, truncated = products.list_all_products(api.client, product_name=keyword)
# 목록 API 도 쓰기 직후 한동안 예전 값을 준다 — 진열/판매 등을 최근 쓰기로 보정한다.
try:
snapshots = st.get_recent_product_snapshots(read_lag_grace_minutes())
except Exception: # noqa: BLE001 — 보정 실패는 목록 표시를 막지 않는다
logger.exception("카페24 최근 쓰기 스냅샷 조회 실패")
snapshots = {}
raw_rows = store.overlay_product_rows(raw_rows, snapshots, grace_minutes=read_lag_grace_minutes())
st.upsert_products([products.normalize_product(r) for r in raw_rows])
total = len(raw_rows)
rows = [_row_for_list(r) for r in raw_rows]
+2 -2
View File
@@ -26,7 +26,7 @@ from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config,
from . import store, writes
from .common import base_ctx, guard
from .routes_products import _no_store
from .routes_products import _no_store, load_product
logger = logging.getLogger("cafe24.schedules")
@@ -187,7 +187,7 @@ def schedule_current_flags(request: Request, product_no: int) -> dict:
st, _user = require_store(request)
api = build_cafe24_api(st)
try:
raw = products.get_product(api.client, product_no)
raw, _ = load_product(st, api, product_no) # 방금 바꾼 진열/판매가 지연으로 예전 값이 되지 않게
except Cafe24Error as exc:
return {"product_no": product_no, "error": str(exc)}
normalized = products.normalize_product(raw)
+53 -1
View File
@@ -640,6 +640,12 @@ def overlay_recent_write(
보다 GET 의 updated_date 가 **이전**이면 GET 이 아직 예전 레코드를 돌려주는
것이다. 우리 서버 시계와 비교하지 않으므로 시계 차이에 영향받지 않는다.
날짜가 없어 판정할 수 없으면 카페24 값을 그대로 둔다.
두 updated_date 가 **같을** 때: 카페24는 진열/판매만 바꾼 PUT 에서 updated_date 를
올리지 않을 수 있다. 그러면 지연된 GET 도 같은 시각을 돌려주므로 "같다 = 따라잡음"
으로 보면 예전 진열/판매가 그대로 보인다(실제 발생 — 바꿔도 반영 안 된 것처럼 보임).
같은 시각인데 값이 다르면 카페24 기준으로 그 뒤 수정된 근거가 없으므로 지연으로 본다.
GET 이 **이후** 시각이면 관리자 등에서 다시 고친 것 — 카페24 값을 믿는다.
반환: (병합된 상품 dict, 지연 여부)
"""
if not snapshot:
@@ -648,7 +654,9 @@ def overlay_recent_write(
return fetched, False
fetched_at = _as_aware(fetched.get("updated_date"))
snap_at = _as_aware(snapshot.get("updated_date"))
if fetched_at is None or snap_at is None or fetched_at >= snap_at:
if fetched_at is None or snap_at is None or fetched_at > snap_at:
return fetched, False
if fetched_at == snap_at and not _snapshot_differs(fetched, snapshot):
return fetched, False
merged = dict(fetched)
for key in SNAPSHOT_FIELDS:
@@ -658,6 +666,50 @@ def overlay_recent_write(
return merged, True
def _snapshot_differs(fetched: dict, snapshot: dict) -> bool:
"""GET 에 있는 스냅샷 필드 중 값이 다른 것이 있는가(문자열로 비교 — 둘 다 카페24 원본 모양)."""
for key in SNAPSHOT_FIELDS:
if key == "updated_date" or key not in snapshot or key not in fetched:
continue
if fetched[key] is None:
continue
if str(fetched[key]) != str(snapshot[key]):
return True
return False
def overlay_product_rows(
rows: list[dict],
snapshots: dict,
*,
grace_minutes: int,
now: datetime | None = None,
) -> list[dict]:
"""목록(GET /admin/products) 행마다 최근 쓰기 스냅샷을 덮어씌운다.
snapshots: {product_no: {"data": 스냅샷, "written_at": ISO}} — 스냅샷 product 섹션.
목록 API 도 단건 GET 과 똑같이 읽기 지연이 있다. 보정하지 않으면 진열/판매를 바꾼
뒤 목록을 다시 불러올 때 예전 상태로 보이고(필터에 걸려 사라지기도 한다), 그 값이
캐시(cafe24_products)에도 다시 저장된다.
"""
if not snapshots:
return rows
out: list[dict] = []
for row in rows:
try:
no = int(row.get("product_no") or 0)
except (TypeError, ValueError):
no = 0
section = snapshots.get(no) if no else None
if isinstance(section, dict) and section.get("data"):
row, _ = overlay_recent_write(
row, snapshot=section.get("data"), written_at=section.get("written_at"),
grace_minutes=grace_minutes, now=now,
)
out.append(row)
return out
# ── 품목 스냅샷: 코드별 · 필드별 병합 ──
# 스냅샷 모양: {variant_code: {필드: 값, ..., "_at": ISO, "_deleted": bool,
# "options": [{name,value}...], "_options_before": [...]}}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
{% endblock %}
{% block content %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20260918e" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
{% endblock %}
{% block content %}
@@ -125,7 +125,7 @@
{% endblock %}
{% block scripts %}
<script src="/static/cafe24-options.js?v=20260928c"></script>
<script src="/static/cafe24-options.js?v=20261020a"></script>
<script>
(function () {
var pane = document.getElementById("cf24-editor-pane");
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
{% endblock %}
{% block content %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20260819c" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
{% endblock %}
{% block content %}
+14
View File
@@ -193,6 +193,9 @@ class MemoryStore:
def get_write_snapshot(self, product_no):
return dict(self.snapshots.get(int(product_no), {}))
def get_recent_product_snapshots(self, grace_minutes):
return {no: dict(snap["product"]) for no, snap in self.snapshots.items() if snap.get("product")}
# ── 예약 ──
def add_schedule(self, **fields):
sid = next(self._ids)
@@ -475,10 +478,20 @@ class FakeFTP:
raise ftplib.error_perm("550 No such file")
callback(self.files[path])
# 카페24 디자인 FTP 는 허용 확장자만 받는다(실물: `x.js.cf24tmp-…` STOR → 550).
ALLOWED_EXT = (".js", ".html", ".htm", ".css", ".json", ".txt", ".xml",
".jpg", ".jpeg", ".gif", ".png", ".svg", ".webp")
@classmethod
def _check_ext(cls, path):
if not path.lower().endswith(cls.ALLOWED_EXT):
raise ftplib.error_perm(f"550 {path}: Operation not permitted")
def storbinary(self, cmd, fp):
path = cmd.split(" ", 1)[1]
data = fp.read()
FakeFTP.log.append(("STOR", path))
self._check_ext(path)
self.files[path] = data[: len(data) // 2] if FakeFTP.truncate_store else data
def rename(self, src, dst):
@@ -490,6 +503,7 @@ class FakeFTP:
raise ftplib.error_perm("502 RNFR not implemented")
if src not in self.files:
raise ftplib.error_perm("550 No such file")
self._check_ext(dst)
if dst in self.files and FakeFTP.rename_mode == "no_overwrite":
raise ftplib.error_perm("553 File exists")
self.files[dst] = self.files.pop(src)
+86 -3
View File
@@ -25,8 +25,25 @@ SECRET = "unit-test-secret"
# wait_for_description 은 실물 카페24 API 의 쓰기 직후 읽기 지연을 흡수하려고
# 실제로 sleep 한다. 가짜 클라이언트는 그 지연을 재현하지 않으므로(항상 같은
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
# 기다릴 필요는 없다.
products.time.sleep = lambda *_a, **_k: None
# 기다릴 필요는 없다. products.time 은 공유 time 모듈이라 import 때 바꾸면 다른 테스트의
# time.sleep 까지 바뀐다 — 이 파일 테스트 동안만 바꾼다(pytest fixture / 직접 실행은 _run_all, 검토 F10).
_NO_SLEEP = lambda *_a, **_k: None # noqa: E731
try:
import pytest
except ImportError: # 직접 실행은 pytest 없이도 돈다
pytest = None
if pytest is not None:
@pytest.fixture(autouse=True, scope="module")
def _no_sleep_in_this_file():
prev = products.time.sleep
products.time.sleep = _NO_SLEEP
try:
yield
finally:
products.time.sleep = prev
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
@@ -729,7 +746,7 @@ def test_design_ftp_read_and_write_roundtrip():
assert design_ftp.read_text_file(_FTP_CFG, _SWIPER) == "new content"
# 원본에 직접 STOR 하지 않는다 — 임시 파일에 올린 뒤 이름 바꾸기로 교체
stors = [e for e in ftp.log if e[0] == "STOR"]
assert stors and all(".cf24tmp-" in e[1] for e in stors), ftp.log
assert stors and all("_cf24tmp_" in e[1] and e[1].endswith(".js") for e in stors), ftp.log
assert any(e[0] == "RENAME" and e[2] == _SWIPER for e in ftp.log)
# 임시 파일이 남지 않는다
assert set(ftp.files) == {_SWIPER}
@@ -1110,6 +1127,71 @@ def test_product_snapshot_keeps_only_scalar_fields():
assert snap == {"product_name": "A", "price": "1.00", "display": "T"}
def test_overlay_same_updated_date_but_different_flags_is_lag():
# 카페24는 진열/판매만 바꾼 PUT 에서 updated_date 를 안 올릴 수 있다 — 같은 시각에 값이
# 다르면 지연이다(예전엔 "같다 = 따라잡음"으로 봐서 바꾼 진열/판매가 되돌아 보였다).
fetched = {"display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"}
snap = {"display": "F", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"}
merged, stale = store.overlay_recent_write(fetched, snapshot=snap, written_at=now_kst(), grace_minutes=60)
assert stale is True and merged["display"] == "F"
def test_overlay_same_updated_date_and_same_values_is_caught_up():
fetched = {"display": "F", "price": "1.00", "updated_date": "2026-09-18T10:00:00+09:00"}
snap = {"display": "F", "price": "1.00", "updated_date": "2026-09-18T10:00:00+09:00"}
merged, stale = store.overlay_recent_write(fetched, snapshot=snap, written_at=now_kst(), grace_minutes=60)
assert stale is False and merged is fetched
def test_overlay_product_rows_fixes_lagging_list():
rows = [
{"product_no": 1, "display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"},
{"product_no": 2, "display": "T", "selling": "T", "updated_date": "2026-09-18T10:00:00+09:00"},
]
snaps = {1: {"data": {"display": "T", "selling": "F", "updated_date": "2026-09-18T10:00:00+09:00"},
"written_at": now_kst().isoformat()}}
out = store.overlay_product_rows(rows, snaps, grace_minutes=60)
assert out[0]["selling"] == "F"
assert out[1] is rows[1]
assert store.overlay_product_rows(rows, {}, grace_minutes=60) is rows
def test_status_toggle_survives_read_lag_without_updated_date_bump():
"""진열/판매 배지 → PUT → 다시 열어도(단건·목록) 바꾼 값이 보인다.
실물 재현 조건: PUT 이 updated_date 를 올리지 않고, GET 은 한동안 예전 값을 준다.
"""
from app.modules.cafe24 import routes_products
st = fakes.MemoryStore()
cafe = fakes.FakeCafe24()
api = fakes.FakeApi(cafe)
cafe._tick = lambda: None # 진열/판매만 바꾸면 updated_date 그대로
cafe.stale = dict(cafe.state) # GET 은 바꾸기 전 값(읽기 지연)
orig = (routes_products.require_store, routes_products.build_cafe24_api)
routes_products.require_store = lambda request: (st, {"email": "a@b.c"})
routes_products.build_cafe24_api = lambda _st: api
try:
res = routes_products.product_status(None, 131, {"field": "selling", "value": False})
assert res == {"ok": True, "display": True, "selling": False}
assert cafe.state["selling"] == "F"
assert cafe.puts()[-1][2]["request"] == {"selling": "F"}
product, stale = routes_products.load_product(st, api, 131)
assert stale is True and products.normalize_product(product)["selling"] is False
rows = store.overlay_product_rows(
[dict(cafe.stale)], st.get_recent_product_snapshots(60), grace_minutes=60
)
assert products.normalize_product(rows[0])["selling"] is False
# 다시 켜기 — 값은 요청한 결과값 그대로(뒤집기 아님)
res = routes_products.product_status(None, 131, {"field": "selling", "value": True})
assert res["selling"] is True and cafe.state["selling"] == "T"
finally:
routes_products.require_store, routes_products.build_cafe24_api = orig
# ════════════════════════════════════════════════════════════
# 기본 정보 · 옵션 · 품목 입력 검증
# ════════════════════════════════════════════════════════════
@@ -1725,6 +1807,7 @@ def test_client_maybe_applied_classification():
def _run_all():
products.time.sleep = _NO_SLEEP # 직접 실행 = 이 프로세스는 이 파일 테스트만
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
for fn in fns:
fn()
+3
View File
@@ -232,6 +232,9 @@ def resolve_effective(
# ════════════════════════════════════════════════════════════
def remember_product_write(st: Any, product_no: int, updated: dict[str, Any]) -> tuple[dict[str, Any], str]:
"""PUT 응답(상품 dict)을 캐시·스냅샷에 남긴다. (정규화된 상품 행, 기록 오류 문자열)."""
if updated and not updated.get("product_no"):
# 응답에 상품번호가 빠져도 기록은 남긴다 — 안 남기면 지연 보정이 안 돼 예전 값이 보인다.
updated = {**updated, "product_no": int(product_no)}
info = products.normalize_product(updated) if updated else {}
if not info.get("product_no"):
return info, ""
+47
View File
@@ -0,0 +1,47 @@
# [쿠팡] 쿠팡 밀크런 모듈 — `app/modules/cupang/`, `cupang_db`
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 이 파일이 기준.
> 정적 파일: `app/static/cupang.css`, `app/static/cupang.js`. 템플릿: `templates/`.
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`).
## 출고 달력 / 상자 계산
- 출고 달력·상자 계산이 중심.
- 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다. 신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트.
- 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택.
- 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일 = 출고일 + 1일).
- 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷(혼합 상자 내용물·상자 종류 표시용).
- 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD).
- 양식 생성은 `export.py` 한 곳에서 만들어 xlsx·구글시트가 공유.
- 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기.
## 구글 시트 동기화
- `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시
확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip).
- 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제
(문서에 시트가 하나뿐이면 내용만 비움).
## 제품 포장무게
- 설정(제품명)에서 제품별 포장무게(g, `cupang_products.weight_g`, 마이그레이션 007 + 시드) 입력·표시·정렬.
- 출고 상세 상자 목록에 상자별 무게 합계(수량 × 지금 포장무게, `router._attach_box_weights`).
- 무게 없는 제품은 "일부 미입력".
- 화면은 kg 소수 첫째 자리 사사오입(`router._g_to_kg`) + 맨 아래 수량·무게 합계 행(앞 3열 병합).
- 표 칸 모두 가운데 정렬, 요약 카드와 20px 간격.
- 상자 목록 엑셀에도 무게(g) 열.
## 쿠팡 발주 엑셀 업로드
- 다중 업로드(`POST /cupang/api/box-calc/upload`, openpyxl).
- F13 입고예정일의 하루 전 = 출고일.
- 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 → 센터별 합산
→ 센터 단위로 상자 계산·자동 배분.
## 쿠팡 로켓 매출 (`/cupang/sales`)
- 테이블 `cupang_sales`·`cupang_sales_weekly`. 발주 라인별 공급가·원가·물류비·마진 표.
- 기간/센터/유형/검색 조회, 행 CRUD, 엑셀 다운로드.
- 구글 시트 양식 xlsx·csv 업로드(`sales_import.py`) — 같은 발주번호+SKU+출고일+센터+수량은 덮어씀.
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
+34 -7
View File
@@ -36,10 +36,23 @@ class CupangDBStore:
open=False,
)
self._pool.open(wait=False)
self._weight_col: bool | None = None # 마이그레이션 007(weight_g) 적용 여부 — 한 번 확인되면 기억
def close(self) -> None:
self._pool.close()
def weight_enabled(self) -> bool:
"""cupang_products.weight_g(포장무게, 마이그레이션 007) 가 있는가. 있으면 기억(없으면 다음에 다시 확인)."""
if self._weight_col:
return True
with self._pool.connection() as conn:
row = conn.execute(
"SELECT 1 FROM information_schema.columns "
"WHERE table_name = 'cupang_products' AND column_name = 'weight_g'"
).fetchone()
self._weight_col = row is not None
return self._weight_col
# ════════════════════════════════════════════════════════════
# 입고센터 (cupang_centers)
# ════════════════════════════════════════════════════════════
@@ -300,32 +313,39 @@ class CupangDBStore:
product_name: str,
coupang_item_code: str | None = None,
sort_order: int = 0,
weight_g: int | None = None,
) -> dict[str, Any]:
"""제품 등록/수정.
coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기).
weight_g(포장무게 g) 가 None 이면 기존 값을 유지한다(수기 추가에서 비워 두면 그대로). 007 미적용이면 무시.
"""
code = (product_code or "").strip()
name = (product_name or "").strip()
cic = None if coupang_item_code is None else coupang_item_code.strip()
if not code or not name:
raise ValueError("제품코드와 제품명 모두 필요합니다.")
weight = self.weight_enabled()
with self._pool.connection() as conn:
row = conn.execute(
"""
INSERT INTO cupang_products
(product_code, product_name, coupang_item_code, sort_order)
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s)
(product_code, product_name, coupang_item_code, sort_order"""
+ (", weight_g" if weight else "") + """)
VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s"""
+ (", %(w)s" if weight else "") + """)
ON CONFLICT (product_code) DO UPDATE
SET product_name = EXCLUDED.product_name,
coupang_item_code = COALESCE(
%(cic)s, cupang_products.coupang_item_code
),
),"""
+ ("\n weight_g = COALESCE(%(w)s, cupang_products.weight_g)," if weight else "")
+ """
sort_order = EXCLUDED.sort_order,
active = TRUE
RETURNING *
""",
{"code": code, "name": name, "cic": cic, "sort": sort_order},
{"code": code, "name": name, "cic": cic, "sort": sort_order, "w": weight_g},
).fetchone()
return self._product_serialize(row)
@@ -345,8 +365,11 @@ class CupangDBStore:
product_name: str,
product_code: str,
coupang_item_code: str = "",
weight_g: Any = ...,
) -> dict[str, Any]:
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드).
"""등록된 제품 수정(제품명/제품코드/쿠팡상품코드/포장무게).
weight_g: 정수 g 또는 None(지움). 넘기지 않으면(...) 그대로 — 007 미적용이면 무시.
제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의
product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지).
@@ -356,6 +379,7 @@ class CupangDBStore:
cic = (coupang_item_code or "").strip()
if not name or not code:
raise ValueError("제품코드와 제품명 모두 필요합니다.")
set_weight = weight_g is not ... and self.weight_enabled() # 트랜잭션 밖에서 확인(연결을 겹쳐 잡지 않게)
with self._pool.connection() as conn:
with conn.transaction():
old = conn.execute(
@@ -378,11 +402,12 @@ class CupangDBStore:
UPDATE cupang_products
SET product_name = %s,
product_code = %s,
coupang_item_code = %s
coupang_item_code = %s"""
+ (", weight_g = %s" if set_weight else "") + """
WHERE id = %s
RETURNING *
""",
(name, code, cic, product_id),
(name, code, cic) + ((weight_g,) if set_weight else ()) + (product_id,),
).fetchone()
if code != old_code:
# 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지).
@@ -1081,6 +1106,8 @@ class CupangDBStore:
out["active"] = bool(out.get("active", True))
out["sort_order"] = int(out.get("sort_order", 0))
out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip()
w = out.get("weight_g") # 007 미적용이면 키 없음 → None
out["weight_g"] = int(w) if w is not None else None
for k in ("created_at", "updated_at"):
v = out.get(k)
if isinstance(v, datetime):
+23 -7
View File
@@ -193,10 +193,17 @@ def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
# ── 상자 목록(상자 번호별 내용물) ──────────────────────────────
BOX_HEADERS = ["상자번호", "제품명", "제품코드", "수량"]
BOX_WIDTHS_PX = {1: 70, 2: 240, 3: 110, 4: 70}
BOX_WEIGHT_HEADER = "무게(g)" # with_weight 일 때 5열 — 상자 무게 합계(상자번호처럼 상자 단위로 세로 병합)
BOX_WEIGHT_WIDTH_PX = 80
def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, Any]]) -> Any:
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일)."""
def build_box_list_workbook(
shipment: dict[str, Any], box_list: list[dict[str, Any]], *, with_weight: bool = False
) -> Any:
"""상자 번호 · 제품명 · 제품코드 · 수량 한 줄씩. 시트명 = YYYYMMDD(요일).
with_weight 면 5열 "무게(g)" — 상자마다 box["weight_g"](라우터 _attach_box_weights), 모르면 빈칸."""
headers = BOX_HEADERS + ([BOX_WEIGHT_HEADER] if with_weight else [])
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter
@@ -215,10 +222,10 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
ws.cell(row=1, column=1, value=f"{with_dow(ship_date)} {center} 상자 목록")
ws.cell(row=1, column=1).font = Font(size=14, bold=True)
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(BOX_HEADERS))
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(headers))
header_fill = PatternFill("solid", fgColor=HEADER_BG)
for idx, name in enumerate(BOX_HEADERS, start=1):
for idx, name in enumerate(headers, start=1):
cell = ws.cell(row=2, column=idx, value=name)
cell.font = Font(bold=True)
cell.alignment = center_align
@@ -235,18 +242,27 @@ def build_box_list_workbook(shipment: dict[str, Any], box_list: list[dict[str, A
ws.cell(row=row, column=3, value=it.get("product_code") or "")
ws.cell(row=row, column=4, value=int(it.get("quantity") or 0))
row += 1
# 한 상자에 여러 제품이면 상자번호 칸을 세로로 합친다.
if with_weight and contents:
w = entry.get("weight_g")
ws.cell(row=first, column=5, value=(int(w) if w is not None else None))
ws.cell(row=first, column=5).number_format = "#,##0"
# 한 상자에 여러 제품이면 상자번호(·무게) 칸을 세로로 합친다.
if row - first > 1:
ws.merge_cells(start_row=first, start_column=1, end_row=row - 1, end_column=1)
if with_weight:
ws.merge_cells(start_row=first, start_column=5, end_row=row - 1, end_column=5)
last = row - 1
for r in range(3, last + 1):
for col in range(1, len(BOX_HEADERS) + 1):
for col in range(1, len(headers) + 1):
cell = ws.cell(row=r, column=col)
cell.border = box
cell.alignment = left_align if col == 2 else center_align
for col, px in BOX_WIDTHS_PX.items():
widths = dict(BOX_WIDTHS_PX)
if with_weight:
widths[5] = BOX_WEIGHT_WIDTH_PX
for col, px in widths.items():
ws.column_dimensions[get_column_letter(col)].width = round(px / PX_PER_CHAR, 2)
ws.row_dimensions[1].height = 24
+70 -6
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import calendar as _calendar
import json
from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction
from typing import Any
@@ -22,7 +23,7 @@ from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from .holidays import holiday_name, is_holiday
from .store import SHIP_METHODS
from .store import SHIP_METHODS, parse_weight_g
router = APIRouter(prefix="/cupang", tags=["cupang"])
@@ -411,6 +412,19 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
]
calc = _compute_boxes(store, items)
total_qty = sum(it["quantity"] for it in items)
box_list = _expand_box_list(ship, calc, items)
box_weight = _attach_box_weights(store, box_list)
# 상자 목록 합계 행 — 수량 합계와 무게 합계(kg, 소수 첫째 자리)
box_qty_total = sum(int(it.get("quantity") or 0) for b in box_list for it in (b.get("items") or []))
box_weight_total = None
box_weight_partial = False
if box_weight:
for b in box_list:
b["weight_kg"] = _g_to_kg(b.get("weight_g"))
if b.get("weight_g") is not None:
box_weight_total = (box_weight_total or 0) + int(b["weight_g"])
if b.get("weight_missing"):
box_weight_partial = True
return render_template(
request,
@@ -424,7 +438,12 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
"shipment": ship,
"items": items,
"calc": calc,
"box_list": _expand_box_list(ship, calc, items),
"box_list": box_list,
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
"box_weight": box_weight,
"box_qty_total": box_qty_total,
"box_weight_total_kg": _g_to_kg(box_weight_total),
"box_weight_partial": box_weight_partial,
"total_qty": total_qty,
},
)
@@ -432,7 +451,7 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
@router.get("/{shipment_id:int}/boxes.xlsx")
def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
"""상자 목록(상자번호·제품명·제품코드·수량) 엑셀 다운로드."""
"""상자 목록(상자번호·제품명·제품코드·수량·무게) 엑셀 다운로드."""
from io import BytesIO # noqa: WPS433
from fastapi.responses import StreamingResponse # noqa: WPS433
@@ -457,8 +476,9 @@ def export_box_list_xlsx(request: Request, shipment_id: int) -> Any:
for ln in (ship.get("lines") or [])
]
box_list = _expand_box_list(ship, _compute_boxes(store, items), items)
with_weight = _attach_box_weights(store, box_list)
wb = build_box_list_workbook(ship, box_list)
wb = build_box_list_workbook(ship, box_list, with_weight=with_weight)
buf = BytesIO()
wb.save(buf)
buf.seek(0)
@@ -1185,6 +1205,44 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
}
def _g_to_kg(grams: Any) -> str | None:
"""g → kg 표시 글자 — 소수 둘째 자리에서 반올림(사사오입)해 첫째 자리까지. 예: 1,250g → "1.3"."""
if grams is None:
return None
kg = (Decimal(int(grams)) / 1000).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
return f"{kg:,.1f}"
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
상자에 넣는 값: weight_g = 아는 무게의 합(상자 안 제품 무게가 하나도 없으면 None),
weight_missing = 무게가 없는 제품코드 목록(일부만 없으면 합계는 그 제품을 뺀 값).
포장무게 칸(마이그레이션 007)이 없으면 아무것도 넣지 않고 False.
"""
if not store.weight_enabled():
return False
weights = {
str(p.get("product_code") or "").strip(): p.get("weight_g")
for p in store.list_products(include_inactive=True)
}
for box in box_list:
contents = box.get("items") or []
total, missing = 0, []
for it in contents:
code = str(it.get("product_code") or "").strip()
w = weights.get(code)
if w is None:
if code not in missing:
missing.append(code)
continue
total += int(w) * int(it.get("quantity") or 0)
known = any(weights.get(str(it.get("product_code") or "").strip()) is not None for it in contents)
box["weight_g"] = total if known else None
box["weight_missing"] = missing
return True
def _expand_box_list(
shipment: dict[str, Any], calc: dict[str, Any], items: list[dict[str, Any]]
) -> list[dict[str, Any]]:
@@ -1349,6 +1407,8 @@ def products_page(request: Request) -> HTMLResponse:
"page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.",
"products": store.list_products(include_inactive=True),
"registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)],
# 포장무게(g) — 마이그레이션 007 적용 전이면 무게 칸을 숨긴다
"weight_enabled": store.weight_enabled(),
"search_enabled": bool(reader and reader.enabled),
"search_reason": (reader.reason if reader else ""),
},
@@ -1412,6 +1472,7 @@ def product_upsert(
product_code: str = Form(...),
product_name: str = Form(...),
coupang_item_code: str = Form(""),
weight_g: str = Form(""),
sort_order: int = Form(0),
user: dict[str, Any] = Depends(_require_user),
) -> RedirectResponse:
@@ -1422,9 +1483,10 @@ def product_upsert(
store.upsert_product(
product_code=product_code,
product_name=product_name,
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드를 유지한다.
# 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드·포장무게를 유지한다.
coupang_item_code=(coupang_item_code.strip() or None),
sort_order=sort_order,
weight_g=parse_weight_g(weight_g),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@@ -1457,7 +1519,8 @@ def product_edit(
payload: dict[str, Any] = Body(...),
user: dict[str, Any] = Depends(_require_user),
) -> JSONResponse:
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code}."""
"""등록된 제품 수정. body: {product_name, product_code, coupang_item_code, weight_g?}.
weight_g 키가 있으면 저장(빈 값 = 지움), 없으면 무게는 그대로."""
store = _store(request)
if store is None:
raise HTTPException(status_code=503, detail="cupang_db 미설정")
@@ -1467,6 +1530,7 @@ def product_edit(
product_name=str(payload.get("product_name") or ""),
product_code=str(payload.get("product_code") or ""),
coupang_item_code=str(payload.get("coupang_item_code") or ""),
weight_g=(parse_weight_g(payload.get("weight_g")) if "weight_g" in payload else ...),
)
except KeyError:
raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.")
+29
View File
@@ -94,3 +94,32 @@ def compute_boxes(quantity: int, units_per_box: int | None) -> dict[str, Any]:
"remainder_units": qty % upb,
"required_boxes": math.ceil(qty / upb),
}
# 제품 포장무게(g) — cupang_products.weight_g (마이그레이션 007). 0 ~ 1,000,000g, 정수.
WEIGHT_MAX_G = 1_000_000
def parse_weight_g(value: Any) -> int | None:
"""포장무게 입력 → 그램 정수. 빈 값은 None(미입력).
"1,070" · " 1,070 " · "1070g" · "1070.0" 처럼 쉼표·공백·g 단위가 붙어도 읽는다.
숫자가 아니거나 음수·소수(0.5g 등)·범위 밖이면 ValueError.
"""
if value is None:
return None
s = str(value).strip().replace(",", "").replace(" ", "")
if s.lower().endswith("g"):
s = s[:-1]
if not s:
return None
try:
f = float(s)
except ValueError:
raise ValueError(f"포장무게는 숫자(g)로 입력하세요: {value}")
if f != f or f < 0 or f != int(f):
raise ValueError(f"포장무게는 0 이상의 정수(g)로 입력하세요: {value}")
v = int(f)
if v > WEIGHT_MAX_G:
raise ValueError(f"포장무게가 너무 큽니다(최대 {WEIGHT_MAX_G:,}g): {value}")
return v
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
<section class="cpg">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
<section class="cpg">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
<section class="cpg">
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
<section class="cpg">
@@ -34,6 +34,12 @@
<input class="erp-input" type="text" name="product_code" required placeholder="예: MS-1012" /></label>
<label class="erp-field"><span>쿠팡상품코드</span>
<input class="erp-input" type="text" name="coupang_item_code" placeholder="예: 1234567890" /></label>
{% if weight_enabled %}
{# 포장무게(g) — 쉼표·g 붙여도 됨(1,070). 비워 두면 같은 제품코드의 기존 무게 유지 #}
<label class="erp-field cpg-weight-field"><span>포장무게(g)</span>
<input class="erp-input" type="text" name="weight_g" inputmode="numeric" autocomplete="off"
pattern="\s*[0-9][0-9,]*\s*(g|G)?\s*" title="숫자(g)로 입력하세요. 예: 1,070" placeholder="예: 1,070" /></label>
{% endif %}
<button type="submit" class="erp-btn erp-btn-primary">추가</button>
</div>
</form>
@@ -60,6 +66,7 @@
<th><button type="button" class="cpg-sort" data-sort-key="name">제품명<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
<th><button type="button" class="cpg-sort" data-sort-key="code">제품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
<th><button type="button" class="cpg-sort" data-sort-key="cpcode">쿠팡상품코드<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>
{% if weight_enabled %}<th class="cpg-weight-col"><button type="button" class="cpg-sort" data-sort-key="weight">포장무게<span class="cpg-sort-ind" aria-hidden="true"></span></button></th>{% endif %}
<th>상태</th>
<th>동작</th>
</tr>
@@ -68,10 +75,12 @@
{% for p in products %}
<tr data-name="{{ p.product_name }}" data-code="{{ p.product_code }}"
data-cpcode="{{ p.coupang_item_code }}"
data-weight="{{ p.weight_g if p.weight_g is not none else '' }}"
class="cpg-prod-row{% if not p.active %} is-inactive{% endif %}">
<td title="{{ p.product_name }}">{{ p.product_name }}</td>
<td title="{{ p.product_code }}">{{ p.product_code }}</td>
<td class="cpg-cpcode" title="{{ p.coupang_item_code }}">{% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}<span class="erp-muted">—</span>{% endif %}</td>
{% if weight_enabled %}<td class="cpg-weight-col">{% if p.weight_g is not none %}{{ "{:,}".format(p.weight_g) }}<span class="cpg-weight-unit">g</span>{% else %}<span class="erp-muted">—</span>{% endif %}</td>{% endif %}
<td>
<!-- 배지 자체가 토글 버튼: 클릭 → 활성/비활성 전환 -->
<button type="button" class="erp-badge cpg-active-toggle
@@ -92,7 +101,7 @@
</tr>
{% endfor %}
{% if not products %}
<tr class="cpg-no-sort"><td colspan="5" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
<tr class="cpg-no-sort"><td colspan="{{ 6 if weight_enabled else 5 }}" class="erp-muted">등록된 제품명이 없습니다. 왼쪽에서 선택해 등록하세요.</td></tr>
{% endif %}
</tbody>
</table>
@@ -117,6 +126,10 @@
rows.sort(function (a, b) {
var av = a.getAttribute("data-" + state.key) || "";
var bv = b.getAttribute("data-" + state.key) || "";
if (state.key === "weight") { // 포장무게 — 숫자 크기순, 무게 없는 줄은 늘 맨 뒤
if (!av || !bv) return (av ? 0 : 1) - (bv ? 0 : 1);
return (Number(av) - Number(bv)) * state.dir;
}
return collator.compare(av, bv) * state.dir;
});
rows.forEach(function (r) { tbody.appendChild(r); });
@@ -150,6 +163,10 @@
<input class="erp-input" type="text" id="cpg-edit-code" /></label>
<label class="erp-field"><span>쿠팡상품코드</span>
<input class="erp-input" type="text" id="cpg-edit-cpcode" placeholder="비우면 지워집니다" /></label>
{% if weight_enabled %}
<label class="erp-field"><span>포장무게(g)</span>
<input class="erp-input" type="text" id="cpg-edit-weight" inputmode="numeric" autocomplete="off" placeholder="예: 1,070 (비우면 지워집니다)" /></label>
{% endif %}
<p class="erp-muted" id="cpg-edit-msg" style="margin:0;font-size:12px;"></p>
<div class="cpg-dlg-actions erp-page-actions">
<button type="button" class="erp-btn erp-btn-outline" data-edit-close>취소</button>
@@ -167,6 +184,7 @@
var elName = document.getElementById("cpg-edit-name");
var elCode = document.getElementById("cpg-edit-code");
var elCp = document.getElementById("cpg-edit-cpcode");
var elW = document.getElementById("cpg-edit-weight"); // 마이그레이션 007 전이면 없음
var elMsg = document.getElementById("cpg-edit-msg");
var saveBtn = document.getElementById("cpg-edit-save");
var editingId = null;
@@ -181,6 +199,10 @@
elName.value = row.getAttribute("data-name") || "";
elCode.value = row.getAttribute("data-code") || "";
elCp.value = row.getAttribute("data-cpcode") || "";
if (elW) {
var w = row.getAttribute("data-weight") || "";
elW.value = w ? Number(w).toLocaleString("ko-KR") : "";
}
elMsg.textContent = "";
dlg.hidden = false;
elName.focus();
@@ -200,6 +222,12 @@
product_code: (elCode.value || "").trim(),
coupang_item_code: (elCp.value || "").trim()
};
if (elW) {
// 포장무게 — 쉼표·g 는 서버가 읽는다. 숫자가 아니면 여기서 먼저 막는다(빈 값 = 지움)
var wv = (elW.value || "").trim();
if (wv && !/^[0-9][0-9,]*\s*g?$/i.test(wv)) { elMsg.textContent = "포장무게는 숫자(g)로 입력하세요. 예: 1,070"; return; }
body.weight_g = wv;
}
if (!body.product_name || !body.product_code) {
elMsg.textContent = "제품명과 제품코드는 필수입니다."; return;
}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
+32 -4
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20260904f" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block content %}
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
@@ -73,16 +73,17 @@
</div>
</div>
<div class="cpg-sum-scroll">
<div class="cpg-sum-scroll cpg-boxno-scroll">
<table class="erp-table cpg-boxno-table">
<colgroup>
<col class="cpg-boxno-c-no" />
<col class="cpg-boxno-c-name" />
<col class="cpg-boxno-c-code" />
<col class="cpg-boxno-c-qty" />
{% if box_weight %}<col class="cpg-boxno-c-weight" />{% endif %}
</colgroup>
<thead>
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th></tr>
<tr><th>상자번호</th><th>제품명</th><th>제품코드</th><th>수량</th>{% if box_weight %}<th title="상자에 든 제품의 수량 × 포장무게(설정(제품명)) 합계">무게</th>{% endif %}</tr>
</thead>
<tbody>
{% for b in box_list %}
@@ -94,13 +95,40 @@
<td title="{{ it.product_name }}">{{ it.product_name }}</td>
<td class="cpg-boxno-code">{{ it.product_code }}</td>
<td class="cpg-calc-num">{{ it.quantity }}</td>
{% if box_weight and loop.first %}
{# 상자 무게 합계 — 상자번호처럼 상자 단위로 한 칸. 무게 없는 제품이 있으면 표시 #}
{% set miss = b.weight_missing or [] %}
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
{%- if b.weight_g is not none -%}
{{ b.weight_kg }}<span class="cpg-weight-unit">kg</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
</td>
{% endif %}
</tr>
{% endfor %}
{% endfor %}
{% if not box_list %}
<tr><td colspan="4" class="erp-muted">상자 정보가 없습니다.</td></tr>
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
{% endif %}
</tbody>
{% if box_list %}
{# 합계 행 — 수량 합계, 무게 합계(kg). 무게 없는 제품이 있으면 아는 무게만 더한 값 #}
<tfoot>
<tr class="cpg-boxno-total">
<td class="cpg-boxno-cell" colspan="3">합계</td>
<td class="cpg-calc-num">{{ "{:,}".format(box_qty_total) }}</td>
{% if box_weight %}
<td class="cpg-boxno-weight"
{% if box_weight_partial %}title="포장무게 미입력 제품이 있어 아는 무게만 더한 합계 (설정(제품명)에서 입력)"{% endif %}>
{%- if box_weight_total_kg is not none -%}
{{ box_weight_total_kg }}<span class="cpg-weight-unit">kg</span>{% if box_weight_partial %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
</td>
{% endif %}
</tr>
</tfoot>
{% endif %}
</table>
</div>
</div>
+13
View File
@@ -0,0 +1,13 @@
# [배송] 말레이시아 배송 모듈 — `app/modules/dispatch/`, `dispatch_db`
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/DISPATCH_MODULE.md`.
> 정적 파일: `app/static/dispatch/`. 템플릿: `templates/`. 테스트: `tests/`.
- TikTok·Shopee 출고관리. 권한키 `dispatch`.
- 플랫폼별 데이터 엑셀 업로드(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 파싱/생성.
+4
View File
@@ -0,0 +1,4 @@
# [경비] 개인경비 모듈 — `app/modules/expense/`, `expense_db`
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드(`router.py`·`store.py`·`categories.py`)가 기준.
> 템플릿: `templates/`. DB 구성은 필요할 때만 `docs/DATABASES.md` 의 expense_db 절.
+66
View File
@@ -0,0 +1,66 @@
# [입출고] 입출고 관리 모듈 — `app/modules/inout/`, `inout_db`(2026-10-16)
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/INOUT_MODULE.md`.
> 정적 파일: `app/static/inout.css`, `inout.js`. 템플릿: `templates/`.
> 상품은 `itemcode_db.single_items` 읽기 전용(`itemcode.py`). `APP_ENCRYPTION_KEY` 는 실적 모듈과 공유.
> 참고 모델: 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결.
## 발주 / 입고
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
- 미입고 현황(제품별 합계·발주별·지연).
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
- 잔량 종결·취소(취소는 입고 없을 때만).
- 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`).
- 모든 품목 입고완료·초과입고 = "✓ 전체 입고 완료"(초과면 "초과 포함", `order_badge`).
- 발주 삭제는 **수퍼관리자만**(발주 목록 🗑, `perms.super`, 입고·사진·메일 기록까지 CASCADE).
## 권한 / 옵션
- 권한키 `inout`(조회).
- **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션** — 상단 톱니 → 팝업(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`). 관리자는 둘 다.
- 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음.
- **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만.
## 발주 메일 (003)
- 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 보냄.
- **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`).
- 보낸 기록·재발송 확인.
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
## 입고 요청 메일 (005, 2026-10-19)
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
- 받는 사람 = 옵션 → **물류센터** 탭 담당자 이메일(`inout_settings` `logistics_emails`), 참조 기본 = `receipt_mail_cc`(005 가 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 넣음). 창에서 고칠 수 있음.
- 제목 `[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.`(입고일) · 본문 "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + 표(상품 이름·상품 코드·입고 수량·비고 = 발주 품목 줄 메모, 합계) + 메모 + **맨 아래 입고증 사진 = 본문 안 이미지**(CID `multipart/related`, 첨부 아님 — `gmail.build_message(inline_images=)`), 서버가 가로 600px 이하·비율 유지 JPEG 로 줄임(`store.mail_images`, EXIF 회전 반영, HEIC 는 빼고 안내). 미리보기는 cid → data: 로 바꿔 보여 줌.
- 보낸 기록 `inout_receipt_mails`(입고 지우면 CASCADE), 이미 보낸 입고는 `resend` 확인.
## 사방넷 입고 파일 (2026-10-19, 마이그레이션 없음)
- 입고 기록 줄 [사방넷 입고 파일](엑셀 초록 `#217346`) → `GET /inout/orders/{id}/receipts/{rid}/sabangnet.xlsx`(발주·입고 담당). 1행 제목 **A 상품코드 · B 가용수량 · C 불용수량**,
A = 코드표 `single_items.sabangnet_code`(`itemcode.sabangnet_codes`), B = 입고 수량, **C = 수량이 아니라 상품 이름**(사용자 지정). A·C 는 글자 칸(앞자리 0 보존).
- 사방넷 코드가 빈 품목이 있거나 코드표를 못 읽으면 파일을 만들지 않고 발주서로 돌아가 품목을 알려 준다(빈 칸 업로드 방지). 파일 이름 `사방넷_입고_{입고일}_{발주번호}.xlsx`.
## 입고증 사진 (003)
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
## 상품 정보 (004, 옵션 세 번째 탭)
- 테이블 `inout_products`·`inout_products_excluded`.
- [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기).
- 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동).
- 한 번 불러오면 발주서 제품은 이 목록에서. 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`).
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
## 시각 / 날짜
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
+32
View File
@@ -0,0 +1,32 @@
"""입출고 관리(inout) 모듈 — 본사 → 공장 제품 제작 발주, 물류 입고(분할), 발주 대비 미입고·초과 관리.
- 라우터: `router.py` (prefix=/inout)
- 저장소: `db.py` (inout_db / PostgreSQL) + `store.py` (상태·검사, 순수 함수)
- 제품: `itemcode.py` — itemcode_db.single_items(단품) 읽기 전용(ITEMCODE_DB_URL 재사용)
- 템플릿: `templates/inout/`, 화면 스크립트·스타일 `static/inout.{js,css}`
INOUT_DB_URL 미설정이면 build_inout_store 가 None → 라우터가 "설정 필요" 안내(앱은 죽지 않음).
권한: 모듈 권한키 `inout`(조회), 발주 담당·입고 담당은 모듈 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션.
상세 docs/INOUT_MODULE.md.
"""
from typing import Any
from .router import router
__all__ = ["router", "build_inout_store", "build_inout_items"]
def build_inout_store(*, dsn: str | None) -> Any:
if not dsn:
return None
from .db import InoutDBStore # 지연 import
return InoutDBStore(dsn)
def build_inout_items() -> Any:
"""코드표 단품 리더(ITEMCODE_DB_URL). 미설정이면 enabled=False."""
from .itemcode import SingleItemReader # 지연 import
return SingleItemReader()
+669
View File
@@ -0,0 +1,669 @@
"""inout_db PostgreSQL 저장소 — 공장·담당자·발주서·입고.
- 드라이버: psycopg 3 + pool(다른 모듈과 같은 패턴), 연결 `INOUT_DB_URL`. 스키마는 scripts/sql/inout_db_init.sql(앱이 만들지 않음).
- 상태(발주·부분입고·입고완료·초과·종결·취소)는 저장하지 않고 품목별 누적 입고로 계산한다(store.order_status) — 어긋날 일이 없다.
- 쓰기는 한 트랜잭션. 입고 저장은 발주서 행을 잠그고(FOR UPDATE) 그 안에서 누적 입고를 다시 읽어 초과를 판단한다
(두 사람이 동시에 입고해도 초과 확인을 건너뛰지 않게).
"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any
from psycopg.errors import UndefinedColumn, UndefinedTable
from psycopg.rows import dict_row
from psycopg.types.datetime import TimestamptzLoader
from psycopg_pool import ConnectionPool
from app.timezone import KST
from . import store
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
class OverReceipt(Exception):
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
def __init__(self, over: list[dict[str, Any]]) -> None:
super().__init__("초과 입고")
self.over = over
def _norm_email(e: str) -> str:
return (e or "").strip().lower()
class _KstTimestamptzLoader(TimestamptzLoader):
"""TIMESTAMPTZ → 한국 시각(KST) datetime. 화면·메일에 찍는 시각(입력·보낸 시각 등)이 DB 서버 시간대(보통 UTC)와 무관하게."""
def load(self, data: Any) -> datetime:
return super().load(data).astimezone(KST)
def _kst_session(conn: Any) -> None:
# 세션 시간대(SET TIME ZONE)는 쓰지 않는다 — 'Asia/Seoul' 은 시간대 자료가 없는 서버에서 접속이 실패하고,
# 고정 오프셋은 psycopg 가 못 읽어 UTC 로 돌아간다. 읽을 때 파이썬에서 바꾼다.
conn.adapters.register_loader("timestamptz", _KstTimestamptzLoader)
class InoutDBStore:
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
kwargs={"row_factory": dict_row, "autocommit": True}, configure=_kst_session, open=False)
self._pool.open(wait=False)
def close(self) -> None:
self._pool.close()
# ════════════════════════════════════════════════════════════
# 공장
# ════════════════════════════════════════════════════════════
def list_factories(self, *, include_inactive: bool = False) -> list[dict[str, Any]]:
where = "" if include_inactive else "WHERE f.is_active"
with self._pool.connection() as conn:
return conn.execute(
"SELECT f.*, (SELECT count(*) FROM inout_orders o WHERE o.factory_id = f.id) AS order_count "
f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name"
).fetchall()
def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", email: str = "",
memo: str = "", is_active: bool = True, sort_order: int = 0) -> int:
"""공장 추가·수정. 담당자(manager, 002)·연락처(contact)·이메일(email, 003 — 여러 개는 쉼표)."""
name = (name or "").strip()
if not name or len(name) > 100:
raise ValueError("공장 이름을 1~100자로 입력하세요.")
emails = ", ".join(store.parse_emails(email, label="공장 이메일"))
vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], emails, (memo or "").strip()[:store.MEMO_MAX],
bool(is_active), int(sort_order))
try:
with self._pool.connection() as conn:
dup = conn.execute("SELECT id FROM inout_factories WHERE lower(name) = lower(%s) AND id <> %s",
(name, factory_id or 0)).fetchone()
if dup:
raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}")
if factory_id:
row = conn.execute(
"UPDATE inout_factories SET name=%s, manager=%s, contact=%s, email=%s, memo=%s, is_active=%s, sort_order=%s "
"WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone()
if not row:
raise ValueError("공장을 찾을 수 없습니다.")
return int(row["id"])
return int(conn.execute(
"INSERT INTO inout_factories (name, manager, contact, email, memo, is_active, sort_order) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"])
except UndefinedColumn:
raise ValueError("DB 마이그레이션 inout_db 002·003(공장 담당자·이메일 칸)이 아직 적용되지 않았습니다.") from None
def delete_factory(self, factory_id: int) -> None:
"""발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김)."""
with self._pool.connection() as conn:
used = conn.execute("SELECT 1 FROM inout_orders WHERE factory_id=%s LIMIT 1", (factory_id,)).fetchone()
if used:
raise ValueError("발주 기록이 있는 공장은 지울 수 없습니다 — '사용 안 함'으로 바꾸세요.")
conn.execute("DELETE FROM inout_factories WHERE id=%s", (factory_id,))
# ════════════════════════════════════════════════════════════
# 담당자(발주 담당·입고 담당)
# ════════════════════════════════════════════════════════════
def list_roles(self) -> dict[str, list[str]]:
out: dict[str, list[str]] = {r: [] for r in store.ROLES}
with self._pool.connection() as conn:
for r in conn.execute("SELECT email, role FROM inout_roles ORDER BY email").fetchall():
out.setdefault(r["role"], []).append(r["email"])
return out
def roles_of(self, email: str) -> set[str]:
with self._pool.connection() as conn:
rows = conn.execute("SELECT role FROM inout_roles WHERE email=%s", (_norm_email(email),)).fetchall()
return {r["role"] for r in rows}
def set_role_members(self, role: str, emails: list[str], *, by: str) -> None:
"""그 역할 담당자를 통째로 바꾼다(한 트랜잭션)."""
if role not in store.ROLES:
raise ValueError("알 수 없는 담당 종류입니다.")
clean = sorted({_norm_email(e) for e in emails if _norm_email(e)})
with self._pool.connection() as conn, conn.transaction():
conn.execute("DELETE FROM inout_roles WHERE role=%s AND NOT (email = ANY(%s))", (role, clean))
for e in clean:
conn.execute("INSERT INTO inout_roles (email, role, created_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
(e, role, _norm_email(by)))
# ════════════════════════════════════════════════════════════
# 발주서
# ════════════════════════════════════════════════════════════
def _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str],
specs: dict[str, dict[str, Any]]) -> None:
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다."""
if self.products_ready():
sp = specs.get(ln["item_code"]) or {}
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct")))
else:
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) VALUES (%s,%s,%s,%s,%s,%s)",
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"]))
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str,
specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}."""
with self._pool.connection() as conn, conn.transaction():
self._require_factory(conn, data["factory_id"])
conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))")
prefix = store.order_no(data["order_date"], 0)[:-2]
# 순번은 숫자로 비교 — 글자 max 면 "-99" 가 "-100" 보다 커서 100번째부터 같은 번호가 나온다
row = conn.execute("SELECT max(substr(order_no, %s)::int) AS m FROM inout_orders "
"WHERE order_no LIKE %s AND substr(order_no, %s) ~ '^[0-9]{1,9}$'",
(len(prefix) + 1, prefix + "%", len(prefix) + 1)).fetchone()
seq = (row["m"] or 0) + 1 if row else 1
no = store.order_no(data["order_date"], seq)
oid = conn.execute(
"INSERT INTO inout_orders (order_no, factory_id, order_date, due_date, memo, created_by, updated_by) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
(no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)),
).fetchone()["id"]
for i, ln in enumerate(data["lines"], start=1):
self._insert_line(conn, oid, i, ln, names, specs or {})
return {"id": int(oid), "order_no": no}
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str,
specs: dict[str, dict[str, Any]] | None = None) -> None:
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서는 고칠 수 없습니다.")
self._require_factory(conn, data["factory_id"], allow_inactive_id=head["factory_id"])
existing = {r["item_code"]: r for r in conn.execute(
"SELECT l.id, l.item_code, COALESCE(sum(rl.qty), 0) AS received FROM inout_order_lines l "
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s GROUP BY l.id",
(order_id,)).fetchall()}
wanted = {ln["item_code"] for ln in data["lines"]}
blocked = [c for c, r in existing.items() if c not in wanted and int(r["received"]) > 0]
if blocked:
raise ValueError("입고 기록이 있는 품목은 뺄 수 없습니다: " + ", ".join(sorted(blocked)))
for code, r in existing.items():
if code not in wanted:
conn.execute("DELETE FROM inout_order_lines WHERE id=%s", (r["id"],))
for i, ln in enumerate(data["lines"], start=1):
if ln["item_code"] in existing:
conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s",
(i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
else:
self._insert_line(conn, order_id, i, ln, names, specs or {})
conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s",
(data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id))
def set_closed(self, order_id: int, *, closed: bool, reason: str = "", by: str) -> None:
"""종결(남은 미입고를 더 기다리지 않음) / 종결 풀기."""
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서입니다.")
if closed:
conn.execute("UPDATE inout_orders SET closed_at=now(), closed_by=%s, close_reason=%s, updated_by=%s WHERE id=%s",
(_norm_email(by), (reason or "").strip()[:store.MEMO_MAX], _norm_email(by), order_id))
else:
conn.execute("UPDATE inout_orders SET closed_at=NULL, closed_by='', close_reason='', updated_by=%s WHERE id=%s",
(_norm_email(by), order_id))
def cancel_order(self, order_id: int, *, by: str) -> None:
"""잘못 넣은 발주 — 입고 기록이 없을 때만 취소(기록은 남김)."""
with self._pool.connection() as conn, conn.transaction():
self._lock_order(conn, order_id)
if conn.execute("SELECT 1 FROM inout_receipts WHERE order_id=%s LIMIT 1", (order_id,)).fetchone():
raise ValueError("입고 기록이 있는 발주서는 취소할 수 없습니다 — 남은 수량은 '종결'하세요.")
conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s",
(_norm_email(by), _norm_email(by), order_id))
def delete_order(self, order_id: int) -> dict[str, Any]:
"""발주서 완전 삭제(수퍼관리자) — 품목·입고 기록·입고증 사진·메일 기록까지 함께(CASCADE). 되돌릴 수 없다.
반환 {order_no, receipts} — 화면 안내·로그용."""
with self._pool.connection() as conn, conn.transaction():
self._lock_order(conn, order_id)
n = conn.execute("SELECT count(*) AS n FROM inout_receipts WHERE order_id=%s", (order_id,)).fetchone()["n"]
row = conn.execute("DELETE FROM inout_orders WHERE id=%s RETURNING order_no", (order_id,)).fetchone()
return {"order_no": row["order_no"], "receipts": int(n)}
def get_order(self, order_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
head = conn.execute(
# 담당자(manager)는 002 열 — 미적용 DB 에서도 깨지지 않게 to_jsonb 로 읽는다
"SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact, "
"COALESCE(to_jsonb(f) ->> 'email', '') AS factory_email "
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s",
(order_id,)).fetchone()
if not head:
return None
lines = conn.execute(
"SELECT l.*, COALESCE(sum(rl.qty), 0)::int AS received FROM inout_order_lines l "
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s "
"GROUP BY l.id ORDER BY l.line_no", (order_id,)).fetchall()
receipts = conn.execute("SELECT * FROM inout_receipts WHERE order_id=%s ORDER BY receipt_date, id",
(order_id,)).fetchall()
rlines = conn.execute(
"SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl "
"JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id "
"WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall()
# 입고증 사진(목록만 — 내용은 /inout/photos/{id})·발주 메일 기록 — 003 미적용이면 빈 목록
try:
photos = conn.execute(
"SELECT p.id, p.receipt_id, p.filename, p.content_type, p.size_bytes FROM inout_receipt_photos p "
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE r.order_id=%s ORDER BY p.id", (order_id,)).fetchall()
mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall()
except UndefinedTable:
photos, mails = [], []
# 입고 요청 메일 기록(005) — 미적용이면 빈 목록
try:
rmails = conn.execute(
"SELECT m.* FROM inout_receipt_mails m JOIN inout_receipts r ON r.id = m.receipt_id "
"WHERE r.order_id=%s ORDER BY m.sent_at, m.id", (order_id,)).fetchall()
except UndefinedTable:
rmails = []
by_rmail: dict[int, list[dict[str, Any]]] = {}
for m in rmails:
by_rmail.setdefault(int(m["receipt_id"]), []).append(m)
by_photo: dict[int, list[dict[str, Any]]] = {}
for ph in photos:
by_photo.setdefault(int(ph["receipt_id"]), []).append(ph)
by_receipt: dict[int, list[dict[str, Any]]] = {}
for r in rlines:
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
lines = store.decorate_lines(lines)
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
"status_label": store.ORDER_LABELS[status],
"receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []),
"mails": by_rmail.get(int(r["id"]), []),
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts],
"mails": mails}
def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "",
date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]:
"""목록 — 상태는 품목 합계로 계산한 뒤 거른다. q = 발주번호·제품 코드·제품 이름."""
where, params = ["TRUE"], []
if factory_id:
where.append("o.factory_id = %s")
params.append(factory_id)
if date_from:
where.append("o.order_date >= %s")
params.append(date_from)
if date_to:
where.append("o.order_date <= %s")
params.append(date_to)
if q.strip():
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
where.append("(o.order_no ILIKE %s OR EXISTS (SELECT 1 FROM inout_order_lines x WHERE x.order_id = o.id "
"AND (x.item_code ILIKE %s OR x.item_name ILIKE %s)))")
params += [like, like, like]
with self._pool.connection() as conn:
heads = conn.execute(
"SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
# 상태는 품목 합계로 계산해 아래에서 거르므로 넉넉히 읽는다(발주서는 많아야 연 수천 건)
f"WHERE {' AND '.join(where)} ORDER BY o.order_date DESC, o.id DESC LIMIT {_SCAN_LIMIT}", params
).fetchall()
ids = [h["id"] for h in heads]
lines = conn.execute(
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
by_order: dict[int, list[dict[str, Any]]] = {}
for ln in lines:
by_order.setdefault(int(ln["order_id"]), []).append(ln)
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
out = []
for h in heads:
ls = by_order.get(int(h["id"]), [])
st = store.order_status(ls, closed=bool(h["closed_at"]), cancelled=bool(h["cancelled_at"]))
if st not in allowed:
continue
names = [x["item_name"] or x["item_code"] for x in ls]
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
"line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
if len(out) >= limit:
break
return out
# ════════════════════════════════════════════════════════════
# 입고
# ════════════════════════════════════════════════════════════
def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
confirm_over: bool, by: str, photos: list[dict[str, Any]] | None = None) -> dict[str, Any]:
"""입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함).
photos = store.validate_photos 결과(입고증) — 입고와 한 트랜잭션(사진 저장이 실패하면 입고도 저장 안 함)."""
try:
return self._add_receipt(order_id, quantities, receipt_date=receipt_date, memo=memo,
confirm_over=confirm_over, by=by, photos=photos or [])
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않아 사진을 저장할 수 없습니다 — "
"사진 없이 저장하거나 관리자에게 알려 주세요.") from None
def _add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
confirm_over: bool, by: str, photos: list[dict[str, Any]]) -> dict[str, Any]:
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서에는 입고할 수 없습니다.")
if head["closed_at"]:
raise ValueError("종결된 발주서입니다 — 입고하려면 발주 담당이 종결을 풀어야 합니다.")
lines = conn.execute(
"SELECT l.id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
"WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall()
# 전체 입고 완료(모든 품목 입고 ≥ 발주)면 더 받지 않는다(2026-10-19) — 화면은 버튼을 막고, 서버도 거절(잠근 뒤 판단)
if lines and all(int(x["received"]) >= int(x["qty"]) for x in lines):
raise ValueError("전체 입고가 완료된 발주서입니다 — 더 입고할 수 없습니다(잘못 넣은 입고는 입고 기록에서 지운 뒤 다시 넣으세요).")
data = store.validate_receipt(lines, quantities, receipt_date=receipt_date, memo=memo)
if data["over"] and not confirm_over:
raise OverReceipt(data["over"])
rid = conn.execute("INSERT INTO inout_receipts (order_id, receipt_date, memo, created_by) VALUES (%s,%s,%s,%s) RETURNING id",
(order_id, data["receipt_date"], data["memo"], _norm_email(by))).fetchone()["id"]
for it in data["items"]:
conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)",
(rid, it["order_line_id"], it["qty"]))
self._insert_photos(conn, int(rid), photos, by)
return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"]), "photos": len(photos)}
# ── 입고증 사진(003) ──
@staticmethod
def _insert_photos(conn: Any, receipt_id: int, photos: list[dict[str, Any]], by: str) -> None:
for ph in photos:
conn.execute("INSERT INTO inout_receipt_photos (receipt_id, filename, content_type, size_bytes, data, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(receipt_id, ph["filename"], ph["content_type"], len(ph["data"]), ph["data"], _norm_email(by)))
def add_receipt_photos(self, order_id: int, receipt_id: int, files: list[tuple[str, bytes]], *, by: str) -> int:
"""이미 있는 입고에 사진 더하기(빠뜨렸을 때). 장수 한도는 잠근 뒤 다시 센다. 반환 = 더한 장수."""
try:
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서입니다.")
if not conn.execute("SELECT 1 FROM inout_receipts WHERE id=%s AND order_id=%s", (receipt_id, order_id)).fetchone():
raise ValueError("입고 기록을 찾을 수 없습니다.")
have = int(conn.execute("SELECT count(*) AS n FROM inout_receipt_photos WHERE receipt_id=%s",
(receipt_id,)).fetchone()["n"])
photos = store.validate_photos(files, existing=have)
if not photos:
raise ValueError("올릴 사진을 고르세요.")
self._insert_photos(conn, receipt_id, photos, by)
return len(photos)
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않았습니다.") from None
def delete_receipt_photo(self, order_id: int, photo_id: int) -> None:
with self._pool.connection() as conn, conn.transaction():
self._lock_order(conn, order_id)
row = conn.execute("DELETE FROM inout_receipt_photos p USING inout_receipts r "
"WHERE p.id=%s AND p.receipt_id = r.id AND r.order_id=%s RETURNING p.id",
(photo_id, order_id)).fetchone()
if not row:
raise ValueError("사진을 찾을 수 없습니다.")
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
"""사진 내용(+ 발주서 id) — 보여 주기용."""
try:
with self._pool.connection() as conn:
return conn.execute("SELECT p.id, p.filename, p.content_type, p.data, r.order_id FROM inout_receipt_photos p "
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE p.id=%s", (photo_id,)).fetchone()
except UndefinedTable:
return None
# ════════════════════════════════════════════════════════════
# Gmail 연결(사람별, 갱신 토큰 암호문만) · 발주 메일 기록 — 003
# ════════════════════════════════════════════════════════════
def gmail_token(self, email: str) -> dict[str, Any] | None:
try:
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)).fetchone()
except UndefinedTable:
return None
def save_gmail_token(self, email: str, *, refresh_token_enc: str, scopes: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_gmail_tokens (email, refresh_token_enc, scopes, connected_at, last_error) "
"VALUES (%s,%s,%s,now(),'') ON CONFLICT (email) DO UPDATE SET refresh_token_enc=EXCLUDED.refresh_token_enc, "
"scopes=EXCLUDED.scopes, connected_at=now(), last_error=''",
(_norm_email(email), refresh_token_enc, scopes[:500]))
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(발주 메일)이 아직 적용되지 않았습니다.") from None
def delete_gmail_token(self, email: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("DELETE FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),))
except UndefinedTable:
pass
def mark_gmail(self, email: str, *, error: str = "") -> None:
"""보낸 뒤 — 성공이면 마지막 사용 시각, 실패면 오류 문구(비밀값 없음)."""
with self._pool.connection() as conn:
conn.execute("UPDATE inout_gmail_tokens SET last_used_at = CASE WHEN %s = '' THEN now() ELSE last_used_at END, "
"last_error=%s WHERE email=%s", (error[:300], error[:300], _norm_email(email)))
def add_order_mail(self, order_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_order_mails (order_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
# ════════════════════════════════════════════════════════════
# 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 — 005
# ════════════════════════════════════════════════════════════
def settings_ready(self) -> bool:
with self._pool.connection() as conn:
return bool(conn.execute("SELECT to_regclass('public.inout_settings') IS NOT NULL AND "
"to_regclass('public.inout_receipt_mails') IS NOT NULL AS ok").fetchone()["ok"])
def get_settings(self) -> dict[str, str]:
"""설정 값 — 없는 키는 store.SETTING_DEFAULTS. 005 미적용이어도 기본값으로."""
out = dict(store.SETTING_DEFAULTS)
try:
with self._pool.connection() as conn:
for r in conn.execute("SELECT key, value FROM inout_settings").fetchall():
if r["key"] in out:
out[r["key"]] = r["value"]
except UndefinedTable:
pass
return out
def save_settings(self, values: dict[str, str], *, by: str) -> None:
try:
with self._pool.connection() as conn, conn.transaction():
for k, v in values.items():
conn.execute("INSERT INTO inout_settings (key, value, updated_by, updated_at) VALUES (%s,%s,%s,now()) "
"ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_by=EXCLUDED.updated_by, updated_at=now()",
(k, v, _norm_email(by)))
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
try:
with self._pool.connection() as conn:
return conn.execute("SELECT id, filename, content_type, data FROM inout_receipt_photos WHERE receipt_id=%s ORDER BY id",
(receipt_id,)).fetchall()
except UndefinedTable:
return []
def add_receipt_mail(self, receipt_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_receipt_mails (receipt_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(receipt_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
except UndefinedTable:
pass # 메일은 이미 나갔다 — 기록만 못 남김(005 미적용)
def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None:
"""잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고)."""
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서입니다.")
row = conn.execute("DELETE FROM inout_receipts WHERE id=%s AND order_id=%s RETURNING id",
(receipt_id, order_id)).fetchone()
if not row:
raise ValueError("입고 기록을 찾을 수 없습니다.")
conn.execute("UPDATE inout_orders SET updated_by=%s WHERE id=%s", (_norm_email(by), order_id))
# ════════════════════════════════════════════════════════════
# 상품 정보(004) — 코드표 단품 + 단가·무게(개당 g)·은 함유량(%) 수기 입력, 지운 단품은 제외 목록
# ════════════════════════════════════════════════════════════
def products_ready(self) -> bool:
"""004 가 적용됐나(상품 표·발주 품목 값 칸). 한 번 확인되면 기억."""
if getattr(self, "_products_ok", False):
return True
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT to_regclass('public.inout_products') IS NOT NULL AND EXISTS (SELECT 1 FROM information_schema.columns "
"WHERE table_name = 'inout_order_lines' AND column_name = 'unit_price') AS ok").fetchone()["ok"])
self._products_ok = ok
return ok
def _need_products(self) -> None:
if not self.products_ready():
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
def list_products(self) -> list[dict[str, Any]]:
if not self.products_ready():
return []
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
def list_excluded(self) -> list[dict[str, Any]]:
if not self.products_ready():
return []
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM inout_products_excluded ORDER BY item_code").fetchall()
def import_products(self, items: list[dict[str, str]], *, by: str) -> dict[str, int]:
"""코드표 단품 → 상품 정보. 새 단품은 추가, 값(단가·무게·은 함유량)을 넣은 상품은 그대로(이름도),
값이 없는 상품은 이름만 최신으로, 제외 목록의 단품은 건너뛴다."""
self._need_products()
out = {"added": 0, "renamed": 0, "kept": 0, "excluded": 0, "same": 0}
with self._pool.connection() as conn, conn.transaction():
have = {r["item_code"]: r for r in conn.execute("SELECT * FROM inout_products FOR UPDATE").fetchall()}
skip = {r["item_code"] for r in conn.execute("SELECT item_code FROM inout_products_excluded").fetchall()}
for it in items:
code, name = it["code"].strip().upper(), (it.get("name") or "").strip()[:300]
if not code:
continue
if code in skip:
out["excluded"] += 1
elif code not in have:
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) "
"ON CONFLICT (item_code) DO NOTHING", (code, name, _norm_email(by)))
have[code] = {"item_code": code}
out["added"] += 1
elif store.has_values(have[code]):
out["kept"] += 1
elif have[code].get("item_name") != name:
conn.execute("UPDATE inout_products SET item_name=%s, updated_at=now() WHERE item_code=%s", (name, code))
out["renamed"] += 1
else:
out["same"] += 1
return out
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션."""
self._need_products()
with self._pool.connection() as conn, conn.transaction():
for r in rows:
hit = conn.execute("UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, updated_by=%s, updated_at=now() "
"WHERE item_code=%s RETURNING item_code",
(r["unit_price"], r["weight_g"], r["silver_pct"], _norm_email(by), r["code"])).fetchone()
if not hit:
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
return len(rows)
def exclude_product(self, code: str, *, by: str) -> None:
"""상품 정보에서 지우고 제외 목록에 — 다음 불러오기에서 빠진다(지난 발주서는 그대로)."""
self._need_products()
with self._pool.connection() as conn, conn.transaction():
row = conn.execute("DELETE FROM inout_products WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
if not row:
raise ValueError("상품을 찾을 수 없습니다.")
conn.execute("INSERT INTO inout_products_excluded (item_code, item_name, excluded_by) VALUES (%s,%s,%s) "
"ON CONFLICT (item_code) DO UPDATE SET excluded_at=now(), excluded_by=EXCLUDED.excluded_by",
(code, row["item_name"], _norm_email(by)))
def restore_product(self, code: str, *, by: str) -> None:
"""제외 목록에서 되살리기 — 바로 상품 정보로(값은 빈칸)."""
self._need_products()
with self._pool.connection() as conn, conn.transaction():
row = conn.execute("DELETE FROM inout_products_excluded WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
if not row:
raise ValueError("제외 목록에 없는 단품입니다.")
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
(code, row["item_name"], _norm_email(by)))
def catalog_count(self) -> int:
if not self.products_ready():
return 0
with self._pool.connection() as conn:
return int(conn.execute("SELECT count(*) AS n FROM inout_products").fetchone()["n"])
def catalog_search(self, q: str, *, limit: int = 30) -> list[dict[str, Any]]:
"""발주서 제품 고르기 — 상품 정보에서(지운 단품 제외). 코드 앞부분 일치 먼저."""
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
if not esc:
return []
with self._pool.connection() as conn:
return conn.execute(
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s",
{"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}).fetchall()
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
if not codes or not self.products_ready():
return {}
with self._pool.connection() as conn:
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
return {r["item_code"]: r for r in rows}
# ════════════════════════════════════════════════════════════
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
# ════════════════════════════════════════════════════════════
def outstanding(self, *, factory_id: int | None = None, q: str = "") -> dict[str, list[dict[str, Any]]]:
where, params = ["o.closed_at IS NULL", "o.cancelled_at IS NULL"], []
if factory_id:
where.append("o.factory_id = %s")
params.append(factory_id)
if q.strip():
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
where.append("(l.item_code ILIKE %s OR l.item_name ILIKE %s OR o.order_no ILIKE %s)")
params += [like, like, like]
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT o.id AS order_id, o.order_no, o.order_date, o.due_date, f.name AS factory_name, "
"l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
"FROM inout_order_lines l JOIN inout_orders o ON o.id = l.order_id "
"JOIN inout_factories f ON f.id = o.factory_id "
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
f"WHERE {' AND '.join(where)} GROUP BY l.id, o.id, f.name "
"ORDER BY o.due_date NULLS LAST, o.order_date, o.id, l.line_no", params).fetchall()
rows = store.decorate_lines(rows)
return {"pending": [r for r in rows if r["remaining"] > 0], "over": [r for r in rows if r["over"] > 0]}
# ── 내부 ──
@staticmethod
def _lock_order(conn: Any, order_id: int) -> dict[str, Any]:
head = conn.execute("SELECT * FROM inout_orders WHERE id=%s FOR UPDATE", (order_id,)).fetchone()
if not head:
raise LookupError("발주서를 찾을 수 없습니다.")
return head
@staticmethod
def _require_factory(conn: Any, factory_id: int, *, allow_inactive_id: int | None = None) -> None:
row = conn.execute("SELECT is_active FROM inout_factories WHERE id=%s", (factory_id,)).fetchone()
if not row:
raise ValueError("공장을 찾을 수 없습니다.")
if not row["is_active"] and factory_id != allow_inactive_id:
raise ValueError("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).")
+192
View File
@@ -0,0 +1,192 @@
"""발주 메일 — 발주 담당자 본인 Gmail 로 보내기(2026-10-16 사용자 요청, Gmail API).
연결(사람마다 한 번): [Gmail 연결] → 구글 동의 화면(로그인과 같은 OAuth 클라이언트 GOOGLE_CLIENT_ID, 범위 = gmail.send 만)
→ /inout/gmail/callback 에서 ① 고른 구글 계정이 ERP 로그인 계정과 같은지(다르면 거절 — 남의 메일함으로 보내지 않게)
② gmail.send 를 허락했는지 ③ 갱신 토큰이 왔는지 확인 → 갱신 토큰을 APP_ENCRYPTION_KEY(실적 모듈과 같은 마스터 키,
AES-256-GCM, AAD = inout:gmail:{email})로 암호화해 inout_gmail_tokens 에. 원문·접근 토큰은 저장·출력하지 않는다.
보내기: 갱신 토큰 → 접근 토큰(oauth2.googleapis.com/token) → gmail.users.messages.send(raw = RFC 822, 글 + HTML).
사람이 [메일 발송]을 눌렀을 때만 보낸다(자동 발송 없음). 연결이 끊겼으면(invalid_grant·권한 없음) 다시 연결 안내.
구글 클라우드 준비(관리자 1회): Gmail API 사용 설정 · OAuth 동의 화면에 …/auth/gmail.send 범위 추가 ·
OAuth 클라이언트의 승인된 리디렉션 URI 에 {PUBLIC_BASE_URL}/inout/gmail/callback 추가. 상세 docs/INOUT_MODULE.md.
"""
from __future__ import annotations
import base64
import os
from email.message import EmailMessage
from email.utils import formataddr
from typing import Any
import httpx
GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
TOKEN_URI = "https://oauth2.googleapis.com/token"
SEND_URI = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
CLIENT_NAME = "inout_gmail"
class GmailNotConnected(Exception):
"""Gmail 연결이 없거나 끊김 — 다시 [Gmail 연결]."""
class GmailError(Exception):
"""보내기 실패(구글 오류 등) — 문구는 화면에 그대로(비밀값 없음)."""
def _http() -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=20.0)
# ── 토큰 암호화(실적 모듈과 같은 마스터 키) ─────────────────
def _ring() -> Any:
from app.modules.performance.security.crypto import CryptoConfigError, KeyRing # noqa: WPS433
try:
return KeyRing.from_env()
except CryptoConfigError as exc:
raise GmailError(f"암호화 키가 없어 Gmail 연결을 저장할 수 없습니다 — {exc}") from None
def _aad(email: str) -> str:
return f"inout:gmail:{(email or '').strip().lower()}"
def encrypt_token(email: str, refresh_token: str) -> str:
from app.modules.performance.security.crypto import encrypt # noqa: WPS433
return encrypt(refresh_token, aad=_aad(email), ring=_ring())
def decrypt_token(email: str, enc: str) -> str:
from app.modules.performance.security.crypto import DecryptError, decrypt # noqa: WPS433
try:
return decrypt(enc, aad=_aad(email), ring=_ring())
except DecryptError:
raise GmailNotConnected("저장된 Gmail 연결을 읽을 수 없습니다(암호화 키가 바뀌었을 수 있음) — 다시 연결하세요.") from None
# ── OAuth 클라이언트(로그인과 같은 GOOGLE_CLIENT_ID, 범위만 다름) ──
def oauth_client() -> Any:
from app.main import env, oauth # noqa: WPS433
if not env("GOOGLE_CLIENT_ID") or not env("GOOGLE_CLIENT_SECRET"):
raise GmailError("GOOGLE_CLIENT_ID/SECRET 이 없어 Gmail 을 연결할 수 없습니다.")
client = oauth.create_client(CLIENT_NAME)
if client is None:
oauth.register(
name=CLIENT_NAME,
client_id=env("GOOGLE_CLIENT_ID"),
client_secret=env("GOOGLE_CLIENT_SECRET"),
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": f"openid email {GMAIL_SCOPE}"},
)
client = oauth.create_client(CLIENT_NAME)
return client
def check_grant(token: dict[str, Any], *, expected_email: str) -> tuple[str, str]:
"""콜백 토큰 확인 → (갱신 토큰, 허락된 범위). 계정이 다르거나 발송 권한·갱신 토큰이 없으면 GmailError."""
info = token.get("userinfo") or {}
got = str(info.get("email") or "").strip().lower()
want = (expected_email or "").strip().lower()
if not got or got != want:
raise GmailError(f"ERP 로그인 계정({want})과 다른 구글 계정({got or '알 수 없음'})을 골랐습니다 — 같은 계정으로 다시 연결하세요.")
scopes = str(token.get("scope") or "")
if GMAIL_SCOPE not in scopes.split():
raise GmailError("메일 보내기 권한(gmail.send)을 허락하지 않았습니다 — 동의 화면에서 체크한 뒤 다시 연결하세요.")
refresh = str(token.get("refresh_token") or "")
if not refresh:
raise GmailError("구글이 갱신 토큰을 주지 않았습니다 — 구글 계정 → 보안 → 타사 앱 접근에서 이 앱을 지우고 다시 연결하세요.")
return refresh, scopes
# ── 보내기 ──────────────────────────────────────────────
def _google_message(resp: httpx.Response) -> str:
try:
body = resp.json()
except ValueError:
return f"HTTP {resp.status_code}"
err = body.get("error")
if isinstance(err, dict):
return str(err.get("message") or err.get("status") or resp.status_code)[:200]
return str(body.get("error_description") or err or resp.status_code)[:200]
def access_token(refresh_token: str) -> str:
from app.main import env # noqa: WPS433
try:
with _http() as client:
resp = client.post(TOKEN_URI, data={"client_id": env("GOOGLE_CLIENT_ID"), "client_secret": env("GOOGLE_CLIENT_SECRET"),
"refresh_token": refresh_token, "grant_type": "refresh_token"})
except httpx.HTTPError as exc:
raise GmailError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
try:
code = str(resp.json().get("error") or "")
except ValueError:
code = ""
if code in ("invalid_grant", "unauthorized_client", "invalid_client"):
raise GmailNotConnected("Gmail 연결이 끊겼습니다(권한 취소·비밀번호 변경 등) — 다시 연결하세요.")
raise GmailError(f"구글 인증 실패: {_google_message(resp)}")
token = str(resp.json().get("access_token") or "")
if not token:
raise GmailError("구글 인증 서버가 접근 토큰을 주지 않았습니다.")
return token
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes:
"""글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어
<img src="cid:…"> 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19)."""
msg = EmailMessage()
msg["From"] = formataddr((sender_name or sender_email, sender_email))
msg["To"] = ", ".join(to)
if cc:
msg["Cc"] = ", ".join(cc)
msg["Subject"] = subject
msg.set_content(text)
msg.add_alternative(html, subtype="html")
if inline_images:
html_part = msg.get_payload()[1]
for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게
html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline")
return msg.as_bytes()
def send(refresh_token: str, raw: bytes) -> str:
"""보내고 Gmail 메시지 id 를 돌려준다."""
token = access_token(refresh_token)
body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
try:
with _http() as client:
resp = client.post(SEND_URI, json=body, headers={"Authorization": f"Bearer {token}"})
except httpx.HTTPError as exc:
raise GmailError(f"Gmail 에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code in (401, 403):
msg = _google_message(resp)
if "has not been used" in msg or "disabled" in msg.lower():
raise GmailError(f"Gmail API 가 꺼져 있습니다 — 관리자가 구글 클라우드에서 Gmail API 를 사용 설정해야 합니다. ({msg})")
raise GmailNotConnected(f"Gmail 보내기 권한이 없습니다 — 다시 연결하세요. ({msg})")
if resp.status_code != 200:
raise GmailError(f"메일을 보내지 못했습니다: {_google_message(resp)}")
return str(resp.json().get("id") or "")
def revoke(refresh_token: str) -> None:
"""연결 끊기 — 구글 쪽 권한도 취소(실패해도 무시, 우리 쪽 토큰은 지운다)."""
try:
with _http() as client:
client.post(REVOKE_URI, data={"token": refresh_token})
except httpx.HTTPError:
pass
def configured() -> bool:
"""APP_ENCRYPTION_KEY·GOOGLE_CLIENT_ID/SECRET 이 있는지(화면 안내용)."""
return bool(os.getenv("APP_ENCRYPTION_KEY", "").strip() and os.getenv("GOOGLE_CLIENT_ID", "").strip()
and os.getenv("GOOGLE_CLIENT_SECRET", "").strip())
+103
View File
@@ -0,0 +1,103 @@
"""itemcode_db 읽기 전용 — 단품(single_items)만 검색·확인.
입출고 발주서의 제품은 코드표 DB 의 단품 아이템에서만 고른다(2026-10-16 사용자 요청 — 세트는 공장 발주 대상이 아님).
itemcode_db 실제 스키마(운영 확인됨, malaysia/itemcode.py 와 같음): single_items(item_code, sabangnet_code, name).
환경변수 `ITEMCODE_DB_URL`(읽기 전용 역할 itemcode_ro) — cupang·malaysia 모듈과 공유.
미설정/실패 시 enabled=False, 빈 결과(앱/모듈을 죽이지 않음) — 그때 발주서 저장은 "코드표 연결 필요"로 막는다.
"""
from __future__ import annotations
import logging
import os
from typing import Any
logger = logging.getLogger("inout.itemcode")
_SEARCH_SQL = (
"SELECT item_code, name FROM single_items "
"WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s "
"ORDER BY (item_code ILIKE %(prefix)s) DESC, item_code ASC LIMIT %(limit)s"
)
_LOOKUP_SQL = "SELECT item_code, name FROM single_items WHERE upper(item_code) = ANY(%(codes)s)"
class SingleItemReader:
def __init__(self, dsn: str | None = None) -> None:
self._pool: Any = None
self.enabled = False
self.reason = ""
self.last_error = ""
self._configure(dsn if dsn is not None else os.getenv("ITEMCODE_DB_URL", "").strip())
def _configure(self, dsn: str) -> None:
if not dsn:
self.reason = "ITEMCODE_DB_URL 미설정 — 코드표(단품) 조회 비활성."
return
try:
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
self._pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=3,
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
self._pool.open(wait=False)
self.enabled = True
except Exception as exc: # noqa: BLE001 — 설정/드라이버 문제로 모듈을 죽이지 않음
self.reason = f"itemcode_db 연결 풀 생성 실패: {type(exc).__name__}"
def search(self, query: str, *, limit: int = 30) -> list[dict[str, str]]:
"""코드·이름 부분 일치(코드 앞부분 일치 먼저). 반환 [{"code","name"}]. 실패는 빈 목록."""
q = (query or "").strip()
if not q or not self.enabled or not self._pool:
return []
esc = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
rows = self._run(_SEARCH_SQL, {"q": f"%{esc}%", "prefix": f"{esc}%", "limit": int(limit)})
return [{"code": str(r["item_code"]).strip(), "name": str(r.get("name") or "").strip()} for r in rows or []]
def list_all(self, *, limit: int = 20000) -> list[dict[str, str]] | None:
"""단품 전체(옵션 → 상품 정보 → 단품 불러오기). 조회 불가면 None(빈 목록과 구분)."""
if not self.enabled or not self._pool:
return None
rows = self._run("SELECT item_code, name FROM single_items ORDER BY item_code LIMIT %(limit)s", {"limit": int(limit)})
if rows is None:
return None
return [{"code": str(r["item_code"]).strip().upper(), "name": str(r.get("name") or "").strip()} for r in rows if r.get("item_code")]
def lookup(self, codes: list[str]) -> dict[str, str] | None:
"""코드들 → {코드(대문자): 이름}. 단품 표에 없는 코드는 빠진다. 조회 불가면 None."""
if not self.enabled or not self._pool:
return None
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
if not wanted:
return {}
rows = self._run(_LOOKUP_SQL, {"codes": wanted})
if rows is None:
return None
return {str(r["item_code"]).strip().upper(): str(r.get("name") or "").strip() for r in rows}
def sabangnet_codes(self, codes: list[str]) -> dict[str, str] | None:
"""코드들 → {코드(대문자): 사방넷 코드}(사방넷 입고 파일, 2026-10-19). 사방넷 코드가 빈 단품은 ''. 조회 불가면 None."""
if not self.enabled or not self._pool:
return None
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
if not wanted:
return {}
rows = self._run("SELECT item_code, sabangnet_code FROM single_items WHERE upper(item_code) = ANY(%(codes)s)", {"codes": wanted})
if rows is None:
return None
return {str(r["item_code"]).strip().upper(): str(r.get("sabangnet_code") or "").strip() for r in rows}
def _run(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]] | None:
try:
with self._pool.connection() as conn:
rows = conn.execute(sql, params).fetchall()
self.last_error = ""
return rows
except Exception as exc: # noqa: BLE001 — 모듈을 죽이지 않음
self.last_error = f"{type(exc).__name__}"
logger.exception("itemcode(single_items) 조회 실패")
return None
def close(self) -> None:
if self._pool is not None:
self._pool.close()
File diff suppressed because it is too large Load Diff
+683
View File
@@ -0,0 +1,683 @@
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음).
흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결):
발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨)
→ 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시).
더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다.
"""
from __future__ import annotations
import html as _html
import re
from datetime import date, datetime
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Iterable
ROLE_ORDER = "order" # 발주 담당
ROLE_RECEIVE = "receive" # 입고 담당
ROLES = (ROLE_ORDER, ROLE_RECEIVE)
ROLE_LABELS = {ROLE_ORDER: "발주 담당", ROLE_RECEIVE: "입고 담당"}
MAX_QTY = 10_000_000
MAX_LINES = 200
MEMO_MAX = 500
# 품목 상태
LINE_NONE, LINE_PARTIAL, LINE_DONE, LINE_OVER = "none", "partial", "done", "over"
LINE_LABELS = {LINE_NONE: "미입고", LINE_PARTIAL: "부분입고", LINE_DONE: "입고완료", LINE_OVER: "초과입고"}
# 발주서 상태 — 진행(open·partial)은 미입고 현황에 나온다
ST_OPEN, ST_PARTIAL, ST_DONE, ST_OVER, ST_CLOSED, ST_CANCELLED = "open", "partial", "done", "over", "closed", "cancelled"
# 모든 품목이 입고완료·초과입고 = "전체 입고 완료"(2026-10-17 요청 — 초과가 있으면 화면에 "초과 포함"만 덧붙인다)
ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "전체 입고 완료", ST_OVER: "전체 입고 완료",
ST_CLOSED: "종결", ST_CANCELLED: "취소"}
ACTIVE_STATUSES = (ST_OPEN, ST_PARTIAL) # 아직 더 들어올 것이 있는 발주
STATUS_FILTERS = { # 목록 거르기
"active": ("진행 중", ACTIVE_STATUSES),
"done": ("완료", (ST_DONE, ST_OVER)),
"closed": ("종결·취소", (ST_CLOSED, ST_CANCELLED)),
"all": ("전체", tuple(ORDER_LABELS)),
}
WEEKDAYS_KO = "월화수목금토일"
def fmt_date(d: date | None) -> str:
"""날짜 서식 — 2026.10.17(토). 입출고 화면·메일 모두 이 모양(2026-10-17 요청). 화면 쪽은 _macros.html ymd 와 같다."""
if not d:
return ""
return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
def fmt_datetime(dt: datetime | None) -> str:
"""2026.10.17(토) 15:14 — 시각은 DB 에서 KST 로 읽는다(db._KstTimestamptzLoader)."""
return f"{fmt_date(dt)} {dt:%H:%M}" if dt else ""
def line_status(qty: int, received: int) -> str:
if received <= 0:
return LINE_NONE
if received < qty:
return LINE_PARTIAL
return LINE_DONE if received == qty else LINE_OVER
def order_status(lines: Iterable[dict[str, Any]], *, closed: bool = False, cancelled: bool = False) -> str:
"""lines: [{qty, received}]. 취소·종결이 먼저, 그다음 입고 합계로."""
if cancelled:
return ST_CANCELLED
if closed:
return ST_CLOSED
sts = [line_status(int(x["qty"]), int(x.get("received") or 0)) for x in lines]
if not sts or all(s == LINE_NONE for s in sts):
return ST_OPEN
if any(s in (LINE_NONE, LINE_PARTIAL) for s in sts):
return ST_PARTIAL
return ST_OVER if any(s == LINE_OVER for s in sts) else ST_DONE
def summarize(lines: list[dict[str, Any]]) -> dict[str, int]:
"""발주·입고·미입고(0 아래로 안 내려감)·초과 합계."""
ordered = sum(int(x["qty"]) for x in lines)
received = sum(int(x.get("received") or 0) for x in lines)
remaining = sum(max(int(x["qty"]) - int(x.get("received") or 0), 0) for x in lines)
over = sum(max(int(x.get("received") or 0) - int(x["qty"]), 0) for x in lines)
pct = min(100, round(received * 100 / ordered)) if ordered else 0
return {"ordered": ordered, "received": received, "remaining": remaining, "over": over, "pct": pct}
def decorate_lines(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""화면용 — 품목마다 미입고·초과·상태 이름."""
out = []
for x in lines:
qty, rec = int(x["qty"]), int(x.get("received") or 0)
st = line_status(qty, rec)
out.append({**x, "received": rec, "remaining": max(qty - rec, 0), "over": max(rec - qty, 0),
"status": st, "status_label": LINE_LABELS[st]})
return out
# ── 입력 검사 ────────────────────────────────────────────────
def parse_qty(raw: Any, *, label: str = "수량", allow_zero: bool = False) -> int:
s = str(raw if raw is not None else "").replace(",", "").strip()
if not s:
if allow_zero:
return 0
raise ValueError(f"{label}을(를) 입력하세요.")
try:
n = int(s)
except ValueError:
raise ValueError(f"{label}은(는) 정수로 입력하세요.") from None
if n < 0 or (n == 0 and not allow_zero):
raise ValueError(f"{label}은(는) {0 if allow_zero else 1} 이상이어야 합니다.")
if n > MAX_QTY:
raise ValueError(f"{label}이(가) 너무 큽니다.")
return n
def parse_date(raw: Any, *, label: str, required: bool = True) -> date | None:
s = str(raw or "").strip()
if not s:
if required:
raise ValueError(f"{label}을(를) 입력하세요.")
return None
try:
return date.fromisoformat(s)
except ValueError:
raise ValueError(f"{label} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
def validate_order(*, factory_id: Any, order_date: Any, due_date: Any, memo: Any,
codes: list[str], quantities: list[str], line_memos: list[str] | None = None) -> dict[str, Any]:
"""발주서 폼 → 정리된 값. 빈 줄(코드·수량 둘 다 없음)은 건너뛴다. 같은 제품 두 줄은 오류."""
errors: list[str] = []
try:
fid = int(str(factory_id or "").strip())
except ValueError:
fid = 0
if fid <= 0:
errors.append("공장을 고르세요.")
od = dd = None
try:
od = parse_date(order_date, label="발주일")
except ValueError as exc:
errors.append(str(exc))
try:
dd = parse_date(due_date, label="입고 예정일", required=False)
except ValueError as exc:
errors.append(str(exc))
if od and dd and dd < od:
errors.append("입고 예정일이 발주일보다 빠릅니다.")
line_memos = line_memos or []
lines: list[dict[str, Any]] = []
seen: set[str] = set()
for i, code in enumerate(codes):
code = (code or "").strip().upper()
raw_qty = quantities[i] if i < len(quantities) else ""
if not code and not str(raw_qty or "").strip():
continue
if not code:
errors.append(f"{i + 1}번째 줄: 제품을 고르세요.")
continue
if code in seen:
errors.append(f"{code}: 같은 제품이 두 줄에 있습니다 — 한 줄로 합쳐 주세요.")
continue
seen.add(code)
try:
qty = parse_qty(raw_qty, label=f"{code} 발주 수량")
except ValueError as exc:
errors.append(str(exc))
continue
lines.append({"item_code": code, "qty": qty,
"memo": str(line_memos[i] if i < len(line_memos) else "").strip()[:MEMO_MAX]})
if not lines and not any("줄" in e or "수량" in e for e in errors):
errors.append("발주할 제품을 한 줄 이상 넣으세요.")
if len(lines) > MAX_LINES:
errors.append(f"한 발주서에 {MAX_LINES}개 제품까지 넣을 수 있습니다.")
if errors:
raise ValueError("\n".join(errors))
return {"factory_id": fid, "order_date": od, "due_date": dd, "memo": str(memo or "").strip()[:MEMO_MAX], "lines": lines}
def validate_receipt(order_lines: list[dict[str, Any]], quantities: dict[int, Any], *,
receipt_date: Any, memo: Any) -> dict[str, Any]:
"""입고 입력 — quantities: {발주 줄 id: 입력값}. 빈칸·0 은 이번에 안 들어온 것.
over = 이번 입고로 발주를 넘는 품목(확인 받은 뒤 저장). order_lines 는 지금까지 누적 입고(received)를 포함."""
errors: list[str] = []
try:
rd = parse_date(receipt_date, label="입고일")
except ValueError as exc:
errors.append(str(exc))
rd = None
by_id = {int(x["id"]): x for x in order_lines}
items: list[dict[str, Any]] = []
over: list[dict[str, Any]] = []
for lid, raw in quantities.items():
line = by_id.get(int(lid))
if line is None:
errors.append("이 발주서에 없는 품목이 들어 있습니다.")
continue
try:
qty = parse_qty(raw, label=f"{line['item_code']} 입고 수량", allow_zero=True)
except ValueError as exc:
errors.append(str(exc))
continue
if qty == 0:
continue
items.append({"order_line_id": int(lid), "qty": qty})
after = int(line.get("received") or 0) + qty
if after > int(line["qty"]):
over.append({"item_code": line["item_code"], "item_name": line.get("item_name", ""),
"ordered": int(line["qty"]), "after": after, "over": after - int(line["qty"])})
if not items and not errors:
errors.append("입고 수량을 한 품목 이상 넣으세요.")
if errors:
raise ValueError("\n".join(errors))
return {"receipt_date": rd, "memo": str(memo or "").strip()[:MEMO_MAX], "items": items, "over": over}
def order_no(order_date: date, seq: int) -> str:
"""PO-YYMMDD-NN — 발주일 기준 그날 순번(01부터)."""
return f"PO-{order_date:%y%m%d}-{seq:02d}"
# ════════════════════════════════════════════════════════════
# 발주 메일(2026-10-16, 마이그레이션 003) — 받는 주소 검사, 본문(요약) 만들기. 보내기는 gmail.py
# ════════════════════════════════════════════════════════════
MAX_RECIPIENTS = 10
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) -> list[str]:
"""'a@x.com, b@y.co.kr; c@z.com' → 주소 목록(순서 유지·중복 제거). 형식이 틀리면 ValueError."""
out: list[str] = []
for part in re.split(r"[\s,;]+", str(raw or "")):
if not part:
continue
if not _EMAIL_RE.match(part) or len(part) > 254:
raise ValueError(f"{label} 형식이 올바르지 않습니다: {part[:60]}")
if part.lower() not in [x.lower() for x in out]:
out.append(part)
if required and not out:
raise ValueError(f"{label}을(를) 입력하세요.")
if len(out) > MAX_RECIPIENTS:
raise ValueError(f"{label}은(는) {MAX_RECIPIENTS}개까지 넣을 수 있습니다.")
return out
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
— 발주 품목에 남긴 그때 값(004). 없으면 '-'. (2026-10-19 — 예전엔 PP(g/개)·개당 은 g)"""
lines = order["lines"]
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
total = sum(int(x["qty"]) for x in lines)
money = order_totals(lines)
due = fmt_date(order["due_date"]) if order.get("due_date") else "협의"
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
who = sender_name or sender_email
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
if money["amount"] is not None:
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
if money["pp_kg"] is not None:
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
if money["pp_use_kg"] is not None:
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
if ag_kg is not None:
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
if order.get("memo"):
facts.append(("요청 사항", order["memo"]))
def cells(x: dict[str, Any]) -> dict[str, str]:
price, w, pct = to_dec(x.get("unit_price")), to_dec(x.get("weight_g")), to_dec(x.get("silver_pct"))
q = int(x["qty"])
amt = line_amount(q, price)
total_kg = w * q / Decimal(1000) if w is not None else None # 전체 무게 = 개당 g × 수량
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
"weight": fmt_num(total_kg, 3) if total_kg is not None else "-",
"pp_use": fmt_num(total_kg - ag_kg, 3) if ag_kg is not None else "-",
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag_kg, 4)}kg)" if ag_kg is not None else "")) if pct is not None else "-"}
# 글 본문(HTML 을 못 보는 메일 프로그램용)
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
text += [f"- {k}: {v}" for k, v in facts]
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
for i, x in enumerate(lines, start=1):
c = cells(x)
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}"
+ (f" ({x['memo']})" if x.get("memo") else ""))
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
# HTML 본문 — 값은 모두 escape
e = _html.escape
td = "padding:6px 10px;border:1px solid #d9dce1;"
r = "text-align:right;white-space:nowrap;"
# 요약 표 = 항목·값 두 쌍씩 한 줄(4열, 2026-10-19 — 예전 2열 × 8행). 요청 사항(길 수 있음)은 맨 아래 한 줄 전체.
# 칸 높이는 글자 한 줄에 맞게 — 받은 메일(메일 프로그램)에서 칸이 크게 늘어나 보여 줄 높이·글자 크기·위아래 여백을 칸마다 못 박는다.
ftd = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;height:20px;vertical-align:middle;white-space:nowrap;"
fth = f"{ftd}background:#f6f7f9;text-align:left;font-weight:700;"
pairs = [(k, v) for k, v in facts if k != "요청 사항"]
fact_rows = ""
for i in range(0, len(pairs), 2):
cols = "".join(f'<th style="{fth}">{e(k)}</th><td style="{ftd}">{e(str(v))}</td>' for k, v in pairs[i:i + 2])
if len(pairs[i:i + 2]) == 1:
cols += f'<th style="{fth}"></th><td style="{ftd}"></td>'
fact_rows += f"<tr>{cols}</tr>"
if order.get("memo"): # 요청 사항은 길면 줄을 바꿔야 하므로 높이를 고정하지 않는다
memo_td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;vertical-align:middle;"
fact_rows += (f'<tr><th style="{fth}">요청 사항</th>'
f'<td colspan="3" style="{memo_td}">{e(str(order["memo"]))}</td></tr>')
rows = []
for i, x in enumerate(lines, start=1):
c = cells(x)
rows.append(
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>'
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>'
f'<td style="{td}{r}">{e(c["weight"])}</td><td style="{td}{r}">{e(c["pp_use"])}</td><td style="{td}{r}">{e(c["ag"])}</td>'
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>')
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else ""
foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else ""
foot_ag = f'{fmt_num(ag_kg, 4)} kg' if ag_kg is not None else ""
bg = "background:#f6f7f9;"
html = (
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{fact_rows}</table>'
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
'<div style="height:18px;line-height:18px;font-size:1px">&nbsp;</div>'
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>'
f'<th style="{td}">비고</th></tr></thead>'
f'<tbody>{"".join(rows)}</tbody>'
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>'
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
)
return {"subject": subject, "text": "\n".join(text), "html": html}
# ════════════════════════════════════════════════════════════
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
# ════════════════════════════════════════════════════════════
PRODUCT_LIMITS = {"unit_price": ("단가", Decimal("1000000000"), 2), "weight_g": ("무게", Decimal("1000000"), 2),
"silver_pct": ("은 함유량", Decimal("100"), 4)}
def to_dec(v: Any) -> Decimal | None:
if v is None or v == "":
return None
try:
return Decimal(str(v))
except (InvalidOperation, ValueError):
return None
def fmt_num(v: Any, places: int = 2) -> str:
"""1234.50 → '1,234.5', 1234 → '1,234' (소수 끝 0 은 뺀다)."""
d = to_dec(v)
if d is None:
return ""
q = d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
s = f"{q:,.{places}f}"
return s.rstrip("0").rstrip(".") if "." in s else s
def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
w, p = to_dec(weight_g), to_dec(silver_pct)
if w is None or p is None:
return None
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
def line_amount(qty: int, unit_price: Any) -> Decimal | None:
p = to_dec(unit_price)
return None if p is None else (p * int(qty)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
"""발주 금액 합(단가 있는 줄만, 없으면 None)·단가 없는 줄 수·PP 총량(= 전체 무게, kg)·은 총량(g)·
PP 사용량(kg, 무게·은 함유량이 다 있는 줄의 전체 무게 − 은 무게 — 메일 표, 2026-10-19)."""
amount = pp = ag = use = None
missing = 0
for x in lines:
q = int(x["qty"])
a = line_amount(q, x.get("unit_price"))
if a is None:
missing += 1
else:
amount = (amount or Decimal(0)) + a
w = to_dec(x.get("weight_g"))
if w is not None:
pp = (pp or Decimal(0)) + w * q / Decimal(1000)
p = to_dec(x.get("silver_pct"))
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag,
"pp_use_kg": use}
def parse_decimal(raw: Any, *, key: str) -> Decimal | None:
"""상품 정보 칸 하나 — 빈칸은 None(미입력), 숫자·쉼표·0 이상·한도 안·소수 자리."""
label, limit, places = PRODUCT_LIMITS[key]
s = str(raw if raw is not None else "").replace(",", "").replace("%", "").strip()
if not s:
return None
try:
d = Decimal(s)
except InvalidOperation:
raise ValueError(f"{label}은(는) 숫자로 입력하세요.") from None
if not d.is_finite() or d < 0:
raise ValueError(f"{label}은(는) 0 이상이어야 합니다.")
if d > limit:
raise ValueError(f"{label}이(가) 너무 큽니다(최대 {fmt_num(limit, 0)}).")
return d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]:
"""{"unit_price","weight_g","silver_pct"} → 정리된 값. 틀리면 ValueError(칸 이름 포함)."""
return {k: parse_decimal(values.get(k), key=k) for k in PRODUCT_LIMITS}
def has_values(p: dict[str, Any]) -> bool:
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
# ════════════════════════════════════════════════════════════
# 입고증 사진(2026-10-16, 마이그레이션 003)
# ════════════════════════════════════════════════════════════
MAX_PHOTOS = 10 # 입고 한 건에
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 한 장(브라우저가 줄여서 보내므로 보통 0.3~1MB)
def sniff_image(data: bytes) -> str | None:
"""파일 머리로 이미지 종류 판단(브라우저가 보낸 종류는 믿지 않는다). 모르면 None."""
if data[:3] == b"\xff\xd8\xff":
return "image/jpeg"
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
if data[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
if data[4:12] in (b"ftypheic", b"ftypheix", b"ftypmif1", b"ftyphevc", b"ftypheif"):
return "image/heic" # 아이폰 원본 — 사파리 외 브라우저는 미리보기 못 함(내려받기)
return None
def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> list[dict[str, Any]]:
"""[(파일 이름, 내용)] → [{filename, content_type, data}]. 빈 파일은 건너뛴다. 하나라도 틀리면 ValueError."""
out: list[dict[str, Any]] = []
for name, data in files:
if not data:
continue
name = (name or "photo").replace("\\", "/").rsplit("/", 1)[-1][:120]
if len(data) > MAX_PHOTO_BYTES:
raise ValueError(f"사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지): {name}")
ctype = sniff_image(data)
if ctype is None:
raise ValueError(f"사진 파일(JPG·PNG·WEBP·GIF·HEIC)만 올릴 수 있습니다: {name}")
out.append({"filename": name, "content_type": ctype, "data": data})
if existing + len(out) > MAX_PHOTOS:
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
return out
# ════════════════════════════════════════════════════════════
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하).
# ════════════════════════════════════════════════════════════
SETTING_LOGISTICS_EMAILS = "logistics_emails"
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
SETTING_ORDER_MAIL_CC = "order_mail_cc" # 발주 메일 참조 기본값(2026-10-19 — king@, 옵션 → 공장에서 고침)
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr",
SETTING_ORDER_MAIL_CC: "king@dbxcorp.co.kr"}
MAIL_IMAGE_MAX_W = 600
def clean_emails(raw: Any, *, label: str) -> str:
"""옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '')."""
return ", ".join(parse_emails(raw, label=label))
def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
"""입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영).
반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다."""
from io import BytesIO # noqa: WPS433
from PIL import Image, ImageOps # noqa: WPS433
out: list[dict[str, Any]] = []
skipped = 0
for ph in photos:
try:
im = Image.open(BytesIO(bytes(ph["data"])))
if im.format == "JPEG":
im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름)
im = ImageOps.exif_transpose(im)
if im.mode not in ("RGB", "L"):
rgba = im.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.split()[-1])
im = bg
if im.width > MAIL_IMAGE_MAX_W:
im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS)
buf = BytesIO()
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로)
skipped += 1
continue
out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height})
return out, skipped
def receipt_mail_subject(receipt_date: date) -> str:
d = receipt_date
return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다."
def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0,
sender_name: str, sender_email: str) -> dict[str, str]:
"""입고 1건 → 제목·글 본문·HTML 본문. 이미지는 <img src="cid:…"> (보낼 때 gmail.build_message 가 본문에 붙임).
비고 = 그 발주 품목의 줄 메모. 값은 모두 escape."""
memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]}
rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")}
for x in receipt["lines"]]
total = sum(r["qty"] for r in rows)
who = sender_name or sender_email
when = fmt_date(receipt["receipt_date"])
info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}"
lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다."
# 글 본문(HTML 을 못 보는 메일 프로그램용)
text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"]
text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows]
text.append(f"합계 {total:,}개")
if receipt.get("memo"):
text += ["", f"메모: {receipt['memo']}"]
if images or skipped:
text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")]
text += ["", f"입고 담당: {who} ({sender_email})"]
# HTML 본문
e = _html.escape
td = "padding:6px 10px;border:1px solid #d9dce1;"
r_ = "text-align:right;white-space:nowrap;"
bg = "background:#f6f7f9;"
body_rows = "".join(
f'<tr><td style="{td}">{e(r["name"])}</td><td style="{td}font-family:Consolas,monospace">{e(r["code"])}</td>'
f'<td style="{td}{r_}">{r["qty"]:,}</td><td style="{td}">{e(r["note"])}</td></tr>' for r in rows)
imgs = "".join(
f'<p style="margin:8px 0"><img src="cid:{e(im["cid"])}" width="{im["width"]}" height="{im["height"]}" alt="입고 인증 사진 {i}" '
f'style="display:block;width:{im["width"]}px;max-width:100%;height:auto;border:1px solid #d9dce1"></p>'
for i, im in enumerate(images, start=1))
photo_block = ""
if images or skipped:
photo_block = (f'<p style="margin:18px 0 4px"><b>입고 인증 사진</b> <span style="color:#777">{len(images)}장</span></p>{imgs}'
+ (f'<p style="color:#777">본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.</p>' if skipped else ""))
html = (
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
f"<p>안녕하세요.<br>{e(lead)}</p>"
f'<p style="color:#555;margin:0 0 8px">{e(info)}</p>'
'<table style="border-collapse:collapse;min-width:480px">'
f'<thead><tr style="{bg}"><th style="{td}">상품 이름</th><th style="{td}">상품 코드</th><th style="{td}">입고 수량</th>'
f'<th style="{td}">비고</th></tr></thead><tbody>{body_rows}</tbody>'
f'<tfoot><tr><th colspan="2" style="{td}{bg}text-align:right">합계</th><th style="{td}{bg}{r_}">{total:,}</th>'
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
+ (f'<p style="margin:10px 0 0">메모: {e(str(receipt["memo"]))}</p>' if receipt.get("memo") else "")
+ photo_block
+ f'<p style="color:#555;margin-top:18px">입고 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
)
return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html}
def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str:
"""미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로)."""
import base64 # noqa: WPS433
for im in images:
html = html.replace(f'src="cid:{_html.escape(im["cid"])}"',
f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"')
return html
# ════════════════════════════════════════════════════════════
# 사방넷 입고 파일(2026-10-19) — 입고 1건 → 엑셀. 1행 제목 A 상품코드 · B 가용수량 · C 불용수량,
# A = 코드표(itemcode_db single_items)의 사방넷 코드, B = 입고 수량, C = 수량이 아니라 상품 이름(사용자 지정).
# ════════════════════════════════════════════════════════════
SABANGNET_HEADER = ("상품코드", "가용수량", "불용수량")
def sabangnet_rows(receipt: dict[str, Any], codes: dict[str, str]) -> tuple[list[list[Any]], list[str]]:
"""입고 품목 → (엑셀 줄 [사방넷 코드, 입고 수량, 상품 이름], 사방넷 코드가 없는 품목 "코드 이름" 목록)."""
rows: list[list[Any]] = []
missing: list[str] = []
for x in receipt["lines"]:
code = (codes.get(str(x["item_code"]).strip().upper()) or "").strip()
if not code:
missing.append(f"{x['item_code']} {x['item_name']}".strip())
rows.append([code, int(x["qty"]), str(x["item_name"] or "")])
return rows, missing
def sabangnet_xlsx(rows: list[list[Any]]) -> bytes:
"""제목 행(굵게·회색 바탕) + 줄. 상품코드·불용수량(상품 이름)은 글자 칸(앞자리 0 보존)."""
from io import BytesIO # noqa: WPS433
from openpyxl import Workbook # noqa: WPS433
from openpyxl.styles import Font, PatternFill # noqa: WPS433
wb = Workbook()
ws = wb.active
ws.title = "입고"
ws.append(list(SABANGNET_HEADER))
for c in ws[1]:
c.font = Font(bold=True)
c.fill = PatternFill(start_color="FFE7E9ED", end_color="FFE7E9ED", fill_type="solid")
for code, qty, name in rows:
ws.append([code, qty, name])
r = ws.max_row
ws.cell(row=r, column=1).number_format = "@"
ws.cell(row=r, column=3).number_format = "@"
for letter, col in (("A", 0), ("B", 1), ("C", 2)):
longest = max(sum(2 if ord(ch) > 0x1100 else 1 for ch in str(v)) for v in [SABANGNET_HEADER[col]] + [r[col] for r in rows])
ws.column_dimensions[letter].width = max(10, min(60, longest + 2))
buf = BytesIO()
wb.save(buf)
return buf.getvalue()
def sabangnet_filename(order: dict[str, Any], receipt: dict[str, Any]) -> str:
return f"사방넷_입고_{receipt['receipt_date']:%Y%m%d}_{order['order_no']}.xlsx"
# ════════════════════════════════════════════════════════════
# 발주 알림 메일(2026-10-19) — 발주 담당이 발주 메일을 보낼 때 입고 담당(옵션 → 담당자)에게 같은 Gmail 로 따로 자동 발송.
# 내용 = 발주번호·발주일·제품 코드·제품명·수량만(단가·무게 등은 넣지 않음), 제목 = 발주 메일과 같음.
# ════════════════════════════════════════════════════════════
def order_notice_mail(order: dict[str, Any], *, subject: str, sender_name: str, sender_email: str) -> dict[str, str]:
e = _html.escape
lines = order["lines"]
total = sum(int(x["qty"]) for x in lines)
who = sender_name or sender_email
when = fmt_date(order["order_date"])
text = ["입고 담당자님, 안녕하세요.", "", "아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.", "",
f"- 발주번호: {order['order_no']}", f"- 발주일: {when}", "", "[발주 품목] 제품 코드 · 제품명 · 수량"]
text += [f"- {x['item_code']} · {x['item_name']} · {int(x['qty']):,}개" for x in lines]
text += [f"합계 {total:,}개", "", f"발주 담당: {who} ({sender_email})"]
td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;"
th = f"{td}background:#f6f7f9;font-weight:700;white-space:nowrap;"
r = "text-align:right;white-space:nowrap;"
facts = (f'<tr><th style="{th}text-align:left">발주번호</th><td style="{td}">{e(order["order_no"])}</td>'
f'<th style="{th}text-align:left">발주일</th><td style="{td}">{e(when)}</td></tr>')
rows = "".join(f'<tr><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td><td style="{td}">{e(x["item_name"])}</td>'
f'<td style="{td}{r}">{int(x["qty"]):,}</td></tr>' for x in lines)
html = (
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
"<p>입고 담당자님, 안녕하세요.<br>아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.</p>"
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{facts}</table>'
'<div style="height:18px;line-height:18px;font-size:1px">&nbsp;</div>'
'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;min-width:420px">'
f'<thead><tr><th style="{th}">제품 코드</th><th style="{th}">제품명</th><th style="{th}">수량</th></tr></thead>'
f'<tbody>{rows}</tbody>'
f'<tfoot><tr><th colspan="2" style="{th}text-align:right">합계</th><th style="{th}{r}">{total:,}</th></tr></tfoot></table>'
f'<p style="color:#555;margin-top:18px">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
)
return {"subject": subject, "text": "\n".join(text), "html": html}
@@ -0,0 +1,28 @@
{# 상태 배지 — 발주서(open·partial·done·over·closed·cancelled) / 품목(none·partial·done·over) #}
{% macro status_badge(status, label) -%}
<span class="io-badge io-st-{{ status }}">{{ label }}</span>
{%- endmacro %}
{# 진행률 막대 — 입고 ÷ 발주 #}
{% macro progress(summary) -%}
<span class="io-progress" title="입고 {{ '{:,}'.format(summary.received) }} / 발주 {{ '{:,}'.format(summary.ordered) }}">
<span class="io-progress-bar{% if summary.over %} is-over{% endif %}" style="width:{{ summary.pct }}%"></span>
</span><span class="io-progress-pct">{{ summary.pct }}%</span>
{%- endmacro %}
{# 날짜 서식 — 2026.10.17(토) / 2026.10.17(토) 15:14 (2026-10-17 요청, 메일·JSON 은 store.fmt_date·fmt_datetime) #}
{% macro ymd(d) -%}{% if d %}{{ d.strftime('%Y.%m.%d') }}({{ '월화수목금토일'[d.weekday()] }}){% endif %}{%- endmacro %}
{% macro ymdhm(d) -%}{% if d %}{{ ymd(d) }} {{ d.strftime('%H:%M') }}{% endif %}{%- endmacro %}
{# 발주서 상태 — 모든 품목이 입고완료·초과입고면 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함"), 나머지는 상태 배지 #}
{% macro order_badge(status, label) -%}
{% if status in ('done', 'over') %}<span class="io-badge io-st-done io-st-all">✓ {{ label }}</span>{% if status == 'over' %}<span class="io-badge-note">초과 포함</span>{% endif %}
{%- else %}{{ status_badge(status, label) }}{% endif %}
{%- endmacro %}
{# 입고 예정일 — 지났는데 남은 게 있으면 빨강 "지연 N일" #}
{% macro due(due_date, today, active) -%}
{% if due_date %}{{ ymd(due_date) }}{% if active and due_date < today %} <span class="io-late">지연 {{ (today - due_date).days }}일</span>{% elif active %} <span class="erp-muted">D-{{ (due_date - today).days }}</span>{% endif %}{% else %}<span class="erp-muted">-</span>{% endif %}
{%- endmacro %}
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
@@ -0,0 +1,36 @@
{# 입출고 관리 공용 상단: 탭(발주 목록·미입고 현황) + 담당 표시 + 새 발주서 + 옵션 톱니(관리자, 팝업) + 알림 문구(?msg=) #}
<div class="io-nav">
<a class="erp-btn {% if tab == 'orders' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/">발주 목록</a>
<a class="erp-btn {% if tab == 'pending' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/pending">미입고 현황</a>
<span class="io-nav-gap"></span>
<span class="io-roles erp-muted">
{% if perms.can_order %}<span class="erp-badge erp-badge-neutral">발주 담당</span>{% endif %}
{% if perms.can_receive %}<span class="erp-badge erp-badge-neutral">입고 담당</span>{% endif %}
{% if not perms.can_order and not perms.can_receive %}조회만 가능 — 담당 지정은 옵션(관리자){% endif %}
</span>
{% if perms.can_order %}<a class="erp-btn erp-btn-primary" href="/inout/orders/new">+ 새 발주서</a>{% endif %}
{% if perms.admin %}
<button type="button" class="io-gear" id="io-options-btn" title="입출고 관리 옵션" aria-label="입출고 관리 옵션"
aria-haspopup="dialog" {% if open_options %}data-open="1"{% endif %}>
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="3"/>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
</svg>
</button>
{% endif %}
</div>
{% if msg %}<p class="io-flash" role="status">{{ msg }}</p>{% endif %}
{% if perms.admin %}
{# 옵션 팝업 — 내용은 열 때 GET /inout/settings?panel=1 로 받아 넣고, 저장은 제자리에서(inout.js) #}
<dialog class="io-dlg" id="io-options" aria-labelledby="io-options-title" tabindex="-1">
<header class="io-dlg-head">
<h2 id="io-options-title">입출고 관리 옵션</h2>
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
</button>
</header>
<p class="io-dlg-msg" role="status" hidden></p>
<div class="io-dlg-body" id="io-options-body"><p class="erp-muted">불러오는 중…</p></div>
</dialog>
{% endif %}
@@ -0,0 +1,155 @@
{% from "inout/_macros.html" import ymd %}
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
<button type="button" role="tab" class="is-active" aria-selected="true" data-pane="roles">담당자</button>
<button type="button" role="tab" aria-selected="false" data-pane="factories" tabindex="-1">공장 <span class="io-dlg-count">{{ factories|length }}</span></button>
<button type="button" role="tab" aria-selected="false" data-pane="products" tabindex="-1">상품 정보 <span class="io-dlg-count">{{ products|length }}</span></button>
<button type="button" role="tab" aria-selected="false" data-pane="logistics" tabindex="-1">물류센터</button>
</div>
<section class="io-dlg-pane" data-pane="roles" role="tabpanel">
<p class="io-help">
<b>발주 담당</b> — 발주서 작성·고치기·잔량 종결·취소. <b>입고 담당</b> — 물류에 들어온 입고 수량 입력·지우기.
그 밖의 사람은 조회만 합니다. ERP 관리자는 지정 없이도 둘 다 할 수 있습니다.
후보 = ERP 관리자 화면에서 <b>입출고 관리</b> 권한을 받은 사용자.
</p>
<form method="post" action="/inout/settings/roles" class="io-dlg-form">
<table class="io-dlg-table">
<thead><tr><th>사용자</th>{% for role, label in role_labels.items() %}<th class="io-c">{{ label }}</th>{% endfor %}</tr></thead>
<tbody>
{% for c in candidates %}
<tr>
<td><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></td>
{% for role in role_labels %}
<td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %}
aria-label="{{ c.email }} {{ role_labels[role] }}" /></td>
{% endfor %}
</tr>
{% else %}
<tr><td colspan="3" class="io-empty">입출고 관리 권한을 받은 사용자가 없습니다 — ERP 관리자 화면에서 먼저 권한을 주세요.</td></tr>
{% endfor %}
</tbody>
</table>
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary">담당자 저장</button></div>
</form>
</section>
<section class="io-dlg-pane" data-pane="factories" role="tabpanel" hidden>
<p class="io-help">발주서에서 고르는 공장(발주처)입니다. <b>이메일</b>은 발주 메일을 받을 주소(여러 개는 쉼표). 발주 기록이 있는 공장은 지우지 말고 <b>사용</b>을 끄면 목록에서 숨겨집니다.</p>
<form method="post" action="/inout/settings/order-mail" class="io-dlg-form io-ordercc-form">
<label class="io-logi-field"><span>발주 메일 참조 <small>(모든 발주 메일의 참조 칸에 미리 들어감 — 보낼 때 고칠 수 있음, 여러 개는 쉼표)</small></span>
<span class="io-ordercc-row"><input class="io-in" type="text" inputmode="email" name="order_mail_cc" value="{{ settings.order_mail_cc }}" maxlength="1000"
aria-label="발주 메일 참조" />
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm"{% if not settings_ready %} disabled title="DB 마이그레이션 inout_db 005 필요"{% endif %}>저장</button></span></label>
</form>
{% for f in factories %}<form method="post" action="/inout/settings/factories" id="io-f{{ f.id }}" class="io-dlg-form"><input type="hidden" name="id" value="{{ f.id }}" /></form>{% endfor %}
<form method="post" action="/inout/settings/factories" id="io-fnew" class="io-dlg-form"><input type="hidden" name="is_active" value="1" /></form>
<table class="io-dlg-table io-factory-table">
<colgroup><col class="w-name" /><col class="w-man" /><col class="w-tel" /><col class="w-mail" /><col class="w-memo" /><col class="w-sort" /><col class="w-use" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>공장 이름</th><th>담당자</th><th>연락처</th><th title="발주 메일을 받을 주소 — 여러 개는 쉼표로">이메일</th><th>메모</th><th class="io-c">순서</th><th class="io-c">사용</th><th class="io-c">발주</th><th></th></tr></thead>
<tbody>
{% for f in factories %}
{% set fid = 'io-f' ~ f.id %}
<tr class="{% if not f.is_active %}is-inactive{% endif %}">
<td><input class="io-in" form="{{ fid }}" type="text" name="name" value="{{ f.name }}" maxlength="100" required aria-label="공장 이름" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" name="manager" value="{{ f.manager }}" maxlength="100" aria-label="담당자" /></td>
<td><input class="io-in" form="{{ fid }}" type="tel" name="contact" value="{{ f.contact }}" maxlength="200" aria-label="연락처" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" inputmode="email" name="email" value="{{ f.email }}" maxlength="600" aria-label="이메일" placeholder="발주 메일 받는 주소" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" name="memo" value="{{ f.memo }}" maxlength="500" aria-label="메모" /></td>
<td class="io-c"><input class="io-in io-in-num" form="{{ fid }}" type="number" name="sort_order" value="{{ f.sort_order }}" aria-label="순서" /></td>
<td class="io-c"><input form="{{ fid }}" type="checkbox" name="is_active" value="1" {% if f.is_active %}checked{% endif %} aria-label="사용" /></td>
<td class="io-c io-sub">{{ f.order_count }}건</td>
<td class="io-btns">
<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
{% if not f.order_count %}<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/factories/{{ f.id }}/delete"
formnovalidate data-confirm="공장 '{{ f.name }}' 을(를) 지울까요?">지우기</button>{% endif %}
</td>
</tr>
{% endfor %}
<tr class="io-new-row">
<td><input class="io-in" form="io-fnew" type="text" name="name" maxlength="100" required placeholder="새 공장 이름" aria-label="새 공장 이름" /></td>
<td><input class="io-in" form="io-fnew" type="text" name="manager" maxlength="100" placeholder="담당자" aria-label="담당자" /></td>
<td><input class="io-in" form="io-fnew" type="tel" name="contact" maxlength="200" placeholder="010-0000-0000" aria-label="연락처" /></td>
<td><input class="io-in" form="io-fnew" type="text" inputmode="email" name="email" maxlength="600" placeholder="factory@example.com" aria-label="이메일" /></td>
<td><input class="io-in" form="io-fnew" type="text" name="memo" maxlength="500" placeholder="메모" aria-label="메모" /></td>
<td class="io-c"><input class="io-in io-in-num" form="io-fnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
<td></td><td></td>
<td class="io-btns"><button form="io-fnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
</tr>
</tbody>
</table>
</section>
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
{% if not products_ready %}
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
{% else %}
<p class="io-help">
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
</p>
<div class="io-prod-bar">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
<span class="io-sub" id="io-prod-count">{{ products|length }}개{% if excluded %} · 제외 {{ excluded|length }}개{% endif %}</span>
<span class="io-nav-gap"></span>
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" id="io-prod-save" disabled>변경 저장 <span id="io-prod-dirty"></span></button>
</div>
{% if products %}
<div class="io-prod-scroll">
<table class="io-dlg-table io-prod-table">
<colgroup><col class="w-code" /><col /><col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" /><col class="w-del" /></colgroup>
<thead><tr><th>코드</th><th>제품명</th><th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th><th></th></tr></thead>
<tbody>
{% for p in products %}
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name)|lower }}">
<td class="io-code">{{ p.item_code }}</td>
<td class="io-prod-name">{{ p.item_name }}</td>
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
<td><input class="io-in io-in-num" data-key="silver_pct" value="{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" /></td>
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
{% endif %}
{% if excluded %}
<details class="io-excluded">
<summary>제외 목록 {{ excluded|length }}개 — 불러오기에서 빠지는 단품</summary>
<ul>
{% for x in excluded %}
<li><span class="io-code">{{ x.item_code }}</span> {{ x.item_name }} <span class="io-sub">· {{ ymd(x.excluded_at) }}</span>
<button type="button" class="io-link-btn" data-restore="{{ x.item_code }}">되살리기</button></li>
{% endfor %}
</ul>
</details>
{% endif %}
{% endif %}
</section>
<section class="io-dlg-pane" data-pane="logistics" role="tabpanel" hidden>
{% if not settings_ready %}
<p class="io-error">DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
{% endif %}
<p class="io-help">
입고 담당이 <b>입고 저장</b>을 누르면 물류센터 입고 담당자에게 보낼 <b>입고 요청 메일</b>(전산 등록 부탁 · 입고 상품 표 · 입고증 사진)을
미리 보여 주고, [메일 발송]을 눌러 입고 담당 본인 Gmail 로 보냅니다. 아래 주소가 받는 사람·참조 칸에 미리 들어갑니다(보낼 때 고칠 수 있음).
</p>
<form method="post" action="/inout/settings/logistics" class="io-dlg-form io-logi-form">
<label class="io-logi-field"><span>물류센터 담당자 이메일 <small>(받는 사람 — 여러 개는 쉼표)</small></span>
<input class="io-in" type="text" inputmode="email" name="logistics_emails" value="{{ settings.logistics_emails }}" maxlength="1000"
placeholder="logistics@example.com" aria-label="물류센터 담당자 이메일" /></label>
<label class="io-logi-field"><span>입고 요청 메일 참조 <small>(여러 개는 쉼표)</small></span>
<input class="io-in" type="text" inputmode="email" name="receipt_mail_cc" value="{{ settings.receipt_mail_cc }}" maxlength="1000"
aria-label="입고 요청 메일 참조" /></label>
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary"{% if not settings_ready %} disabled{% endif %}>물류센터 저장</button></div>
</form>
</section>
<p class="io-dlg-foot">코드표(단품) 연결: {{ items_status }}</p>
@@ -0,0 +1,71 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
{% block content %}
<section class="io">
{% include "inout/_nav.html" %}
<form class="io-filter" method="get" action="/inout/">
{# 상태 = 링크(다른 거르기 값 유지). 검색 칸 Enter 는 아래 [찾기] — 상태는 숨은 칸 값 그대로 #}
{% set keep = {'factory': filters.factory or '', 'q': filters.q, 'from': filters['from'], 'to': filters['to']} %}
<div class="io-seg" role="group" aria-label="상태">
{% for key, f in status_filters.items() %}
<a href="/inout/?{{ dict(keep, status=key) | urlencode }}" class="io-seg-btn{% if filters.status == key %} is-active{% endif %}"
{% if filters.status == key %}aria-current="true"{% endif %}>{{ f[0] }}</a>
{% endfor %}
</div>
<input type="hidden" name="status" value="{{ filters.status }}" />
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
<option value="">전체 공장</option>
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
</select>
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" /></label>
<span class="erp-muted">~</span>
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
</form>
<div class="erp-card-block">
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr>
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th>
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
</tr></thead>
<tbody>
{% for o in orders %}
{% set active = o.status in ('open', 'partial') %}
<tr class="io-row-link" data-href="/inout/orders/{{ o.id }}">
<td><a href="/inout/orders/{{ o.id }}" class="io-order-no">{{ o.order_no }}</a></td>
<td>{{ o.factory_name }}</td>
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
<td>{{ ymd(o.order_date) }}</td>
<td>{{ due(o.due_date, today, active) }}</td>
<td class="io-num">{{ n(o.summary.ordered) }}</td>
<td class="io-num">{{ n(o.summary.received) }}</td>
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
<td class="io-progress-cell">{{ progress(o.summary) }}</td>
<td class="io-status-cell">{{ order_badge(o.status, o.status_label) }}</td>
{% if perms.super %}
{# 수퍼관리자만 — 완전 삭제(품목·입고 기록·사진·메일 기록까지) #}
<td class="io-col-trash"><form method="post" action="/inout/orders/{{ o.id }}/delete"
data-erp-confirm="{{ o.order_no }} 발주서를 완전히 삭제할까요?{% if o.summary.received %} 입고 {{ n(o.summary.received) }}개 기록과 입고증 사진{% else %} 품목{% endif %}·발주 메일 기록까지 모두 지워지고 되돌릴 수 없습니다.">
<input type="hidden" name="back" value="{{ request.url.path }}{% if request.url.query %}?{{ request.url.query }}{% endif %}" />
<button type="submit" class="io-icon-btn io-del-btn" title="발주 삭제(수퍼관리자)" aria-label="{{ o.order_no }} 발주 삭제">
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg>
</button></form></td>
{% endif %}
</tr>
{% else %}
<tr><td colspan="{{ 11 if perms.super else 10 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
@@ -0,0 +1,256 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %}
{#- 메일 창(발주 메일 · 입고 요청 메일 같은 모양) — 열면 미리보기 GET, [메일 발송]을 눌러야 보낸다(inout.js initMail) -#}
{%- macro mail_dialog(id, title, open_url='', open_title='') -%}
<dialog class="io-dlg io-mail-dlg" id="{{ id }}" aria-labelledby="{{ id }}-title" tabindex="-1"
{%- if open_url %} data-open-url="{{ open_url }}" data-open-title="{{ open_title }}"{% endif %}>
<header class="io-dlg-head">
<h2 id="{{ id }}-title" data-mail-title>{{ title }}</h2>
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
</button>
</header>
<p class="io-dlg-msg" role="status" hidden></p>
<div class="io-dlg-body" data-mail-body><p class="erp-muted">불러오는 중…</p></div>
<footer class="io-dlg-footbar" data-mail-foot hidden>
<button type="button" class="io-link-btn" data-gmail-disconnect>Gmail 연결 끊기</button>
<span class="io-nav-gap"></span>
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
<button type="button" class="erp-btn erp-btn-primary" data-mail-send>메일 발송</button>
</footer>
</dialog>
{%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
{% set receiving = perms.can_receive and can_receive_now %}
{# 전체 입고 완료(모든 품목 입고완료·초과) — 입고 칸·[입고 저장]을 흐리게 막는다(서버도 거절, 2026-10-19). 입고 기록을 지우면 다시 열림 #}
{% set recv_done = order.status in ('done', 'over') %}
{% set dis = ' disabled' if recv_done else '' %}
{% set photo_admin = perms.can_receive and not order.cancelled_at %}
<section class="io">
{% include "inout/_nav.html" %}
<div class="erp-card-block io-head">
<div class="io-head-main">
<div class="io-head-title">
<h2>{{ order.order_no }}</h2>{{ order_badge(order.status, order.status_label) }}
</div>
<dl class="io-head-meta">
<div><dt>공장</dt><dd>{{ order.factory_name }}{% if order.factory_manager or order.factory_contact %}<span class="io-factory-who">{{ order.factory_manager }}{% if order.factory_manager and order.factory_contact %} · {% endif %}{{ order.factory_contact }}</span>{% endif %}</dd></div>
<div><dt>발주일</dt><dd>{{ ymd(order.order_date) }}</dd></div>
<div><dt>입고 예정일</dt><dd>{{ due(order.due_date, today, active) }}</dd></div>
<div><dt>진행</dt><dd>{{ progress(order.summary) }}</dd></div>
<div><dt>발주 메일</dt><dd>{% if order.mails %}{% set last = order.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(last.sent_at) }}</span><span class="io-factory-who">{{ last.sent_by }} → {{ last.to_addrs }}{% if order.mails|length > 1 %} · 모두 {{ order.mails|length }}번{% endif %}</span>{% else %}<span class="erp-muted">아직 안 보냄</span>{% endif %}</dd></div>
{% if order.memo %}<div class="io-wide"><dt>메모</dt><dd>{{ order.memo }}</dd></div>{% endif %}
{% if order.closed_at %}<div class="io-wide"><dt>종결</dt><dd>{{ ymd(order.closed_at) }} · {{ order.closed_by }}{% if order.close_reason %} — {{ order.close_reason }}{% endif %}</dd></div>{% endif %}
{% if order.cancelled_at %}<div class="io-wide"><dt>취소</dt><dd>{{ ymd(order.cancelled_at) }} · {{ order.cancelled_by }}</dd></div>{% endif %}
</dl>
</div>
<div class="io-kpis io-kpis-head">
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">발주</div><div class="erp-summary-value">{{ n(order.summary.ordered) }}</div></div>
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">입고</div><div class="erp-summary-value">{{ n(order.summary.received) }}</div></div>
<div class="erp-summary-card erp-summary-card--mini{% if order.summary.remaining and active %} io-kpi-remaining{% endif %}"><div class="erp-summary-label">미입고</div><div class="erp-summary-value">{{ n(order.summary.remaining) }}</div></div>
{% if order.summary.over %}<div class="erp-summary-card erp-summary-card--mini io-kpi-over"><div class="erp-summary-label">초과</div><div class="erp-summary-value">+{{ n(order.summary.over) }}</div></div>{% endif %}
</div>
{% if perms.can_order and not order.cancelled_at %}
<div class="io-head-actions">
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm io-mail-btn" id="io-mail-btn" data-order="{{ order.id }}"
{% if open_mail %}data-open="1"{% endif %} aria-haspopup="dialog">
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
{% if order.mails %}발주 메일 다시 보내기{% else %}발주 메일 보내기{% endif %}</button>
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/inout/orders/{{ order.id }}/edit">발주서 고치기</a>
{% if order.closed_at %}
<form method="post" action="/inout/orders/{{ order.id }}/reopen"><button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">종결 풀기</button></form>
{% elif order.summary.remaining %}
<form method="post" action="/inout/orders/{{ order.id }}/close" class="io-close-form" data-erp-confirm="남은 미입고 {{ n(order.summary.remaining) }}개를 더 기다리지 않고 종결할까요? 미입고 현황에서 빠집니다.">
<input class="erp-input io-close-reason" type="text" name="reason" maxlength="500" placeholder="종결 사유(선택)" />
<button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">잔량 종결</button>
</form>
{% endif %}
{% if not order.receipts %}
<form method="post" action="/inout/orders/{{ order.id }}/cancel" data-erp-confirm="이 발주서를 취소할까요? (입고 기록이 없을 때만)">
<button class="erp-btn erp-btn-danger erp-btn-sm" type="submit">발주 취소</button>
</form>
{% endif %}
</div>
{% endif %}
</div>
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
<form method="post" action="/inout/orders/{{ order.id }}/receipts" class="erp-card-block io-block" id="io-receipt-form" enctype="multipart/form-data">
{# Enter 키 = 이 버튼(일반 저장). 없으면 폼의 첫 제출 버튼인 [초과 입고로 저장]이 눌려 확인 없이 초과가 저장된다 #}
{% if receiving %}<button type="submit" class="io-default-submit" tabindex="-1" aria-hidden="true"{{ dis }}>입고 저장</button>{% endif %}
<input type="hidden" name="confirm_over" value="" id="io-confirm-over" />
<div class="erp-card-block-head">
<h2>품목</h2>
{% if receiving and recv_done %}<span class="erp-muted io-recv-done-note">✓ 전체 입고 완료 — 더 입고할 수 없습니다(잘못 넣은 입고는 아래 입고 기록에서 지운 뒤 다시 넣으세요)</span>
{% elif receiving %}<span class="erp-muted">물류에 들어온 수량을 [이번 입고]에 넣고 저장 — 여러 번 나눠 넣어도 됩니다</span>
{% elif perms.can_receive and order.closed_at %}<span class="erp-muted">종결된 발주서 — 입고하려면 발주 담당이 종결을 풀어야 합니다</span>{% endif %}
</div>
{% if over %}
<div class="io-over-box" role="alert">
<b>발주보다 많이 입고하려고 합니다.</b> 맞으면 [초과 입고로 저장]을 누르세요.
<ul>{% for o in over %}<li>{% if not items_limited %}<span class="io-code">{{ o.item_code }}</span> {% endif %}{{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
{% if photos_lost %}<p class="io-photo-lost">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>{% endif %}
<button type="submit" class="io-btn-over" name="confirm_over" value="1">초과 입고로 저장</button>
<span class="erp-muted">숫자를 고치려면 아래 칸을 고친 뒤 [입고 저장]</span>
</div>
{% elif photos_lost %}
<p class="io-error">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>
{% endif %}
<div class="erp-table-wrap">
<table class="erp-table io-table">
{# 입고 담당(발주 담당 아님) = 제품 이름·발주 수량(+ 이번 입고)만, 발주 담당 = 단가·금액·PP·은 함께 #}
<thead><tr><th class="io-col-no">#</th>{% if not items_limited %}<th>제품 코드</th>{% endif %}<th>제품</th><th class="io-num">발주</th>
{% if show_prices %}<th class="io-num io-col-money">단가(원)</th><th class="io-num io-col-money">금액(원)</th><th class="io-num io-col-spec">PP(g/개)</th><th class="io-num io-col-spec">은(Ag)</th>{% endif %}
{% if not items_limited %}<th class="io-num">입고</th><th class="io-num">미입고</th><th>상태</th>{% endif %}
{% if receiving %}<th class="io-col-recv">이번 입고</th>{% endif %}</tr></thead>
<tbody>
{% for ln in order.lines %}
<tr>
<td class="io-col-no">{{ loop.index }}</td>
{% if not items_limited %}<td class="io-code">{{ ln.item_code }}</td>{% endif %}
<td>{{ ln.item_name }}{% if ln.memo %}<div class="erp-row-sub">{{ ln.memo }}</div>{% endif %}</td>
<td class="io-num">{{ n(ln.qty) }}</td>
{% if show_prices %}
{% set amt = line_amount(ln.qty, ln.unit_price) %}{% set ag = silver_g(ln.weight_g, ln.silver_pct) %}
<td class="io-num io-col-money">{{ fmt_num(ln.unit_price) if ln.unit_price is not none else '-' }}</td>
<td class="io-num io-col-money">{{ fmt_num(amt) if amt is not none else '-' }}</td>
<td class="io-num io-col-spec">{{ fmt_num(ln.weight_g) if ln.weight_g is not none else '-' }}</td>
<td class="io-num io-col-spec">{% if ln.silver_pct is not none %}{{ fmt_num(ln.silver_pct, 4) }}%{% if ag is not none %}<div class="erp-row-sub">{{ fmt_num(ag, 4) }}g/개</div>{% endif %}{% else %}-{% endif %}</td>
{% endif %}
{% if not items_limited %}
<td class="io-num">{{ n(ln.received) }}</td>
<td class="io-num{% if ln.remaining and active %} io-remaining{% endif %}">{{ n(ln.remaining) }}{% if ln.over %}<div class="io-over-sub">초과 +{{ n(ln.over) }}</div>{% endif %}</td>
<td>{{ status_badge(ln.status, ln.status_label) }}</td>
{% endif %}
{% if receiving %}<td class="io-col-recv"><input class="erp-input io-qty io-recv" type="text" inputmode="numeric" name="qty_{{ ln.id }}"
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" data-ordered="{{ ln.qty }}" data-received="{{ ln.received }}"
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining and not items_limited else '' }}"
aria-label="{{ ln.item_name }} 이번 입고 수량"{{ dis }} /></td>{% endif %}
</tr>
{% endfor %}
</tbody>
{% if show_prices and order.lines %}
<tfoot><tr class="io-total-row">
<td colspan="3">합계</td>
<td class="io-num">{{ n(order.summary.ordered) }}</td>
<td class="io-num io-col-money"></td>
<td class="io-num io-col-money"><b>{{ fmt_num(totals.amount) if totals.amount is not none else '-' }}</b>{% if totals.missing_price %}<div class="erp-row-sub">단가 미입력 {{ totals.missing_price }}종 제외</div>{% endif %}</td>
<td class="io-num io-col-spec">{% if totals.pp_kg is not none %}{{ fmt_num(totals.pp_kg, 3) }}kg{% else %}-{% endif %}</td>
<td class="io-num io-col-spec">{% if totals.silver_g is not none %}{{ fmt_num(totals.silver_g, 2) }}g{% else %}-{% endif %}</td>
{% if not items_limited %}<td colspan="3"></td>{% endif %}
{% if receiving %}<td></td>{% endif %}
</tr></tfoot>
{% endif %}
</table>
</div>
{% if receiving %}
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required{{ dis }} /></label>
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
<div class="erp-field io-photo-field">
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
<label class="io-photo-pick">
<input type="file" name="photos" accept="image/*" multiple id="io-photo-input" class="io-photo-input" data-max="{{ max_photos }}"{{ dis }} />
<svg class="io-photo-pick-icon" viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
입고증 업로드
</label>
</div>
<button type="button" class="erp-btn erp-btn-outline" id="io-fill-remaining"{{ dis }}>남은 수량 모두 채우기</button>
<button type="submit" class="erp-btn erp-btn-primary io-recv-save"{{ dis }}>입고 저장 <span id="io-recv-total"></span></button>
<div class="io-photo-previews" id="io-photo-previews" aria-live="polite"></div>
</div>
{% endif %}
</form>
<div class="erp-card-block io-block">
<div class="erp-card-block-head"><h2>입고 기록</h2><span class="erp-muted">{{ order.receipts|length }}회</span></div>
{% if order.receipts %}
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th><th>입고 요청 메일 · 사방넷</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
<tbody>
{% for r in order.receipts %}
<tr>
<td>{{ ymd(r.receipt_date) }}{% if r.memo %}<div class="erp-row-sub">{{ r.memo }}</div>{% endif %}</td>
<td>{% for x in r.lines %}<span class="io-chip">{% if items_limited %}{{ x.item_name }}{% else %}<span class="io-code">{{ x.item_code }}</span>{% endif %} {{ n(x.qty) }}</span>{% endfor %}</td>
<td class="io-num">{{ n(r.total) }}</td>
<td class="io-photos-cell">
{% for ph in r.photos %}
<button type="button" class="io-thumb" data-photo="{{ ph.id }}" data-receipt="{{ r.id }}" data-type="{{ ph.content_type }}"
data-name="{{ ph.filename }}" title="{{ ph.filename }} — 크게 보기" aria-label="입고증 사진 크게 보기 {{ loop.index }}">
{% if ph.content_type == 'image/heic' %}<span class="io-thumb-heic">HEIC</span>{% else %}<img src="/inout/photos/{{ ph.id }}" alt="" loading="lazy" />{% endif %}
</button>
{% endfor %}
{% if photo_admin and r.photos|length < max_photos %}
<form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/photos" enctype="multipart/form-data" class="io-add-photo-form">
<label class="io-thumb io-thumb-add" title="입고증 사진 더하기">
<input type="file" name="photos" accept="image/*" multiple class="io-photo-input io-photo-auto" data-max="{{ max_photos - r.photos|length }}" aria-label="입고증 사진 더하기" />
<span aria-hidden="true">+</span>
</label>
</form>
{% elif not r.photos %}<span class="erp-muted">-</span>{% endif %}
</td>
<td class="erp-muted">{{ r.created_by }}<div class="erp-row-sub">{{ ymdhm(r.created_at) }}</div></td>
<td class="io-rmail-cell">
{% if r.mails %}{% set lm = r.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(lm.sent_at) }}</span>
<div class="erp-row-sub">{{ lm.sent_by }}{% if r.mails|length > 1 %} · 모두 {{ r.mails|length }}번{% endif %}</div>{% endif %}
{% if perms.can_receive %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-rmail-btn" aria-haspopup="dialog"
data-url="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/mail" data-title="입고 요청 메일 · {{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개">
{% if r.mails %}다시 보내기{% else %}보내기{% endif %}</button>
{% elif not r.mails %}<span class="erp-muted">-</span>{% endif %}
{% if perms.can_order or perms.can_receive %}
<a class="erp-btn erp-btn-outline erp-btn-sm io-sabang-btn" href="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/sabangnet.xlsx"
title="사방넷 입고 엑셀 — 상품코드(사방넷 코드)·가용수량(입고 수량)·불용수량(상품 이름)" download>사방넷 입고 파일</a>
{% endif %}
</td>
{% if photo_admin %}
<td><form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/delete"
data-erp-confirm="{{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 되고 입고증 사진도 지워집니다.">
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">지우기</button></form></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="erp-empty">아직 입고된 것이 없습니다.</p>
{% endif %}
</div>
{# 입고증 사진 크게 보기 — 앞뒤 넘기기(←/→), 원본 열기, 지우기(입고 담당) #}
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
<div class="io-viewer-bar">
<span class="io-viewer-title" id="io-viewer-title"></span>
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
</div>
<button type="button" class="io-viewer-nav is-prev" data-step="-1" aria-label="이전 사진">‹</button>
<img class="io-viewer-img" id="io-viewer-img" alt="입고증 사진" />
<p class="io-viewer-heic" id="io-viewer-heic" hidden>HEIC 사진은 이 브라우저에서 미리 볼 수 없습니다 — [원본]으로 내려받으세요.</p>
<button type="button" class="io-viewer-nav is-next" data-step="1" aria-label="다음 사진">›</button>
</dialog>
{% if perms.can_order and not order.cancelled_at %}
{# 발주 메일 — 열면 GET /inout/orders/{id}/mail 로 미리보기, [메일 발송]을 눌러야 보낸다(발주 담당 본인 Gmail) #}
{{ mail_dialog('io-mail', '발주 메일 보내기 · ' ~ order.order_no) }}
{% endif %}
{% if perms.can_receive and order.receipts %}
{# 입고 요청 메일(005) — 물류센터 입고 담당자에게 전산 등록 부탁(입고 담당 본인 Gmail). 입고 저장 뒤 ?rmail={입고 id} 면 바로 연다 #}
{% set open_r = order.receipts | selectattr('id', 'equalto', open_rmail) | list if open_rmail else [] %}
{% if open_r %}
{{ mail_dialog('io-rmail', '입고 요청 메일', '/inout/orders/' ~ order.id ~ '/receipts/' ~ open_r[0].id ~ '/mail',
'입고 요청 메일 · ' ~ ymd(open_r[0].receipt_date) ~ ' 입고 ' ~ n(open_r[0].total) ~ '개') }}
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
@@ -0,0 +1,83 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
{% block content %}
<section class="io">
{% include "inout/_nav.html" %}
<form class="erp-card-block io-order-form" method="post" id="io-order-form"
action="{% if order %}/inout/orders/{{ order.id }}/edit{% else %}/inout/orders/new{% endif %}">
<div class="erp-card-block-head">
<h2>{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}</h2>
<span class="erp-muted">{% if from_catalog %}제품은 옵션 → 상품 정보의 단품에서 고릅니다(단가 함께){% else %}제품은 코드표의 단품에서 고릅니다{% endif %}</span>
</div>
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
{% if not items_enabled %}<div class="io-error" role="alert">제품을 고를 목록이 없습니다 — 관리자가 옵션 → 상품 정보에서 단품을 불러오거나 코드표 DB(ITEMCODE_DB_URL)를 연결해야 합니다.</div>{% endif %}
<div class="erp-form-grid">
<label class="erp-field"><span>공장 *</span>
<select name="factory_id" required>
<option value="">공장 고르기</option>
{% for f in factories %}<option value="{{ f.id }}" {% if vals.factory_id|string == f.id|string %}selected{% endif %}>{{ f.name }}</option>{% endfor %}
</select>
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
</label>
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" required /></label>
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" /></label>
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
</div>
<div class="erp-table-wrap">
<table class="erp-table io-table io-lines" id="io-lines">
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th><th>줄 메모</th><th class="io-col-del"></th></tr></thead>
<tbody>
{% for ln in lines %}
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}">
<td class="io-col-no"></td>
<td class="io-item-cell">
<input type="hidden" name="item_code" value="{{ ln.code }}" />
<input type="hidden" name="item_name" value="{{ ln.name }}" />
<input class="erp-input io-item-search" type="text" value="{{ ln.code }}{% if ln.name %} · {{ ln.name }}{% endif %}" autocomplete="off"
placeholder="코드 또는 이름" {% if received %}readonly title="입고된 제품은 바꿀 수 없습니다(수량은 바꿀 수 있음)"{% endif %} />
{% if received %}<div class="erp-row-sub">입고 {{ '{:,}'.format(received) }}개 — 제품은 그대로, 수량만 바꿀 수 있습니다</div>{% endif %}
</td>
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" /></td>
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
<td class="io-col-money io-amount">-</td>
<td><input class="erp-input" type="text" name="line_memo" value="{{ ln.memo }}" maxlength="500" /></td>
<td class="io-col-del">{% if not received %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
<tfoot><tr><td colspan="7">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-add-line">+ 제품 줄 추가</button>
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종 · 금액 <b id="io-total-amount">0</b>원<span id="io-total-noprice"></span></span>
</td></tr></tfoot>
</table>
</div>
<template id="io-line-tpl">
<tr class="io-line">
<td class="io-col-no"></td>
<td class="io-item-cell">
<input type="hidden" name="item_code" value="" />
<input type="hidden" name="item_name" value="" />
<input class="erp-input io-item-search" type="text" value="" autocomplete="off" placeholder="코드 또는 이름" />
</td>
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" /></td>
<td class="io-col-money io-price">-</td>
<td class="io-col-money io-amount">-</td>
<td><input class="erp-input" type="text" name="line_memo" value="" maxlength="500" /></td>
<td class="io-col-del"><button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button></td>
</tr>
</template>
<div class="io-form-actions">
<a class="erp-btn erp-btn-outline" href="{% if order %}/inout/orders/{{ order.id }}{% else %}/inout/{% endif %}">취소</a>
<button type="submit" class="erp-btn erp-btn-primary">{% if order %}고친 내용 저장{% else %}발주서 저장{% endif %}</button>
</div>
</form>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
@@ -0,0 +1,91 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
{% block content %}
<section class="io">
{% include "inout/_nav.html" %}
<form class="io-filter" method="get" action="/inout/pending">
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
<option value="">전체 공장</option>
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
</select>
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="제품 코드·제품 이름·발주번호" />
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
<span class="io-nav-gap"></span>
<span class="erp-muted">진행 중인 발주(종결·취소 제외)의 남은 수량</span>
</form>
<div class="io-kpis">
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 수량</div><div class="erp-summary-value">{{ n(total_remaining) }}</div></div>
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 제품</div><div class="erp-summary-value">{{ n(items|length) }}종</div></div>
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 발주 줄</div><div class="erp-summary-value">{{ n(rows|length) }}</div></div>
<div class="erp-summary-card erp-summary-card--mini{% if over %} io-kpi-over{% endif %}"><div class="erp-summary-label">초과 입고</div><div class="erp-summary-value">{{ n(over|length) }}건</div></div>
</div>
<div class="erp-card-block io-block">
<div class="erp-card-block-head"><h2>제품별 미입고 합계</h2><span class="erp-muted">여러 발주에 걸친 남은 수량을 제품마다 더한 값</span></div>
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr><th>제품 코드</th><th>제품</th><th class="io-num">미입고</th><th class="io-num">발주 건수</th><th>가장 이른 입고 예정일</th></tr></thead>
<tbody>
{% for it in items %}
<tr>
<td class="io-code">{{ it.item_code }}</td><td>{{ it.item_name }}</td>
<td class="io-num io-remaining">{{ n(it.remaining) }}</td><td class="io-num">{{ it.orders }}</td>
<td>{{ due(it.earliest_due, today, True) }}</td>
</tr>
{% else %}
<tr><td colspan="5" class="erp-empty">미입고된 제품이 없습니다. 모두 들어왔습니다.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% if rows %}
<div class="erp-card-block io-block">
<div class="erp-card-block-head"><h2>발주별 미입고</h2><span class="erp-muted">입고 예정일이 이른 순 — 지난 것은 빨강</span></div>
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr><th>입고 예정일</th><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th>
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th></tr></thead>
<tbody>
{% for r in rows %}
<tr class="io-row-link{% if r.due_date and r.due_date < today %} is-late{% endif %}" data-href="/inout/orders/{{ r.order_id }}">
<td>{{ due(r.due_date, today, True) }}</td>
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a><div class="erp-row-sub">발주 {{ ymd(r.order_date) }}</div></td>
<td>{{ r.factory_name }}</td><td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td>
<td class="io-num io-remaining">{{ n(r.remaining) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
{% if over %}
<div class="erp-card-block io-block io-block-over">
<div class="erp-card-block-head"><h2>초과 입고</h2><span class="erp-muted">발주보다 많이 들어온 제품 — 공장과 확인이 필요합니다</span></div>
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th><th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">초과</th></tr></thead>
<tbody>
{% for r in over %}
<tr class="io-row-link" data-href="/inout/orders/{{ r.order_id }}">
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a></td><td>{{ r.factory_name }}</td>
<td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td><td class="io-num io-over">+{{ n(r.over) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
+9
View File
@@ -0,0 +1,9 @@
# [말레이시아재고] 말레이시아 창고 재고관리 — `app/modules/malaysia/`, `malaysia_stock_db`
> 이 모듈만 고칠 때 읽는 요약. 상세는 같은 폴더 `README.md`.
> 정적 파일: `app/static/malaysia.js`, `malaysia_rack.js`, `malaysia_rack_view.js`. 템플릿: `templates/`.
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`). 세트 BOM 이 "누락"이면 `itemcode_ro` 의 `set_components` SELECT 권한부터 점검.
- 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트 → 낱개 자동 분해), 현재고 현황.
- 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`).
- 권한키 `malaysia`.
+11
View File
@@ -0,0 +1,11 @@
# [공지] 긴급 공지 모듈 — `app/modules/notice/`, `project_db`(마이그레이션 024 `urgent_notice*`)
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/NOTICE_MODULE.md`.
> 정적 파일: `app/static/erp-notice.js`, `erp-notice.css`, `erp-notice-admin.js`.
- 수퍼관리자만 작성(`/notice/`, 진입 = ERP 왼쪽 아래 · Project ⚙ 옵션).
- 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람.
- ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에
[확인] 누를 때까지 표시(Esc·바깥 클릭 무시), 확인 기록.
- 연결 풀은 `ProjectStore.pool` 공유(→ Project 모듈 DB 변경 시 영향 확인), 새 환경변수 없음.
- PC 알림 프로그램은 아직 미지원.
+23
View File
@@ -0,0 +1,23 @@
"""긴급 공지 — ERP 전체 화면 가운데에 띄우는 공지(2026-10-12).
- 라우터: `router.py` (prefix=/notice) — 만들기·고치기는 수퍼관리자만, 받기·[확인]은 로그인 사용자 누구나
- 저장소: `db.py` (project_db 마이그레이션 024 의 urgent_notice* 표 — 프로젝트 저장소의 연결 풀을 같이 쓴다)
- 검증: `store.py`
- 화면: 관리 `templates/notice/admin.html` + `static/erp-notice-admin.js`, 표시 `static/erp-notice.js`(erp_base.html 공용)
상세는 docs/NOTICE_MODULE.md.
"""
from typing import Any
from .router import router
__all__ = ["router", "build_notice_store"]
def build_notice_store(project_store: Any) -> Any:
"""프로젝트 저장소(PROJECT_DB_URL)가 있으면 그 연결 풀로 NoticeStore, 없으면 None(공지 API 는 503)."""
if project_store is None:
return None
from .db import NoticeStore # noqa: WPS433
return NoticeStore(project_store.pool)
+238
View File
@@ -0,0 +1,238 @@
"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from psycopg import errors as psycopg_errors
from app.modules.project import store as pj_store
from app.timezone import KST
from . import store
def _iso(v: Any) -> str:
return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else ""
def _version(v: Any) -> str:
"""공지 내용 버전 = updated_at(마이크로초까지, UTC) — 고치기·취소 때마다 바뀐다. 받는 사람 화면이 바뀐 내용을 다시 그리고,
[확인]이 어느 내용을 읽고 누른 것인지 서버가 가린다(2026-10-15 검토 F07)."""
return v.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S%f") if isinstance(v, datetime) else ""
class NoticeStore:
def __init__(self, pool: Any) -> None:
self._pool = pool
def _conn(self) -> Any:
return self._pool.connection()
@staticmethod
def _run(fn: Any) -> Any:
try:
return fn()
except psycopg_errors.UndefinedTable:
raise store.NoticeMigrationNeeded()
# ── 읽기 ────────────────────────────────────────────────
@staticmethod
def _row(r: dict[str, Any]) -> dict[str, Any]:
return {
"id": int(r["id"]), "title": r["title"], "body_html": r["body_html"],
"show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]),
"created_by": r["created_by"], "created_at": _iso(r["created_at"]),
"updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")),
"version": _version(r.get("updated_at")),
"cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "",
}
def list_notices(self, *, limit: int = 200) -> list[dict[str, Any]]:
"""관리 화면 — 최근 것부터. 받는 사람·확인한 사람 목록을 함께."""
def run() -> list[dict[str, Any]]:
with self._conn() as conn:
rows = conn.execute("SELECT * FROM urgent_notices ORDER BY show_at DESC, id DESC LIMIT %s",
(int(limit),)).fetchall()
ids = [int(r["id"]) for r in rows]
targets: dict[int, list[str]] = {i: [] for i in ids}
acks: dict[int, dict[str, str]] = {i: {} for i in ids}
if ids:
for t in conn.execute("SELECT notice_id, user_email FROM urgent_notice_targets "
"WHERE notice_id = ANY(%s) ORDER BY user_email", (ids,)).fetchall():
targets[int(t["notice_id"])].append(t["user_email"])
for a in conn.execute("SELECT notice_id, user_email, acked_at FROM urgent_notice_acks "
"WHERE notice_id = ANY(%s) ORDER BY acked_at", (ids,)).fetchall():
acks[int(a["notice_id"])][a["user_email"]] = _iso(a["acked_at"])
return [{**self._row(r), "targets": targets[int(r["id"])], "acks": acks[int(r["id"])]} for r in rows]
return self._run(run)
def pending_for(self, *, email: str, now: datetime | None = None) -> list[dict[str, Any]]:
"""이 사람이 지금 봐야 할 공지 — 취소 안 됨·띄울 시각이 지남·받는 사람(전체 또는 지정)·아직 [확인] 안 함. 오래된 것부터."""
em = pj_store.norm_str(email, lower=True)
def run() -> list[dict[str, Any]]:
with self._conn() as conn:
rows = conn.execute(
"SELECT n.* FROM urgent_notices n "
"WHERE n.cancelled_at IS NULL AND n.show_at <= %s "
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
" AND NOT EXISTS (SELECT 1 FROM urgent_notice_acks a WHERE a.notice_id = n.id AND a.user_email = %s) "
"ORDER BY n.show_at ASC, n.id ASC LIMIT 20",
(now or datetime.now(KST), em, em),
).fetchall()
return [self._row(r) for r in rows]
return self._run(run)
def get_notice(self, *, notice_id: int) -> dict[str, Any] | None:
def run() -> dict[str, Any] | None:
with self._conn() as conn:
r = conn.execute("SELECT * FROM urgent_notices WHERE id = %s", (notice_id,)).fetchone()
if r is None:
return None
t = [x["user_email"] for x in conn.execute(
"SELECT user_email FROM urgent_notice_targets WHERE notice_id = %s ORDER BY user_email",
(notice_id,)).fetchall()]
return {**self._row(r), "targets": t}
return self._run(run)
def is_recipient(self, *, notice: dict[str, Any], email: str) -> bool:
em = pj_store.norm_str(email, lower=True)
return bool(notice["to_all"]) or em in notice.get("targets", [])
# ── 쓰기 ────────────────────────────────────────────────
def _link_images(self, conn: Any, notice_id: int, body: str, by: str) -> None:
"""본문에 든 이미지를 이 공지에 묶는다 — 내가 올린, 아직 어느 공지에도 안 묶인 이미지만(남의 공지 이미지 가로채기 방지)."""
ids = store.image_ids_in(body)
if ids:
conn.execute("UPDATE urgent_notice_images SET notice_id = %s "
"WHERE id = ANY(%s) AND notice_id IS NULL AND uploaded_by = %s", (notice_id, ids, by))
# 하루 넘게 어느 공지에도 안 묶인 이미지(올렸다가 저장 안 함)는 정리
conn.execute("DELETE FROM urgent_notice_images WHERE notice_id IS NULL AND created_at < now() - interval '1 day'")
def create_notice(self, *, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any, by: str) -> dict[str, Any]:
ttl = store.validate_title(title)
html = store.sanitize_body(body)
when = store.parse_show_at(show_at)
all_, emails = store.validate_targets(to_all, targets)
who = pj_store.norm_str(by, lower=True)
def run() -> int:
with self._conn() as conn:
with conn.transaction():
nid = int(conn.execute(
"INSERT INTO urgent_notices (title, body_html, show_at, to_all, created_by, updated_by) "
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", (ttl, html, when, all_, who, who),
).fetchone()["id"])
for em in emails:
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
"ON CONFLICT DO NOTHING", (nid, em))
self._link_images(conn, nid, html, who)
return nid
return self.get_notice(notice_id=self._run(run)) # type: ignore[return-value]
def update_notice(self, *, notice_id: int, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any,
by: str, reshow: bool = False) -> dict[str, Any]:
"""고치기 — 받는 사람·시각·내용 전부. reshow=True 면 이미 [확인]한 사람에게도 다시 띄운다(확인 기록 지움)."""
ttl = store.validate_title(title)
html = store.sanitize_body(body)
when = store.parse_show_at(show_at)
all_, emails = store.validate_targets(to_all, targets)
who = pj_store.norm_str(by, lower=True)
def run() -> None:
with self._conn() as conn:
with conn.transaction():
row = conn.execute("UPDATE urgent_notices SET title=%s, body_html=%s, show_at=%s, to_all=%s, "
"updated_by=%s, updated_at=now() WHERE id=%s RETURNING id",
(ttl, html, when, all_, who, notice_id)).fetchone()
if row is None:
raise KeyError(notice_id)
conn.execute("DELETE FROM urgent_notice_targets WHERE notice_id = %s", (notice_id,))
for em in emails:
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
"ON CONFLICT DO NOTHING", (notice_id, em))
if reshow:
conn.execute("DELETE FROM urgent_notice_acks WHERE notice_id = %s", (notice_id,))
self._link_images(conn, notice_id, html, who)
self._run(run)
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
def cancel_notice(self, *, notice_id: int, by: str, cancel: bool = True) -> dict[str, Any]:
"""취소(더 띄우지 않음) · 취소 되돌리기. 기록은 남는다."""
def run() -> None:
with self._conn() as conn:
row = conn.execute(
"UPDATE urgent_notices SET cancelled_at = CASE WHEN %s THEN now() ELSE NULL END, "
"cancelled_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() WHERE id = %s RETURNING id",
(cancel, cancel, pj_store.norm_str(by, lower=True), notice_id),
).fetchone()
if row is None:
raise KeyError(notice_id)
self._run(run)
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
def ack(self, *, notice_id: int, email: str, version: str | None = None, now: datetime | None = None) -> str:
"""[확인] — 결과: "acked"(처음) · "already"(이미 확인 — 여러 번 눌러도 한 번) · "stale"(그 사이 내용이 바뀜 — 읽은
version 이 지금과 다름) · "denied"(받는 사람이 아님·띄울 시각 전·취소·없음).
받는 사람·표시 시각·취소 확인과 기록이 **한 트랜잭션**(2026-10-15 검토 F08): 공지 행을 FOR SHARE 로 잠그고 조건을 본 뒤
기록한다 — 동시에 취소·고치기가 들어오면 그 쪽이 먼저 끝나거나(그러면 바뀐 행으로 다시 판정) 이 기록 뒤로 기다린다.
version 이 없으면(예전 화면) 내용 확인은 건너뛴다."""
em = pj_store.norm_str(email, lower=True)
def run() -> str:
with self._conn() as conn:
with conn.transaction():
n = conn.execute(
"SELECT n.id, n.updated_at FROM urgent_notices n "
"WHERE n.id = %s AND n.cancelled_at IS NULL AND n.show_at <= %s "
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
"FOR SHARE OF n",
(notice_id, now or datetime.now(KST), em),
).fetchone()
if n is None:
return "denied"
done = conn.execute("SELECT 1 FROM urgent_notice_acks WHERE notice_id = %s AND user_email = %s",
(notice_id, em)).fetchone()
if done is not None:
return "already"
if version and version != _version(n["updated_at"]):
return "stale"
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
"ON CONFLICT DO NOTHING RETURNING notice_id", (notice_id, em)).fetchone()
return "acked" if r is not None else "already"
return self._run(run)
# ── 이미지 ──────────────────────────────────────────────
def add_image(self, *, data: bytes, filename: str, by: str) -> dict[str, Any]:
ctype = store.sniff_image(data)
def run() -> int:
with self._conn() as conn:
return int(conn.execute(
"INSERT INTO urgent_notice_images (filename, content_type, size_bytes, data, uploaded_by) "
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
(pj_store.norm_str(filename)[:200], ctype, len(data), data, pj_store.norm_str(by, lower=True)),
).fetchone()["id"])
iid = self._run(run)
return {"id": iid, "url": f"/notice/images/{iid}", "content_type": ctype}
def get_image(self, *, image_id: int) -> dict[str, Any] | None:
def run() -> dict[str, Any] | None:
with self._conn() as conn:
r = conn.execute("SELECT id, notice_id, content_type, data, uploaded_by FROM urgent_notice_images "
"WHERE id = %s", (image_id,)).fetchone()
return dict(r) if r else None
return self._run(run)
def enabled(self) -> bool:
try:
with self._conn() as conn:
return bool(conn.execute("SELECT to_regclass('public.urgent_notices') AS r").fetchone()["r"])
except Exception: # noqa: BLE001
return False
+188
View File
@@ -0,0 +1,188 @@
"""긴급 공지 라우터(/notice) — ERP 전체 화면 가운데 공지.
- 만들기·고치기·취소·이미지 올리기·확인 현황: 수퍼관리자(app.store.SUPER_ADMIN_EMAIL)만.
- 받기(GET /notice/api/pending)·[확인]: 로그인한 등록 사용자 누구나 — 모듈 권한과 무관(ERP 전체 공지).
- 저장: project_db 024(urgent_notice*). PROJECT_DB_URL 이 없거나 024 미적용이면 503(화면 스크립트는 조용히 멈춘다).
- 핸들러는 동기 DB 라 def(프로젝트 라우터와 같은 이유).
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, Response
from . import store
router = APIRouter(prefix="/notice", tags=["notice"])
_MIGRATION_MSG = "긴급 공지 기능이 아직 준비되지 않았습니다(project_db 마이그레이션 024 필요)."
def _user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
return user
def _is_super(user: dict[str, Any]) -> bool:
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
return str(user.get("email") or "").strip().lower() == SUPER_ADMIN_EMAIL
def _super(request: Request) -> dict[str, Any]:
user = _user(request)
if not _is_super(user):
raise HTTPException(status_code=403, detail="긴급 공지는 수퍼관리자만 만들 수 있습니다.")
return user
def _store(request: Request) -> Any:
st = getattr(request.app.state, "notice_store", None)
if st is None:
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
return st
def _call(fn: Any, **kw: Any) -> Any:
try:
return fn(**kw)
except store.NoticeMigrationNeeded:
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError:
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
def _public(n: dict[str, Any]) -> dict[str, Any]:
"""받는 사람 화면에 보내는 값 — 받는 사람 목록·확인 현황은 빼고."""
return {k: n.get(k, "") for k in ("id", "title", "body_html", "show_at", "created_by", "version")}
# ── 화면 ─────────────────────────────────────────────────────
@router.get("/", response_class=HTMLResponse)
def notice_admin_page(request: Request) -> HTMLResponse:
"""긴급 공지 관리 — 수퍼관리자만. 목록(예약·표시 중·취소)·확인 현황·새 공지."""
from app.main import build_erp_nav, render_template, user_store # noqa: WPS433
from app.store import is_admin # noqa: WPS433
user = _super(request)
st = getattr(request.app.state, "notice_store", None)
enabled = bool(st) and st.enabled()
# 받는 사람 후보 = 등록 사용자 전원 — 프로젝트 멤버 고르기와 같은 모양(아이콘 + 이름)으로 그린다(project.js memberPickHtml)
people = sorted(
({"email": u["email"], "id": u["email"].split("@")[0], "name": u.get("name") or u["email"].split("@")[0],
"avatar": u.get("picture") or ""} for u in user_store.list_all()),
key=lambda p: p["id"],
)
return render_template(request, "notice/admin.html", {
"user": user, "is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active=""),
"page_title": "긴급 공지", "page_subtitle": "정한 시각에 받는 사람 화면 가운데에 띄웁니다([확인] 전까지)",
"enabled": enabled, "people": people,
})
# ── 받는 사람 ────────────────────────────────────────────────
@router.get("/api/pending")
def api_pending(request: Request) -> JSONResponse:
"""지금 내가 봐야 할 공지(띄울 시각이 지났고 아직 [확인] 안 한 것, 오래된 것부터)."""
user = _user(request)
st = _store(request)
rows = _call(st.pending_for, email=user["email"])
return JSONResponse({"notices": [_public(n) for n in rows]})
@router.post("/api/{notice_id}/ack")
def api_ack(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""[확인] — 받는 사람이고 띄울 시각이 지난, 취소 안 된 공지만(검증과 기록을 저장소가 한 트랜잭션에서, 검토 F08).
여러 번 눌러도 한 번 기록. payload.version = 화면에 띄운 내용의 버전 — 그 사이 고쳐졌으면 409(바뀐 내용을 다시 읽게, F07)."""
user = _user(request)
st = _store(request)
version = str((payload or {}).get("version") or "").strip() or None
result = _call(st.ack, notice_id=notice_id, email=user["email"], version=version)
if result == "denied":
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
if result == "stale":
raise HTTPException(status_code=409, detail="공지 내용이 수정되었습니다. 바뀐 내용을 확인한 뒤 다시 [확인]을 눌러 주세요.")
return JSONResponse({"ok": True, "result": result})
@router.get("/images/{image_id}")
def notice_image(request: Request, image_id: int) -> Response:
"""공지 본문 이미지 — 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난 공지)만."""
from datetime import datetime # noqa: WPS433
from app.timezone import KST # noqa: WPS433
user = _user(request)
st = _store(request)
img = _call(st.get_image, image_id=image_id)
if img is None:
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
if not _is_super(user):
n = _call(st.get_notice, notice_id=int(img["notice_id"])) if img["notice_id"] else None
if (n is None or n["cancelled_at"] or not st.is_recipient(notice=n, email=user["email"])
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST)):
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
return Response(content=bytes(img["data"]), media_type=img["content_type"], headers={
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=3600",
"Content-Security-Policy": "default-src 'none'; img-src 'self'; sandbox",
})
# ── 수퍼관리자 ───────────────────────────────────────────────
@router.get("/api/notices")
def api_list(request: Request) -> JSONResponse:
_super(request)
st = _store(request)
return JSONResponse({"notices": _call(st.list_notices)})
def _fields(payload: dict[str, Any]) -> dict[str, Any]:
return {"title": payload.get("title"), "body": payload.get("body_html") or "",
"show_at": payload.get("show_at"), "to_all": payload.get("to_all", True),
"targets": payload.get("targets") or []}
@router.post("/api/notices")
def api_create(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _super(request)
st = _store(request)
n = _call(st.create_notice, **_fields(payload), by=user["email"])
return JSONResponse({"notice": n}, status_code=201)
@router.put("/api/notices/{notice_id}")
def api_update(request: Request, notice_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""고치기 — reshow=true 면 이미 [확인]한 사람에게도 다시 띄운다."""
user = _super(request)
st = _store(request)
n = _call(st.update_notice, notice_id=notice_id, **_fields(payload), by=user["email"],
reshow=payload.get("reshow") is True)
return JSONResponse({"notice": n})
@router.post("/api/notices/{notice_id}/cancel")
def api_cancel(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""취소(더 띄우지 않음) {cancel: true} · 되돌리기 {cancel: false}."""
user = _super(request)
st = _store(request)
n = _call(st.cancel_notice, notice_id=notice_id, by=user["email"], cancel=payload.get("cancel", True) is not False)
return JSONResponse({"notice": n})
@router.post("/api/images")
def api_upload_image(request: Request, file: UploadFile = File(...)) -> JSONResponse:
"""본문 이미지 올리기 — 저장(공지 만들기·고치기) 때 본문에 든 것만 그 공지에 묶인다."""
user = _super(request)
st = _store(request)
data = file.file.read(store.IMAGE_MAX_BYTES + 1)
img = _call(st.add_image, data=data, filename=file.filename or "image", by=user["email"])
return JSONResponse({"image": img}, status_code=201)
+106
View File
@@ -0,0 +1,106 @@
"""긴급 공지 — 순수 검증(DB 없음). 저장은 db.py, 화면·권한은 router.py."""
from __future__ import annotations
import re
from datetime import datetime
from typing import Any
from app.modules.project import store as pj_store
from app.timezone import KST
TITLE_MAX = 200
BODY_MAX = 100_000 # 정리한 HTML 기준(이미지는 주소만 들어간다)
IMAGE_MAX_BYTES = 10 * 1024 * 1024
TARGETS_MAX = 500
# 이미지 형식은 올린 쪽이 정한 Content-Type 이 아니라 파일 앞 바이트로 정한다(svg·html 은 받지 않는다).
_MAGIC: tuple[tuple[bytes, str], ...] = (
(b"\x89PNG\r\n\x1a\n", "image/png"),
(b"\xff\xd8\xff", "image/jpeg"),
(b"GIF87a", "image/gif"),
(b"GIF89a", "image/gif"),
)
_IMG_SRC_OK = re.compile(r"^/notice/images/(\d+)$")
_IMG_TAG = re.compile(r"<img\b[^>]*>", re.IGNORECASE)
_SRC_ATTR = re.compile(r"""\bsrc\s*=\s*"([^"]*)\"""", re.IGNORECASE)
class NoticeMigrationNeeded(Exception):
"""project_db 024 미적용."""
def validate_title(v: Any) -> str:
t = pj_store.norm_str(v)
if not t:
raise ValueError("공지 제목을 입력하세요.")
if len(t) > TITLE_MAX:
raise ValueError(f"제목은 {TITLE_MAX}자 이하로 입력하세요.")
return t
def sanitize_body(html: Any) -> str:
"""작업 설명란과 같은 허용 목록으로 정리한 뒤, 이미지는 공지 이미지 주소(/notice/images/{id})만 남긴다
(외부 주소·data: 이미지는 뺀다 — 받는 사람 화면에서 다른 곳으로 요청이 나가지 않게)."""
out = pj_store.sanitize_description_html(str(html or ""))
def keep(m: re.Match[str]) -> str:
src = _SRC_ATTR.search(m.group(0))
return m.group(0) if src and _IMG_SRC_OK.match(src.group(1)) else ""
out = _IMG_TAG.sub(keep, out)
if len(out) > BODY_MAX:
raise ValueError("내용이 너무 깁니다.")
return out
def image_ids_in(html: str) -> list[int]:
"""본문에 들어 있는 공지 이미지 id(순서대로, 중복 없이)."""
ids: list[int] = []
for tag in _IMG_TAG.findall(html or ""):
src = _SRC_ATTR.search(tag)
m = _IMG_SRC_OK.match(src.group(1)) if src else None
if m and int(m.group(1)) not in ids:
ids.append(int(m.group(1)))
return ids
def parse_show_at(v: Any, *, now: datetime | None = None) -> datetime:
"""띄울 시각 — 'YYYY-MM-DDTHH:MM'(화면 입력, 한국시간) 또는 시간대가 붙은 ISO. 비우면 지금."""
s = pj_store.norm_str(v)
if not s:
return now or datetime.now(KST)
try:
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
except ValueError:
raise ValueError("띄울 시각이 올바르지 않습니다.")
if d.tzinfo is None:
d = d.replace(tzinfo=KST)
if not 2000 <= d.year <= 2100:
raise ValueError("띄울 시각이 올바르지 않습니다.")
return d
def validate_targets(to_all: Any, targets: Any) -> tuple[bool, list[str]]:
"""(전체 여부, 받는 사람 이메일). 전체가 아니면 한 명 이상."""
if to_all is True or to_all in ("1", "true", "on"):
return True, []
emails = pj_store.normalize_emails(targets if isinstance(targets, (list, tuple)) else [])
if not emails:
raise ValueError("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요.")
if len(emails) > TARGETS_MAX:
raise ValueError(f"받는 사람은 {TARGETS_MAX}명까지 고를 수 있습니다.")
return False, emails
def sniff_image(data: bytes) -> str:
"""파일 앞 바이트로 이미지 형식 — png·jpeg·gif·webp 만. 아니면 ValueError."""
if not data:
raise ValueError("빈 파일입니다.")
if len(data) > IMAGE_MAX_BYTES:
raise ValueError("이미지는 10MB 이하만 올릴 수 있습니다.")
for magic, ctype in _MAGIC:
if data.startswith(magic):
return ctype
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
raise ValueError("이미지(png·jpg·gif·webp)만 올릴 수 있습니다.")
@@ -0,0 +1,70 @@
{% extends "erp_base.html" %}
{% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261019j" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %}
{% block content %}
{% if not enabled %}
<div class="ntc-card">
<h2>긴급 공지 준비 필요</h2>
<p>project_db 마이그레이션 024(<code>scripts/sql/project_db_024_urgent_notices.sql</code>)를 적용하면 사용할 수 있습니다.</p>
</div>
{% else %}
<div class="ntc-wrap" id="ntc-root">
<section class="ntc-card" aria-labelledby="ntc-form-title">
<h2 id="ntc-form-title">새 긴급 공지</h2>
<input type="hidden" id="ntc-id" value="" />
<label class="ntc-field">제목
<input type="text" id="ntc-title" maxlength="200" placeholder="예: 오늘 18시 서버 점검" autocomplete="off" />
</label>
{# 내용 — 작업 설명란과 같은 편집기(서식 도구 전체·이미지 붙여넣기/버튼·크기 조절·링크·체크리스트) #}
<div class="ntc-field pj-desc-block ntc-desc">
<div class="pj-desc-toolbar"><span>내용</span><span class="pj-muted-sm" id="ntc-hint"></span></div>
{% with fmtbar_id = "ntc-fmtbar", img_input_id = "ntc-img-input" %}{% include "project/_desc_fmtbar.html" %}{% endwith %}
<div class="pj-desc-wrap">
<div class="pj-desc-editor" id="ntc-body" contenteditable="true" role="textbox" aria-multiline="true" aria-label="공지 내용"
data-placeholder="공지 내용을 쓰세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
</div>
</div>
{# 띄울 날짜 — 프로젝트와 같은 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸. 둘 다 비우면 바로 #}
<div class="ntc-field">띄울 시각 <small class="ntc-sub">한국시간 · 날짜를 비우면 바로</small>
<div class="ntc-when">
<input type="date" id="ntc-date" />
<input type="time" id="ntc-time" class="ntc-time" step="300" aria-label="띄울 시각" />
</div>
</div>
<div class="ntc-field">받는 사람
<div class="ntc-targets">
<div class="ntc-to">
<label><input type="radio" name="ntc-to" value="all" checked /> 전체(로그인하는 모든 사람)</label>
<label><input type="radio" name="ntc-to" value="some" /> 고른 사람만</label>
</div>
{# 프로젝트 멤버 고르기와 같은 모양 — 아이콘 + 이름 + 체크 #}
<div class="pj-member-picker ntc-people" id="ntc-people" hidden></div>
</div>
</div>
<label class="ntc-field ntc-inline" id="ntc-reshow-row" hidden>
<input type="checkbox" id="ntc-reshow" /> 이미 [확인]한 사람에게도 다시 띄우기
</label>
<div class="ntc-actions">
<button type="button" class="pj-btn" id="ntc-reset">새로 쓰기</button>
<button type="button" class="pj-btn" id="ntc-preview">미리 보기</button>
<button type="button" class="pj-btn pj-btn-primary" id="ntc-save">공지 만들기</button>
</div>
<p class="ntc-msg" id="ntc-msg" role="alert" hidden></p>
</section>
<section class="ntc-card" aria-labelledby="ntc-list-title">
<h2 id="ntc-list-title">공지 목록</h2>
<div class="ntc-list" id="ntc-list">불러오는 중…</div>
</section>
</div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261019g" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %}
{% endblock %}
+78
View File
@@ -0,0 +1,78 @@
# [실적] 실적 모듈 — `app/modules/performance/`, `performance_db`
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/PERFORMANCE_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
> 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`.
> 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유.
## 구조 (네 영역 분리)
1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리).
2. 보안 — `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py`.
3. 계산 — `calc.py`(주 = 월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py`.
4. 화면 — `dashboard.py`/`router.py`/템플릿.
## 규칙
- 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다.
- 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장.
- 매출 기준일: 결제 = 결제일, 취소·반품 = 발생일(`sync.sales_date_for`). 금액은 원 단위 정수.
- 권한키 `performance`. 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`.
- 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현.
- 쇼핑몰 화면 수치와 맞출 때는 필드 추측 말고 붙여넣기 비교 + 원본 필드 합계로 진단부터.
## 카페24 적립금 · 네이버 배송비·환불 (2026-10-19 규칙 변경)
- **카페24** 매출 = 결제합계 − 적립금 사용, 환불 = 실제 + 예치금(적립금 환불 제외). raw `points`. 주문 내역 창 **적립금 사용** 칸·합계.
- **네이버** 매출 = 판매금액(총) + 배송비(raw `goods`·`ship` — 배송 묶음마다 `deliveryFeeAmount` 한 번, 할인 안 뺌 = 판매분석 배송비, 10/18 87,500 확인), 환불 = 클레임 완료일(`CLAIM_COMPLETED_DATETIME`) 조회의 취소·반품 완료 상품주문 −결제금액(`naver:{상품주문}-RF`, raw `refund`). 주문 내역 창 **판매금액**(배송비 뺀 raw `goods` — 저장 금액은 판매금액+배송비)·**배송비·환불금액** 칸·합계 + 맨 아래 "그날 매출 = 판매금액 + 배송비 − 환불".
- 예전 규칙으로 받은 날은 [과거 매출 가져오기]로 다시 받아야 바뀜(최근 10일은 자동). 사용자 확인값 10/18: 카페24 적립금 16,820 · 네이버 배송비 87,500 · 환불 66,100 — 배포 뒤 대조.
## 매출 업데이트
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
## 수동 입력
- 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳).
수동 입력 켠 쇼핑몰은 **API 가 설정돼 있어도 매출 업데이트(수동·자동·과거 매출 가져오기)에서 빠진다**(2026-10-21, `sync.sync_all` 대상 고르기 한 곳) — 예전에 받은 API 값은 그대로 남음.
- 일자별 표 [엑셀 업로드] 팝업(`manual_upload.py`, `POST /performance/api/manual-sales/upload`) — 1열 날짜·2열부터 쇼핑몰 이름 머리글, 수동 입력 켜진 쇼핑몰 열의 값 있는 칸만 반영(덮어씀, 빈 칸 그대로), 잘못된 칸이 하나라도 있으면 전부 저장 안 함, 샘플 = 모듈 폴더 `upload_sample.xlsx`.
- **앞으로의 날짜도 입력·업로드 가능**(2026-10-21) — 매출 수동 입력·광고비 날짜 칸, 매출 엑셀 업로드, 광고 보고서 업로드 모두(가져오기 API 는 여전히 오늘까지).
- **계산식 입력**(2026-10-21, `formula.py` `parse_amount`, 마이그레이션 008 `formula` 열) — 매출·광고비 날짜 칸에 = 없이 `1000+2000`(+ - * / 괄호, ×·÷)을 넣으면
서버가 계산(원 반올림)해 금액으로, 식은 `formula` 열에 저장 → 칸 `is-formula` 파랑 굵은 숫자, 다시 누르면 식. 숫자 입력·업로드·광고 API 로 덮으면 식 지움(`db._set_formulas`, 008 미적용이면 조용히 건너뜀).
광고비 탭 직접 입력값은 파랑 **보통 굵기**(굵게는 계산식만), 매출 탭 수동 입력값은 예전처럼 파랑 굵게.
- 일자별 표 **기간 합계 행은 맨 위**(제목 행 바로 아래, 2026-10-21 `calc.main_table`) — 매출·광고비 공통, 연간 보기 "연간 합계"는 그대로 맨 아래.
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
## 매출 실적 화면 (2026-10-19)
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx` → `performance.js initNextUpdate`, 자동 업데이트 규칙 `auto_sync.next_slot` 과 같게 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트 꺼지면 숨김).
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
- 쿠팡: 1열 날짜·19열 청구금액(+부가가치세).
- 네이버: 3열 기간·4열 총비용·12열 ROAS(구매완료 광고수익률(%)), 머리글 클릭 = 일자별 보고서 항목.
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
- 매출 대비 광고비 KPI.
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께.
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(매출과 같은 회차 카운트다운) · 버튼.
설정된 광고 API 전부를 진행 창 작업으로(`POST /api/ad-sync` → `jobs` kind="ads", 채널별 막대 수집 50% → 저장 → 완료, 채널별 [중지]·[업데이트 취소]는
저장 직전까지, 진행·취소·중지 API 는 매출과 같은 `/api/sync/jobs/…`). 진행 중이면 새로 시작 안 하고 합류(`GET /api/ad-sync/current`, 매출 업데이트와 별개).
자동 업데이트 회차(`auto_sync.run_once`)는 매출과 광고비를 **동시에** 각각 진행 창 작업으로, 이미 돌고 있는 종류만 그 회차 건너뜀. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. [광고비 업데이트]·자동 업데이트. 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [광고비 업데이트]·자동 업데이트 회차.
@@ -0,0 +1,5 @@
"""광고 API 연동(구글 광고 등) — 광고 채널 하나 = 파일 하나 + registry.py 한 줄.
쇼핑몰 어댑터(adapters/)와 같은 모양(입력칸·연결 테스트·인증정보 접근자)을 따르되, 돌려주는 것은 매출 사건이 아니라
"날짜별 광고비·ROAS·보고서 항목"(AdDay)이다. 저장은 ad_sync.py 가 perf_ad_spend(source='api')에.
"""
@@ -0,0 +1,76 @@
"""광고 API 연동 — 공통 인터페이스.
광고 채널 코드(code)는 광고비 표 채널 코드(ad_spend.CHANNELS)와 같다 — 가져온 값은 그 채널 열로 들어간다.
인증정보는 쇼핑몰 인증정보와 같은 방식(설정 화면 입력 → 마스터 키로 암호화 → perf_ad_credentials)이고,
꺼낼 때는 ctx.credentials.get(key) 로만(서버 안에서만 복호화). 오류는 adapters.base 의 AdapterError 계열 —
status 가 곧 연결 상태 코드(설정 화면 표시)다. 오류 문구에 비밀값을 넣지 않는다.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
from typing import Any
from ..adapters.base import AdapterContext, CredentialField, NotConfigured
# AdDay.metrics 안의 계정별 값(여러 광고 계정을 합치는 채널 — 메타, 2026-10-16):
# {ACCOUNTS_KEY: {계정 ID: {"name", "amount", "roas", "metrics"}}} — 상세보기 [합계 | 계정…] 탭(ad_spend.detail_tabs).
# "_" 로 시작하는 metrics 키는 일자별 표 열·합계에 넣지 않는다(ad_spend.detail_table).
ACCOUNTS_KEY = "_accounts"
@dataclass
class AdDay:
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
day: date
amount: int
roas: Decimal | None = None
metrics: dict[str, Any] = field(default_factory=dict)
class AdSource:
code: str = "" # 광고비 채널 코드(google 등)
name: str = "" # 설정 화면 이름
docs_url: str = ""
note: str = "" # 설정 창 맨 위 안내
# 인증정보 서비스(credentials.CredentialService)가 쇼핑몰 어댑터와 같은 방식으로 다루게 맞춘 속성
@property
def uses_shared_integration(self) -> bool:
return False
def credential_fields(self) -> list[CredentialField]:
return []
def visible_fields(self) -> list[CredentialField]:
return [f for f in self.credential_fields() if not f.internal]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
"""저장 전 검사. values 의 "__stored__" = 저장된 값이 있음(원문은 꺼내지 않음). 값 자체를 오류 문구에 넣지 않는다."""
errors: list[str] = []
for f in self.visible_fields():
v = (values.get(f.key) or "").strip()
if f.required and not v:
errors.append(f"{f.label} 을(를) 입력하세요.")
elif v and len(v) > 20000:
errors.append(f"{f.label} 값이 너무 깁니다.")
return errors
def is_configured(self, ctx: AdapterContext) -> bool:
return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required)
def require_configured(self, ctx: AdapterContext) -> None:
if not self.is_configured(ctx):
raise NotConfigured("필수 인증정보가 입력되지 않았습니다. 실적 설정 → 광고 API 연동에서 입력하세요.")
def test_connection(self, ctx: AdapterContext) -> str:
"""성공하면 사람이 읽을 짧은 문구. 실패는 AdapterError."""
raise NotImplementedError
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
"""기간(양 끝 포함)의 날짜별 광고비. 광고가 없던 날은 빠질 수 있다(저장 쪽이 그날의 예전 API 값을 지운다)."""
raise NotImplementedError
@@ -0,0 +1,302 @@
"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-15 사용자: 서비스 계정 Explorer 승인)
- 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx.
서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다
(2024-11 부터 도메인 전체 위임 없이 직접 추가 가능).
- **개발자 토큰은 2026-09-09 폐지** — API 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙는다
(Cloud Console → Google Ads API Overview 에서 신청). developer-token 머리글은 지금은 무시되고 다음 큰 버전부터 거부되므로
보내지 않는다(입력칸도 없음, 예전에 저장한 값은 쓰지 않음).
- 요청 머리글: Authorization(Bearer) · login-customer-id(MCC 를 거쳐 들어갈 때만).
- Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
조회(REST googleAds:searchStream, GAQL)
SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks,
metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date BETWEEN 'from' AND 'to'
- 날짜는 광고 계정 시간대 기준(한국 계정이면 KST). 광고가 없던 날은 행이 없을 수 있다.
- 금액(광고비) = **부가세 포함**(2026-10-15 사용자 요청) = cost_micros ÷ 1,000,000 × 1.1 을 원 단위로 반올림
(구글 광고 비용은 부가세 별도 — 쿠팡 광고비처럼 부가세 포함으로 맞춘다). 계정 통화가 KRW 가 아니면 저장하지 않는다.
- ROAS(%) = 전환 가치 ÷ 비용(부가세 별도) × 100 — 구글 광고 화면 "전환 가치/비용"과 같은 값 그대로, 비용이 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·전환수·전환 가치)은 광고비 탭 구글 머리글 → 일자별 표.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 구글은 버전을 약 1년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
from __future__ import annotations
import json
import re
import threading
import time
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured
from .base import AdDay, AdSource
SCOPE = "https://www.googleapis.com/auth/adwords"
API_BASE = "https://googleads.googleapis.com"
DEFAULT_VERSION = "v26" # 2026-10 기준 최신(구글 광고 API 는 매월 부 버전·분기마다 새 버전)
TOKEN_URI = "https://oauth2.googleapis.com/token"
MAX_DAYS = 366
VAT = Decimal("1.1") # 광고비 = 구글 비용 + 부가세 10%
# 일자별 표(광고비 탭 구글 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND, M_COST = "광고비(부가세 포함)", "비용(부가세 별도)"
M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "노출수", "클릭수", "클릭률(%)", "전환수", "전환 가치", "ROAS(%)"
# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
_HINTS = {
"CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION": "서비스 계정이 속한 Google Cloud 프로젝트에 운영 계정 접근 승인이 없습니다. "
"Cloud Console → Google Ads API Overview 에서 그 프로젝트의 Explorer 이상 승인을 확인하세요.",
"AUTHORIZATION_ERROR": "API 접근 승인 문제입니다. 서비스 계정이 속한 Cloud 프로젝트의 Google Ads API 승인 상태를 확인하세요.",
"INVALID_LOGIN_CUSTOMER_ID": "[로그인 고객 ID(MCC)] 칸 문제입니다. 서비스 계정을 광고 계정에 직접 추가했다면 이 칸을 비우세요"
"(칸을 지우고 [연결 테스트] → [저장]). MCC 에 추가했다면 서비스 계정을 추가한 그 MCC 번호여야 하고, "
"고객 ID 의 광고 계정이 그 MCC 아래에 있어야 합니다.",
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
"NOT_ADS_USER": "서비스 계정이 구글 광고 사용자로 등록돼 있지 않습니다(액세스 및 보안에서 추가).",
"INVALID_CUSTOMER_ID": "고객 ID 가 올바르지 않습니다(광고 계정 오른쪽 위 123-456-7890 형태 번호).",
"CUSTOMER_NOT_FOUND": "고객 ID 의 광고 계정을 찾을 수 없습니다.",
"SERVICE_ACCOUNT_NOT_ALLOWED": "이 계정은 서비스 계정 접근을 허용하지 않습니다.",
}
_token_lock = threading.Lock()
_token_cache: dict[str, tuple[str, float]] = {} # (서비스 계정 이메일, 키 ID) → (액세스 토큰, 만료 시각)
def _digits(value: str) -> str:
return re.sub(r"[\s\-]", "", value or "")
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def parse_service_account(raw: str) -> dict[str, Any]:
"""서비스 계정 JSON 키 → dict. 형식이 틀리면 ValueError(문구에 키 내용을 넣지 않는다)."""
try:
info = json.loads(raw)
except (TypeError, ValueError):
raise ValueError("서비스 계정 키가 JSON 형식이 아닙니다(구글 클라우드에서 내려받은 .json 파일 내용을 통째로 붙여 넣으세요).") from None
if not isinstance(info, dict) or info.get("type") != "service_account":
raise ValueError("서비스 계정 키가 아닙니다(\"type\": \"service_account\" 인 JSON 이어야 합니다).")
for k in ("client_email", "private_key"):
if not str(info.get(k) or "").strip():
raise ValueError(f"서비스 계정 키에 {k} 가 없습니다.")
return info
def _won(micros: int, rate: Decimal = Decimal(1)) -> int:
"""마이크로 단위 금액 × rate → 원(반올림). rate=VAT 면 부가세 포함."""
return int((Decimal(int(micros)) * rate / Decimal(1_000_000)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def _num(v: Any) -> Decimal:
"""REST 응답 숫자(int64 는 문자열, double 은 숫자, 0 은 아예 빠짐) → Decimal."""
if v is None or v == "":
return Decimal(0)
return Decimal(str(v))
def _google_error(resp: httpx.Response) -> tuple[str, str]:
"""구글 오류 응답 → (오류 코드 이름, 사람이 읽을 문구). searchStream 오류는 배열에 싸여 올 수 있다."""
try:
body = resp.json()
except ValueError:
return "", f"HTTP {resp.status_code}"
if isinstance(body, list):
body = next((b for b in body if isinstance(b, dict) and b.get("error")), body[0] if body else {})
err = (body or {}).get("error") or {}
if isinstance(err, str): # 토큰 교환 오류 {"error": "invalid_grant", "error_description": "..."}
return err, str((body or {}).get("error_description") or err)
code_name, message = "", str(err.get("message") or f"HTTP {resp.status_code}")
for d in err.get("details") or []:
for e in (d or {}).get("errors") or []:
ec = e.get("errorCode") or {}
if ec:
code_name = str(next(iter(ec.values())))
if e.get("message"):
message = str(e["message"])
break
if code_name:
break
return code_name, message
class GoogleAdsSource(AdSource):
code = "google"
name = "구글 광고"
docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts"
note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. "
"준비: ① Google Cloud 서비스 계정 JSON 키(그 Cloud 프로젝트가 Google Ads API Explorer 이상 승인) "
"② 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분). "
"개발자 토큰은 2026-09-09 폐지돼 필요 없습니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890",
help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."),
CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근",
help="서비스 계정을 관리자(MCC) 계정에 추가해 그 아래 광고 계정을 볼 때만 MCC 번호를 넣습니다."),
CredentialField("service_account_json", "서비스 계정 키(JSON)", secret=True, multiline=True,
help="Google Cloud → IAM → 서비스 계정 → 키 → JSON 으로 받은 파일 내용을 통째로 붙여 넣습니다. "
"저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
help=f"비워 두면 {DEFAULT_VERSION}. 구글이 버전 종료를 알리면 새 버전(예: v27)으로 바꿉니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
for key, label in (("customer_id", "고객 ID"), ("login_customer_id", "로그인 고객 ID")):
v = (values.get(key) or "").strip()
if v and v != "__stored__" and not re.fullmatch(r"\d{10}", _digits(v)):
errors.append(f"{label}는 숫자 10자리여야 합니다(예: 123-456-7890).")
sa = (values.get("service_account_json") or "").strip()
if sa and sa != "__stored__":
try:
parse_service_account(sa)
except ValueError as exc:
errors.append(str(exc))
ver = (values.get("api_version") or "").strip()
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}", ver):
errors.append("API 버전은 v26 처럼 v 뒤에 숫자로 입력하세요.")
return errors
# ── 인증 ──────────────────────────────────────────────
def _access_token(self, ctx: AdapterContext, client: httpx.Client) -> str:
try:
info = parse_service_account(ctx.credentials.get("service_account_json"))
except ValueError as exc:
raise NotConfigured(str(exc)) from None
cache_key = f"{info['client_email']}|{info.get('private_key_id', '')}"
with _token_lock:
hit = _token_cache.get(cache_key)
if hit and hit[1] > time.time() + 120:
return hit[0]
from google.auth import crypt, jwt # noqa: WPS433 — google-auth(requirements)
try:
signer = crypt.RSASigner.from_service_account_info(info)
except Exception: # noqa: BLE001 — 키 내용은 문구에 넣지 않는다
raise AuthFailed("서비스 계정 키의 private_key 를 읽을 수 없습니다(JSON 파일 내용을 그대로 붙여 넣었는지 확인).") from None
now = int(time.time())
token_uri = str(info.get("token_uri") or TOKEN_URI)
assertion = jwt.encode(signer, {"iss": info["client_email"], "scope": SCOPE, "aud": token_uri,
"iat": now, "exp": now + 3600})
try:
resp = client.post(token_uri, data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion.decode() if isinstance(assertion, bytes) else assertion})
except httpx.HTTPError as exc:
raise ApiError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
name, msg = _google_error(resp)
raise AuthFailed(f"서비스 계정 인증 실패({name or resp.status_code}): {msg[:200]} — 키가 삭제·사용 중지되지 않았는지 확인하세요.")
body = resp.json()
token = str(body.get("access_token") or "")
if not token:
raise AuthFailed("구글 인증 서버가 액세스 토큰을 주지 않았습니다.")
with _token_lock:
_token_cache[cache_key] = (token, time.time() + int(body.get("expires_in") or 3600))
return token
def _search(self, ctx: AdapterContext, query: str) -> list[dict[str, Any]]:
"""GAQL 한 번 — searchStream 응답(묶음 배열)의 results 를 이어 붙여 돌려준다."""
self.require_configured(ctx)
cid = _digits(ctx.credentials.get("customer_id"))
if not re.fullmatch(r"\d{10}", cid):
raise NotConfigured("고객 ID 는 숫자 10자리여야 합니다.")
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
with _http(ctx) as client:
token = self._access_token(ctx, client)
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} # 개발자 토큰 없음(2026-09-09 폐지)
login = _digits(ctx.credentials.get("login_customer_id"))
if login:
headers["login-customer-id"] = login
ctx.progress.check()
try:
resp = client.post(f"{API_BASE}/{version}/customers/{cid}/googleAds:searchStream",
headers=headers, json={"query": query})
except httpx.HTTPError as exc:
raise ApiError(f"구글 광고 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code == 404:
raise ApiError(f"구글 광고 API 버전 {version} 을(를) 쓸 수 없습니다(종료됐을 수 있음) — 실적 설정에서 API 버전을 최신으로 바꾸세요.")
if resp.status_code != 200:
name, msg = _google_error(resp)
hint = _HINTS.get(name, "")
text = f"구글 광고 API 오류({name or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
raise (AuthFailed if resp.status_code in (401, 403) else ApiError)(text)
try:
batches = resp.json()
except ValueError:
raise ApiError("구글 광고 API 응답을 읽을 수 없습니다.") from None
if isinstance(batches, dict):
batches = [batches]
out: list[dict[str, Any]] = []
for b in batches or []:
out.extend((b or {}).get("results") or [])
return out
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
rows = self._search(ctx, "SELECT customer.id, customer.descriptive_name, customer.currency_code, "
"customer.time_zone FROM customer LIMIT 1")
c = (rows[0].get("customer") if rows else None) or {}
currency = c.get("currencyCode") or "?"
msg = f"연결됨 — {c.get('descriptiveName') or '광고 계정'} · 통화 {currency} · 시간대 {c.get('timeZone') or '?'}"
if currency != "KRW":
msg += " (원화 계정이 아니라 광고비를 가져올 수 없습니다)"
return msg
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
rows = self._search(
ctx,
"SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, "
"metrics.conversions, metrics.conversions_value FROM customer "
f"WHERE segments.date BETWEEN '{start.isoformat()}' AND '{end.isoformat()}'",
)
sums: dict[date, dict[str, Decimal]] = {}
for r in rows:
cur = ((r.get("customer") or {}).get("currencyCode") or "").upper()
if cur and cur != "KRW":
raise ApiError(f"광고 계정 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.")
raw_day = (r.get("segments") or {}).get("date")
try:
day = date.fromisoformat(str(raw_day))
except ValueError:
continue
m = r.get("metrics") or {}
acc = sums.setdefault(day, {"cost": Decimal(0), "impr": Decimal(0), "clicks": Decimal(0),
"conv": Decimal(0), "value": Decimal(0)})
acc["cost"] += _num(m.get("costMicros"))
acc["impr"] += _num(m.get("impressions"))
acc["clicks"] += _num(m.get("clicks"))
acc["conv"] += _num(m.get("conversions"))
acc["value"] += _num(m.get("conversionsValue"))
out: list[AdDay] = []
for day in sorted(sums):
a = sums[day]
amount = _won(int(a["cost"]), VAT) # 광고비 = 부가세 포함
cost = a["cost"] / Decimal(1_000_000)
roas = (a["value"] / cost * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if cost > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
metrics = {
M_SPEND: amount,
M_COST: _won(int(a["cost"])),
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_CONV: float(a["conv"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
M_VALUE: int(a["value"].quantize(Decimal(1), rounding=ROUND_HALF_UP)),
M_ROAS: float(roas) if roas is not None else None,
}
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
@@ -0,0 +1,389 @@
"""메타 광고(Meta Marketing API — Insights) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-16 사용자: 토큰·광고 계정 ID 준비 완료)
- 액세스 토큰 하나(시스템 사용자 토큰 권장 — 만료 없음. 사용자 토큰은 약 60일 뒤 만료) + 광고 계정 ID 여러 개.
토큰에 ads_read 권한이 있어야 하고, 토큰 주인(시스템 사용자 등)이 각 광고 계정에 배정돼 있어야 한다.
- 메타 문서대로 토큰은 access_token 매개변수로 보낸다. 앱 설정에서 "앱 시크릿 필요"를 켰다면 앱 시크릿을 넣어
appsecret_proof(HMAC-SHA256)를 같이 보낸다. 토큰은 오류 문구에 넣지 않고(주소도 넣지 않음),
ad_sync 가 저장된 비밀값을 다시 한 번 가린다. httpx 요청 로그(INFO)는 주소에 토큰이 들어가므로 켜지 않는다.
조회(GET /{버전}/act_{계정}/insights)
level=account · time_increment=1(하루씩) · time_range={since, until} · fields=spend·노출·클릭·구매 전환 등.
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다.
- 원화가 아닌 계정(USD 등, 2026-10-16)은 지출 금액·구매 전환값을 그날 환율로 원화 환산(fx.krw_rates — Frankfurter 중앙은행 고시 환율 종합,
그날 값이 없으면 앞 가장 가까운 날). 계정 탭에 원래 통화 지출·적용 환율. ROAS 는 비율이라 환율과 무관.
- 기여(어트리뷰션)는 메타가 광고 관리자 설정을 그대로 따른다(2025-06 부터 API 의 기여 매개변수는 무시됨) — 화면 값과 같다.
- 구매 전환값·구매수 = action_values·actions 의 구매 항목 하나(omni_purchase → purchase → 픽셀 구매 순서로 처음 있는 것).
메타는 같은 구매를 여러 action_type 에 같은 값으로 겹쳐 주므로 더하지 않는다.
- 금액(광고비) = 지출 금액 그대로(원 반올림) — **메타 지출 금액은 이미 부가세 포함**(2026-10-16 사용자 확인).
부가세를 더하는(× 1.1) 것은 비용이 부가세 별도인 구글만이다.
- ROAS(%) = 구매 전환값 ÷ 지출 금액 × 100 — 광고 관리자 "구매 ROAS" 와 같은 값, 지출 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·링크 클릭·구매수·구매 전환값)은 광고비 탭 메타 머리글 → 일자별 표.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 메타는 버전을 약 2년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import re
from datetime import date
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
from .. import fx
from .base import ACCOUNTS_KEY, AdDay, AdSource
API_BASE = "https://graph.facebook.com"
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
MAX_DAYS = 366
MAX_ACCOUNTS = 30
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase")
INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
M_SPEND = "지출 금액(부가세 포함)" # = 광고비(메타 지출 금액은 부가세 포함 — 구글처럼 따로 더하지 않음)
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
M_FX = "적용 환율(원)" # 외화 계정 탭에만 — 그날 1 계정 통화 = ? 원(fx.krw_rates)
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임). 권한 오류는 연결 테스트가 원인을 진단한다(_diagnose) —
# 불러오기에서 난 오류엔 그 안내를 붙이고, 연결 테스트 자체에서는 진단 결과로 바꿔 쓴다.
_DIAG_HINT = "(실적 설정 → 광고 API 연동 → 메타 [연결 테스트]가 원인을 진단합니다)"
_HINTS = {
190: "토큰이 만료됐거나 무효입니다. 비즈니스 설정 → 시스템 사용자에서 토큰을 다시 만들어 [액세스 토큰]에 넣으세요(시스템 사용자 토큰은 만료 없음).",
102: "토큰을 읽을 수 없습니다. 토큰을 다시 복사해 넣으세요.",
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요"
+ _DIAG_HINT + ".",
10: "토큰에 권한이 없습니다(ads_read). 앱·토큰 권한을 확인하세요.",
100: "요청 값이 올바르지 않습니다 — 광고 계정 ID 가 맞는지, 토큰 주인이 그 계정을 볼 수 있는지 확인하세요.",
803: "광고 계정 ID 를 찾을 수 없습니다(숫자만, act_ 는 있어도 됨).",
4: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
17: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
613: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80000: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
80004: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
2635: "API 버전이 종료됐습니다 — 실적 설정에서 API 버전을 최신으로 바꾸세요.",
}
_RATE_LIMIT = {4, 17, 613, 80000, 80004}
_AUTH = {10, 102, 200}
_ACCOUNT_STATUS = {1: "운영 중", 2: "사용 중지", 3: "미결제", 7: "검토 대기", 8: "결제 대기", 9: "유예 기간", 100: "종료 대기", 101: "종료"}
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def parse_account_ids(raw: str) -> list[str]:
"""'act_123, 456\\n789' → ['123', '456', '789'](순서 유지·중복 제거). 형식이 틀리면 ValueError."""
out: list[str] = []
for part in re.split(r"[\s,;]+", raw or ""):
if not part:
continue
v = part[4:] if part.lower().startswith("act_") else part
if not re.fullmatch(r"\d{5,20}", v):
raise ValueError("광고 계정 ID 는 숫자여야 합니다(act_ 는 있어도 됨, 여러 개는 쉼표나 줄바꿈으로 구분).")
if v not in out:
out.append(v)
if len(out) > MAX_ACCOUNTS:
raise ValueError(f"광고 계정은 {MAX_ACCOUNTS}개까지 넣을 수 있습니다.")
return out
def _num(v: Any) -> Decimal:
"""메타 응답 숫자(문자열로 옴, 0 이면 빠지기도 함) → Decimal."""
if v is None or v == "":
return Decimal(0)
try:
return Decimal(str(v))
except ArithmeticError:
return Decimal(0)
def _won(v: Decimal) -> int:
return int(v.quantize(Decimal(1), rounding=ROUND_HALF_UP))
def _purchase(items: Any) -> Decimal:
"""actions / action_values 목록에서 구매 값 하나(PURCHASE_TYPES 순서로 처음 있는 것 — 겹친 값을 더하지 않는다)."""
by_type = {str((i or {}).get("action_type")): (i or {}).get("value") for i in (items or []) if isinstance(i, dict)}
for t in PURCHASE_TYPES:
if t in by_type:
return _num(by_type[t])
return Decimal(0)
def _meta_error(resp: httpx.Response) -> tuple[int, str]:
"""메타 오류 응답 {"error": {"message", "code", "error_subcode", ...}} → (코드, 문구)."""
try:
err = (resp.json() or {}).get("error") or {}
except ValueError:
return 0, f"HTTP {resp.status_code}"
if not isinstance(err, dict):
return 0, f"HTTP {resp.status_code}"
msg = str(err.get("error_user_msg") or err.get("message") or f"HTTP {resp.status_code}")
try:
code = int(err.get("code") or 0)
except (TypeError, ValueError):
code = 0
return code, msg
class MetaAdsSource(AdSource):
code = "meta"
name = "메타 광고"
docs_url = "https://developers.facebook.com/docs/marketing-api/insights"
note = ("메타 마케팅 API(Insights)로 광고 계정별 날짜별 지출 금액·구매 ROAS·노출수·클릭수·구매를 가져와 계정을 합칩니다. "
"준비: ① ads_read 권한이 있는 액세스 토큰(비즈니스 설정 → 시스템 사용자 토큰 권장 — 만료 없음) "
"② 토큰 주인을 각 광고 계정에 배정. 광고비 = 메타 지출 금액 그대로(이미 부가세 포함)입니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("account_ids", "광고 계정 ID", multiline=True, placeholder="act_1234567890\nact_9876543210",
help="광고비를 가져올 광고 계정 번호(광고 관리자 주소의 act= 뒤 숫자). 여러 개면 줄바꿈이나 쉼표로 — "
"날짜별로 합쳐서 메타 한 칸에 들어갑니다."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="ads_read 권한이 있는 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("app_secret", "앱 시크릿", secret=True, required=False, placeholder="앱에서 '앱 시크릿 필요'를 켰을 때만",
help="메타 앱 설정 → 고급에서 'API 호출에 앱 시크릿 필요'를 켰다면 넣습니다(appsecret_proof). 아니면 비워 둡니다."),
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
help=f"비워 두면 {DEFAULT_VERSION}. 메타가 버전 종료를 알리면 새 버전(예: v27.0)으로 바꿉니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
ids = (values.get("account_ids") or "").strip()
if ids and ids != "__stored__":
try:
parse_account_ids(ids)
except ValueError as exc:
errors.append(str(exc))
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
ver = (values.get("api_version") or "").strip()
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}\.0", ver):
errors.append("API 버전은 v26.0 처럼 입력하세요.")
return errors
# ── 요청 ──────────────────────────────────────────────
def _setup(self, ctx: AdapterContext) -> tuple[list[str], str, dict[str, str]]:
self.require_configured(ctx)
try:
accounts = parse_account_ids(ctx.credentials.get("account_ids"))
except ValueError as exc:
raise NotConfigured(str(exc)) from None
if not accounts:
raise NotConfigured("광고 계정 ID 를 입력하세요.")
token = (ctx.credentials.get("access_token") or "").strip()
auth = {"access_token": token}
secret = (ctx.credentials.get("app_secret") or "").strip()
if secret:
auth["appsecret_proof"] = hmac.new(secret.encode(), token.encode(), hashlib.sha256).hexdigest()
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
return accounts, version, auth
def _get(self, ctx: AdapterContext, client: httpx.Client, url: str, params: dict[str, Any] | None) -> dict[str, Any]:
ctx.progress.check()
try:
resp = client.get(url, params=params)
except httpx.HTTPError as exc:
raise ApiError(f"메타 API 에 연결하지 못했습니다({type(exc).__name__}).") from None # 주소(토큰 포함)는 넣지 않는다
if resp.status_code != 200:
code, msg = _meta_error(resp)
hint = _HINTS.get(code, "")
text = f"메타 API 오류({code or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
if code == 190:
raise TokenExpired(text)
auth_problem = code in _AUTH or (resp.status_code in (401, 403) and code not in _RATE_LIMIT)
raise (AuthFailed if auth_problem else ApiError)(text)
try:
body = resp.json()
except ValueError:
raise ApiError("메타 API 응답을 읽을 수 없습니다.") from None
return body if isinstance(body, dict) else {}
# ── 권한 진단(연결 테스트가 권한 오류를 받았을 때) ─────────
def _diagnose(self, ctx: AdapterContext, client: httpx.Client, version: str, auth: dict[str, str],
accounts: list[str]) -> str:
"""토큰이 받은 권한·권한 대상 계정·볼 수 있는 광고 계정을 메타에 물어 원인을 짚는다(2026-10-16 #200 오류).
조회가 실패해도 예외를 내지 않는다(진단은 덧붙이는 정보). 토큰 값은 문구에 넣지 않는다."""
lines: list[str] = []
scopes: set[str] | None = None
ads_targets: set[str] | None = None # ads_read/ads_management 가 특정 계정에만 걸려 있으면 그 계정들
try: # ① 토큰 점검 — 앱 개발자 토큰·시스템 사용자 토큰이면 같은 토큰으로 된다
d = (self._get(ctx, client, f"{API_BASE}/{version}/debug_token",
{**auth, "input_token": auth["access_token"]}).get("data") or {})
scopes = {str(s) for s in d.get("scopes") or []}
for g in d.get("granular_scopes") or []:
if str((g or {}).get("scope")) in ("ads_read", "ads_management") and (g or {}).get("target_ids"):
ads_targets = (ads_targets or set()) | {str(t) for t in g["target_ids"]}
exp = int(d.get("expires_at") or 0)
expires = "만료 없음" if exp == 0 else date.fromtimestamp(exp).isoformat() + " 만료"
lines.append(f"토큰: 앱 {d.get('application') or d.get('app_id') or '?'}({d.get('app_id') or '?'}) · {expires}"
+ ("" if d.get("is_valid", True) else " · 무효"))
except AdapterError:
try: # ② 토큰 점검을 못 하면 받은 권한 목록만
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/permissions", dict(auth)).get("data") or []
scopes = {str(r.get("permission")) for r in rows if r.get("status") == "granted"}
except AdapterError:
pass
if scopes is not None:
has = sorted(scopes & {"ads_read", "ads_management"})
lines.append("광고 권한: " + (", ".join(has) if has else "없음(ads_read·ads_management 둘 다 없음)"))
visible: set[str] | None = None
try: # ③ 이 토큰으로 볼 수 있는 광고 계정
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/adaccounts",
{**auth, "fields": "account_id,name", "limit": 200}).get("data") or []
visible = {str(r.get("account_id") or "") for r in rows}
lines.append(f"이 토큰으로 보이는 광고 계정 {len(visible)}개")
except AdapterError:
pass
missing = [a for a in accounts if visible is not None and a not in visible]
not_target = [a for a in accounts if ads_targets is not None and a not in ads_targets]
# 결론 — 가장 앞선 원인 하나
if scopes is not None and not scopes & {"ads_read", "ads_management"}:
todo = ("토큰에 ads_read 권한이 없습니다 → 토큰을 새로 만들면서 ads_read 를 체크하세요"
"(비즈니스 설정 → 사용자 → 시스템 사용자 → 새 토큰 생성 → 권한에서 ads_read).")
elif missing:
todo = ("입력한 계정 중 이 토큰 주인에게 배정되지 않은 계정: " + ", ".join("act_" + a for a in missing)
+ " → 비즈니스 설정 → 사용자 → 시스템 사용자(토큰 주인) → [자산 할당] → 광고 계정에서 그 계정을 고르고 "
"'성과 보기'(또는 전체 권한)를 켠 뒤, 토큰을 새로 만들어 넣으세요(배정 전에 만든 토큰은 권한이 안 바뀔 수 있음).")
elif not_target:
todo = ("토큰의 ads_read 권한이 다른 계정에만 걸려 있습니다(대상 아님: " + ", ".join("act_" + a for a in not_target)
+ ") → 토큰을 새로 만들 때 이 광고 계정도 대상에 포함하세요.")
elif visible is not None:
todo = ("토큰 권한·계정 배정은 맞습니다 → 앱 쪽 문제일 가능성이 큽니다: 앱이 이 광고 계정을 가진 비즈니스에 연결돼 있는지"
"(비즈니스 설정 → 계정 → 앱), 앱 대시보드에 Marketing API 제품이 추가돼 있는지, 앱이 '제한 액세스'라면 토큰 주인이 앱의 "
"관리자·개발자 역할인지 확인하세요.")
else:
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
return "[진단] " + " · ".join(lines + [todo])
# ── 연결 테스트 · 가져오기 ─────────────────────────────
def test_connection(self, ctx: AdapterContext) -> str:
accounts, version, auth = self._setup(ctx)
parts: list[str] = []
not_krw = False
with _http(ctx) as client:
for acc in accounts:
try:
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
{**auth, "fields": "name,currency,timezone_name,account_status"})
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
# 진단(고칠 곳)을 맨 앞에, 메타 원문은 짧게 뒤에 — 길면 화면·기록에서 뒤가 잘리므로(2026-10-16 "[진…" 잘림)
original = str(exc).split(" — ")[0]
original = re.sub(r",?\s*refer to https?://\S+(?: for details)?", "", original)
raise AuthFailed(self._diagnose(ctx, client, version, auth, accounts)
+ f" (메타 원문: {original})") from None
cur = str(info.get("currency") or "?")
not_krw = not_krw or cur != "KRW"
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
parts.append(f"{info.get('name') or acc}({cur}·{info.get('timezone_name') or '?'}{'·' + status if status else ''})")
msg = f"연결됨 — 광고 계정 {len(accounts)}개: " + ", ".join(parts)
if not_krw:
msg += f" (원화가 아닌 계정은 날마다 그날 환율로 원화로 바꿔 넣습니다 — {fx.SOURCE_LABEL})"
return msg
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
accounts, version, auth = self._setup(ctx)
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})}
raw: list[tuple[str, date, str, dict[str, Any]]] = [] # (계정, 날짜, 통화, insights 한 줄)
names: dict[str, str] = {}
with _http(ctx) as client:
for acc in accounts:
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
page_params: dict[str, Any] | None = params
for _ in range(MAX_PAGES):
body = self._get(ctx, client, url, page_params)
for r in body.get("data") or []:
try:
day = date.fromisoformat(str(r.get("date_start")))
except ValueError:
continue
if r.get("account_name"):
names[acc] = str(r["account_name"])[:100]
raw.append((acc, day, str(r.get("account_currency") or "KRW").upper(), r))
nxt = ((body.get("paging") or {}).get("next") or "").strip()
if not nxt:
break
if not nxt.startswith(API_BASE + "/"):
raise ApiError("메타 API 다음 쪽 주소가 올바르지 않습니다.")
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
else:
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
# 원화가 아닌 계정(USD 등) — 그날 환율로 원화 환산(2026-10-16). 통화마다 기간 환율을 한 번에.
rates: dict[str, dict[date, Decimal]] = {}
for cur in sorted({c for _a, _d, c, _r in raw if c != "KRW"}):
if not re.fullmatch(r"[A-Z]{3}", cur):
raise ApiError(f"광고 계정 통화({cur[:10]})를 알 수 없습니다.")
try:
rates[cur] = fx.krw_rates(client, cur, start, end)
except fx.FxError as exc:
raise ApiError(f"{cur} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합(원화)
per_acc: dict[date, dict[str, dict[str, Any]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
for acc, day, cur, r in raw:
rate = Decimal(1) if cur == "KRW" else rates[cur][day]
one = per_acc.setdefault(day, {}).setdefault(acc, {**_zero(), "cur": cur, "rate": rate, "orig": Decimal(0)})
_add(one, r, rate)
one["orig"] += _num(r.get("spend")) # 그 계정 통화 그대로의 지출 금액
_add(sums.setdefault(day, _zero()), r, rate)
out: list[AdDay] = []
for day in sorted(sums):
amount, roas, metrics = _convert(sums[day])
# 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
# 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
accounts_out: dict[str, Any] = {}
for acc, a in per_acc.get(day, {}).items():
a_amount, a_roas, a_metrics = _convert(a)
if a["cur"] != "KRW": # 외화 계정 — 원래 통화 지출과 적용 환율도 보여 준다(계정 탭)
a_metrics[f"지출 금액({a['cur']})"] = float(a["orig"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
a_metrics[M_FX] = float(a["rate"])
accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
"roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
metrics[ACCOUNTS_KEY] = accounts_out
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
return out
def _zero() -> dict[str, Decimal]:
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
def _add(acc: dict[str, Any], r: dict[str, Any], rate: Decimal = Decimal(1)) -> None:
"""insights 한 줄(계정 하나·하루)을 더한다 — 금액(지출·구매 전환값)은 × rate(그날 1 계정 통화 = ? 원)로 원화."""
acc["spend"] += _num(r.get("spend")) * rate
acc["impr"] += _num(r.get("impressions"))
acc["clicks"] += _num(r.get("clicks"))
acc["link"] += _num(r.get("inline_link_clicks"))
acc["purchases"] += _purchase(r.get("actions"))
acc["value"] += _purchase(r.get("action_values")) * rate
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]:
"""더한 값 → (광고비 원, ROAS %, 일자별 표 항목). 광고비 = 지출 금액 그대로(메타 지출은 부가세 포함, 2026-10-16)."""
amount = _won(a["spend"])
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
return amount, roas, {
M_SPEND: amount,
M_IMPR: int(a["impr"]),
M_CLICKS: int(a["clicks"]),
M_CTR: float(ctr) if ctr is not None else None,
M_LINK: int(a["link"]),
M_PURCHASES: int(a["purchases"]),
M_VALUE: _won(a["value"]),
M_ROAS: float(roas) if roas is not None else None,
}
@@ -0,0 +1,18 @@
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
from __future__ import annotations
from .base import AdSource
from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES}
def all_sources() -> tuple[AdSource, ...]:
return _SOURCES
def get_source(code: str) -> AdSource | None:
return _BY_CODE.get(code)
+608
View File
@@ -0,0 +1,608 @@
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
- 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만.
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
규칙(2026-10-14 사용자 확인): **1열에 날짜가 있는 줄의 19열 값**을 가져온다 — 19열이 빈 줄은 건너뛰고(윙 보고서는
캠페인 줄에도 날짜가 있고 19열이 비어 있다), 같은 날짜에 값이 있는 줄이 여럿이면 더한다.
1열이 빈 캠페인 줄·맨 위 "전체" 합계 줄은 건너뛴다. 날짜는 있는데 19열 값이 한 줄도 없는 날은 empty_days 로 알려 준다.
네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
"""
from __future__ import annotations
import csv
import io
from dataclasses import dataclass, field
from datetime import date
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence
from . import calc
from .ad_sources.base import ACCOUNTS_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
CHANNELS: tuple[tuple[str, str], ...] = (
("google", "구글"),
("meta", "메타"),
("naver", "네이버"),
("coupang_wing", "쿠팡(윙)"),
("coupang_rocket", "쿠팡(로켓)"),
("ohouse", "오늘의집"),
("gmarket", "G마켓"),
("kakao", "카카오"),
("gsshop", "GS샵"),
("elevenst", "11번가"),
("lotteon", "롯데ON"),
("toss", "토스"),
("atomy", "애터미아자몰"),
)
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
FILE_ROAS = frozenset({"google", "meta", "naver"})
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
def roas(sales: int, spend: int) -> int | None:
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
if not spend or spend <= 0:
return None
return int((Decimal(int(sales)) * 100 / Decimal(int(spend))).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def roas_basis(code: str) -> str:
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
s: date, e: date) -> int | None:
"""보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
rev = Decimal(0)
spend = 0
for (d, c), r in file_roas_map.items():
if c != code or not s <= d <= e or r is None:
continue
amt = int(spends.get((d, c)) or 0)
if amt > 0:
rev += Decimal(str(r)) * amt
spend += amt
if spend <= 0:
return None
return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
file_of: Callable[[str], int | None] | None = None) -> int | None:
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
if code in FILE_ROAS:
return file_of(code) if file_of else None
mcode = ROAS_SALES_CODE.get(code)
return None if mcode is None else roas(sales_of(mcode), spend)
ROCKET_DATE_COL = 0 # 1열 날짜
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
NAVER_DATE_COL = 2 # 3열 기간(날짜)
NAVER_AMOUNT_COL = 3 # 4열 총비용
NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
class AdMigrationNeeded(Exception):
"""광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
@dataclass
class ParseResult:
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
errors: list[str] = field(default_factory=list)
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
# 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
roas: dict[date, Decimal] = field(default_factory=dict)
metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
empty_days: list[date] = field(default_factory=list) # 날짜 줄은 있는데 금액이 한 줄도 없던 날(저장 안 함)
# ════════════════════════════════════════════════════════════
# 파일 읽기
# ════════════════════════════════════════════════════════════
def _decode_csv(content: bytes) -> str:
for enc in ("utf-8-sig", "cp949"):
try:
return content.decode(enc)
except UnicodeDecodeError:
continue
raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).")
def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]:
"""CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로)."""
if not content:
raise UploadError("빈 파일입니다.")
if len(content) > MAX_FILE_BYTES:
raise UploadError("파일이 너무 큽니다(5MB 이하).")
is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx")
if not is_xlsx:
return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))]
try:
import openpyxl # noqa: WPS433
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None
try:
return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)]
finally:
wb.close()
def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult:
"""쿠팡(윙·로켓) 광고 보고서 → (날짜, 그날 19열 청구금액(+부가가치세) 합). 1열에 날짜가 있고 19열에 값이 있는 줄만,
같은 날짜는 더한다. 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
rows = read_rows(content, filename)
res = ParseResult()
sums: dict[date, int] = {}
dated: set[date] = set()
for r, row in enumerate(rows, start=1):
raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_DATE_COL else None
text = str(raw_day or "").strip()
if not text or text.replace(" ", "") in SKIP_LABELS:
res.skipped += 1
continue
try:
day = parse_date(raw_day)
except ValueError:
if r == 1: # 머리글
res.skipped += 1
continue
res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).")
continue
if day is None:
res.skipped += 1
continue
raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None
try:
amt = parse_amount(raw_amt)
except ValueError:
res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).")
continue
dated.add(day)
if amt is None:
res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀
elif abs(amt) > MAX_AMOUNT:
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
else:
sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다
if len(sums) > MAX_DATA_ROWS:
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
if len(res.errors) > MAX_ERRORS:
break
res.entries = sorted(sums.items())
res.empty_days = sorted(d for d in dated if d not in sums and d <= today)
# 날짜 줄은 있는데 청구금액이 한 줄도 없는 파일(그 달 광고비 0 등)은 오류가 아니라 넘어간다(2026-10-14 사용자 요청).
# 날짜 줄 자체가 없을 때만 양식 오류.
if not dated and not res.errors:
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
return res
def _number(value: Any) -> Decimal | None:
"""숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
if value is None or (isinstance(value, str) and not value.strip()):
return None
if isinstance(value, bool):
raise ValueError
text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
try:
num = Decimal(text)
except InvalidOperation:
raise ValueError from None
if not num.is_finite():
raise ValueError
return num
def _json_num(num: Decimal | None) -> Any:
if num is None:
return None
return int(num) if num == num.to_integral_value() else float(round(num, 2))
def _norm(name: Any) -> str:
return str(name or "").replace(" ", "")
# 네이버 보고서 ROAS = "구매완료 광고수익률(%)"(2026-10-20 사용자 확인). 그 칸이 없거나 비면
# 구매완료 전환매출액 ÷ 총비용 × 100 으로 계산한다(같은 정의 — 총 전환매출액은 정의가 달라 쓰지 않음).
NAVER_ROAS_KEY = "구매완료광고수익률"
NAVER_REVENUE_KEY = "구매완료전환매출액"
def roas_from_metrics(metrics: Mapping[str, Any] | None, amount: int | None) -> Decimal | None:
"""보고서 항목(머리글 → 값)에서 ROAS(%) — 광고수익률 칸, 없으면 전환매출액 ÷ 광고비. 못 구하면 None.
저장된 roas 가 빈 예전 업로드(열 위치가 달라 12열이 비었던 파일)도 이것으로 다시 구한다(db.ad_roas)."""
if not isinstance(metrics, Mapping):
return None
for key in (NAVER_ROAS_KEY, NAVER_REVENUE_KEY):
for k, v in metrics.items():
if key not in _norm(k) or isinstance(v, bool) or not isinstance(v, (int, float, Decimal)):
continue
if key == NAVER_ROAS_KEY:
return Decimal(str(v))
if amount and int(amount) > 0:
return (Decimal(str(v)) * 100 / int(amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
return None
def _naver_cols(header: tuple[str, ...]) -> tuple[int, int | None]:
"""머리글로 (총비용 열, ROAS 열) 찾기 — 네이버 보고서는 열 구성을 바꿀 수 있어 고정 위치(4열·12열)가 어긋난다.
머리글에 없으면 예전 고정 위치. ROAS 는 머리글은 있는데 광고수익률 칸이 없으면 None(전환매출액으로 계산)."""
names = [_norm(h) for h in header]
amount = next((i for i, n in enumerate(names) if n.startswith("총비용")), NAVER_AMOUNT_COL)
roas_col = next((i for i, n in enumerate(names) if NAVER_ROAS_KEY in n), None)
if roas_col is None and not any(names):
roas_col = NAVER_ROAS_COL
return amount, roas_col
def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(구매완료 광고수익률) + 나머지 항목. 잘못된 줄이 있으면 errors.
총비용·ROAS 열은 머리글 이름으로 찾는다(없으면 4열·12열)."""
rows = read_rows(content, filename)
res = ParseResult()
header: tuple[Any, ...] = ()
amount_col, roas_col = NAVER_AMOUNT_COL, NAVER_ROAS_COL
seen: dict[date, int] = {}
for r, row in enumerate(rows, start=1):
raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_DATE_COL else None
text = str(raw_day or "").strip()
if not text or text.replace(" ", "") in SKIP_LABELS:
res.skipped += 1
continue
try:
day = parse_date(raw_day)
except ValueError:
if not header: # 머리글(1행 "기간")
header = tuple(str(h or "").strip() for h in row)
amount_col, roas_col = _naver_cols(header)
res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
res.skipped += 1
continue
res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
continue
if day is None:
res.skipped += 1
continue
try:
amt = parse_amount(row[amount_col] if len(row) > amount_col else None)
except ValueError:
res.errors.append(f"{r}행 {amount_col + 1}열: 총비용이 숫자가 아닙니다.")
continue
try:
ro = _number(row[roas_col] if roas_col is not None and len(row) > roas_col else None)
except ValueError:
res.errors.append(f"{r}행 {(roas_col or 0) + 1}열: 광고수익률(ROAS)이 숫자가 아닙니다.")
continue
if amt is None:
res.errors.append(f"{r}행 {amount_col + 1}열: {day.isoformat()} 총비용이 비어 있습니다.")
elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
elif day in seen:
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
else:
seen[day] = r
res.entries.append((day, amt))
m: dict[str, Any] = {}
for i, v in enumerate(row):
name = header[i] if i < len(header) else f"{i + 1}열"
if i in NAVER_SKIP_COLS or not name:
continue
try:
m[name] = _json_num(_number(v))
except ValueError:
m[name] = str(v)[:100]
res.metrics[day] = m
if ro is None:
ro = roas_from_metrics(m, amt) # 광고수익률 칸이 없거나 빈 파일 — 전환매출액 ÷ 총비용
if ro is not None:
res.roas[day] = ro
if len(res.entries) > MAX_DATA_ROWS:
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
if len(res.errors) > MAX_ERRORS:
break
if not res.entries and not res.errors:
raise UploadError("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
return res
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
PARSERS: dict[str, Callable[..., ParseResult]] = {
"naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
UPLOAD_HELP = {
"naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
"나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
MAX_UPLOAD_FILES = 30
def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseResult, list[date]]:
"""여러 파일(이름, 파일 수정 시각, 읽은 결과)을 하나로 — 같은 날짜가 여러 파일에 있으면 **파일 날짜(수정 시각)가 최신인
파일** 값(같으면 나중에 올린 파일). 돌려주는 값: (합친 결과, 여러 파일에 겹친 날짜). 오류는 파일 이름을 앞에 붙여 모은다."""
merged = ParseResult()
owner: dict[date, tuple[float, int]] = {}
overlap: set[date] = set()
empty: set[date] = set()
for idx, (name, modified, res) in enumerate(parsed):
merged.errors.extend(f"[{name}] {e}" for e in res.errors)
empty.update(res.empty_days)
merged.skipped += res.skipped
for c in res.columns:
if c not in merged.columns:
merged.columns.append(c)
picked: dict[date, tuple[int, int]] = {}
for idx, (name, modified, res) in enumerate(parsed):
for day, amt in res.entries:
key = (float(modified or 0), idx)
if day in owner:
overlap.add(day)
if key < owner[day]:
continue
owner[day] = key
picked[day] = (idx, amt)
for day in sorted(picked):
idx, amt = picked[day]
res = parsed[idx][2]
merged.entries.append((day, amt))
if day in res.roas:
merged.roas[day] = res.roas[day]
if day in res.metrics:
merged.metrics[day] = res.metrics[day]
merged.empty_days = sorted(d for d in empty if d not in picked) # 어느 파일에도 값이 없던 날
return merged, sorted(overlap)
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
cols: list[str] = []
for r in rows:
for k in (r.get("metrics") or {}):
if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
cols.append(k)
sums: dict[str, Decimal] = {}
for r in rows:
for k, v in (r.get("metrics") or {}).items():
if k.startswith("_"):
continue
if isinstance(v, (int, float)) and not isinstance(v, bool):
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
for k in cols:
if "클릭률" in k and sums.get("노출수"):
total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
elif ("수익률" in k or "ROAS" in k.upper()):
spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
total[k] = float(round(rev / spend, 2)) if spend else None
elif "환율" in k: # 외화 광고 계정 적용 환율(메타 USD 계정, 2026-10-16) — 더하지 않고 광고비 가중 평균
pairs = [(Decimal(str((r.get("metrics") or {})[k])), int(r.get("amount") or 0)) for r in rows
if isinstance((r.get("metrics") or {}).get(k), (int, float)) and int(r.get("amount") or 0) > 0]
weight = sum(w for _v, w in pairs)
total[k] = float(round(sum(v * w for v, w in pairs) / weight, 2)) if weight else None
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
"roas": float(r["roas"]) if r.get("roas") is not None else None,
"values": {k: v for k, v in (r.get("metrics") or {}).items() if not k.startswith("_")}} for r in rows]
cols, labels = _roas_next_to_spend(cols)
return {"columns": cols, "labels": labels, "rows": out_rows, "total": total}
# 상세 표의 광고비 열 — 네이버 "총비용"(4열), 구글 "광고비(부가세 포함)", 메타 "지출 금액(부가세 포함)"
_SPEND_COL_MARKS = ("총비용", "광고비(", "지출 금액(부가세")
def _roas_next_to_spend(cols: list[str]) -> tuple[list[str], dict[str, str]]:
"""ROAS 열을 광고비 열 바로 오른쪽으로 옮긴다(2026-10-20 사용자 요청 — 네이버 파일은 12열이라 멀리 떨어져 있었다).
네이버 "구매완료 광고수익률(%)" 은 머리글을 "ROAS(%)" 로 보여 준다(값·키는 파일 머리글 그대로, labels 로만).
반환: (열 순서, {열: 화면 머리글})."""
roas_col = next((k for k in cols if "수익률" in k or "ROAS" in k.upper()), None)
spend_col = next((k for k in cols if any(m in k for m in _SPEND_COL_MARKS)), None)
labels: dict[str, str] = {}
if roas_col is None:
return cols, labels
if "ROAS" not in roas_col.upper():
labels[roas_col] = "ROAS(%)"
if spend_col is None:
return cols, labels
out = [k for k in cols if k != roas_col]
out.insert(out.index(spend_col) + 1, roas_col)
return out, labels
def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""상세보기 탭 — 계정별 값(ACCOUNTS_KEY)이 있는 채널(메타, 2026-10-16)은 [합계 | 계정…], 없으면 탭 없음.
계정 탭 = 그 계정이 광고를 낸 날만(그날 행의 계정 값으로 detail_table). 계정 이름은 가장 최근 날의 이름,
순서는 기간 광고비가 큰 계정부터(같으면 이름). accounts_missing = 광고비가 있는데 계정별 값이 없는 날 수
(계정별 저장 전에 가져온 날 — 다시 불러오면 생긴다)."""
per: dict[str, list[dict[str, Any]]] = {}
names: dict[str, str] = {}
missing = 0
for r in rows:
accs = (r.get("metrics") or {}).get(ACCOUNTS_KEY)
if not isinstance(accs, dict):
if int(r.get("amount") or 0):
missing += 1
continue
for acc, a in accs.items():
if not isinstance(a, dict):
continue
names[acc] = str(a.get("name") or f"act_{acc}")
per.setdefault(acc, []).append({"date": r["date"], "amount": int(a.get("amount") or 0),
"roas": a.get("roas"), "metrics": a.get("metrics") or {}})
if not per:
return {"tabs": [], "accounts_missing": 0}
spend = {acc: sum(x["amount"] for x in days) for acc, days in per.items()}
order = sorted(per, key=lambda acc: (-spend[acc], names[acc]))
tabs = [{"key": "total", "label": "합계", **detail_table(rows)}]
tabs += [{"key": acc, "label": names[acc], "account_id": acc, **detail_table(per[acc])} for acc in order]
return {"tabs": tabs, "accounts_missing": missing}
# ════════════════════════════════════════════════════════════
# 화면 데이터
# ════════════════════════════════════════════════════════════
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None,
holidays: Mapping[str, str] | None = None,
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
codes = list(CHANNEL_CODES)
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
ref = period.end if period.end < today else today if period.start <= today else period.start
month_period = calc.resolve_period("month", ref)
year_period = calc.resolve_period("year", ref)
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
q_end = max(period.end, year_period.end)
migration_needed = False
try:
amounts, sources = store.ad_amounts(q_start, q_end)
except AdMigrationNeeded:
amounts, sources, migration_needed = {}, {}, True
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
roas_reader = getattr(store, "ad_roas", None)
try:
roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
except AdMigrationNeeded:
roas_map = {}
cur = calc.sum_range(cells, codes, period.start, period.end)
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
total_codes = list(sales_codes)
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
want = set(mcodes)
return sum(v for (d, c), v in sales.items() if c in want and s <= d <= e)
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
word = {"day": "오늘" if period.start == today else "해당일",
"week": "이번주" if period.start <= today <= period.end else "해당 주",
"month": "이번달" if period.start <= today <= period.end else "해당 월",
"year": "올해" if period.start <= today <= period.end else "해당 연도",
"custom": "선택 기간"}[period.kind]
kpis = [
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
]
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if k == "custom":
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
return f"?period={k}&d={anchor_d.isoformat()}"
if period.kind == "custom":
from datetime import timedelta # noqa: WPS433
length = timedelta(days=period.days)
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
else:
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
nav = {"prev": prev_url, "next": next_url, "quick": [
{"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today},
{"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end},
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
]}
share = calc.by_code(cells, codes, period.start, period.end)
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
# 칸마다 ROAS — "광고비(ROAS%)" 로 보인다. 행 기간 = 그 날·주·월(합계 행은 선택 기간)
for row in table:
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
lambda f: file_roas(f, roas_map, amounts, s, e)) for c in codes}
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
m_s, m_e = month_period.start, month_period.end
for r in month["rows"]:
r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
year = calc.year_months(year_period.start.year, codes, cells, today=today)
for i, r in enumerate(year["rows"], start=1):
s = date(year_period.start.year, i, 1)
r["roas"] = None if r.get("future") or not total_codes else roas(sales_sum(total_codes, s, calc.month_end(s)), r["gross"] or 0)
year["total"]["roas"] = roas(sales_sum(total_codes, year_period.start, year_period.end), year["total"]["gross"]) if total_codes else None
return {
"nav": nav,
"period": period,
"period_kind": period.kind,
"today": today.isoformat(),
"codes": codes,
"names": dict(CHANNEL_NAMES),
"kpis": kpis,
"table": table,
"month": month,
"year": year,
"roas_basis": {c: roas_basis(c) for c in codes},
"detail_channels": sorted(DETAIL_CHANNELS),
"chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
# 업로드로 들어온 칸(표시용) — "날짜|채널"
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "upload" and period.start <= d <= period.end),
# 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자)
"api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "api" and period.start <= d <= period.end),
# 계산식으로 입력한 칸(마이그레이션 008) — "날짜|채널" → 식(파랑 굵은 숫자, 누르면 식)
"formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in
(store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas")
and not migration_needed else {}).items()},
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
"migration_needed": migration_needed,
}
+183
View File
@@ -0,0 +1,183 @@
"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
- 광고비 탭 [광고비 업데이트](보고 있는 기간, 진행 창 — jobs kind="ads", 2026-10-20) · 매출 자동 업데이트와 같은 회차
(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다. 진행 창에서 채널별 [중지]·[업데이트 취소] = 저장 직전까지 받아들임.
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
"""
from __future__ import annotations
import logging
import threading
from datetime import date
from typing import Any, Callable
from .ad_sources.registry import all_sources, get_source
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, Cancelled
from .credentials import CredentialService
from .db import AdCredentialTable
from .security.redact import redact_text
logger = logging.getLogger("performance.ad_sync")
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
AD_MESSAGE_MAX = 1200 # 광고 연동 오류 문구 길이 한도(비밀값 가린 뒤)
_locks: dict[str, threading.Lock] = {}
_locks_guard = threading.Lock()
def _lock(code: str) -> threading.Lock:
with _locks_guard:
return _locks.setdefault(code, threading.Lock())
class AdSyncBusy(Exception):
"""같은 광고 채널 가져오기가 이미 진행 중."""
def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService:
"""광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표."""
return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS)
class AdSyncService:
def __init__(self, store: Any, creds: CredentialService) -> None:
self._store = store
self._creds = creds
def configured(self) -> dict[str, bool]:
return self._creds.configured_codes(list(all_sources()))
def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
cleared: set[str] | None = None) -> AdapterContext:
trial = values is not None or bool(cleared)
acc = self._creds.accessor(code, overrides=values, persist=not trial, user=user, cleared=cleared)
return AdapterContext(code=code, credentials=acc, timeout_sec=30.0)
@staticmethod
def _message(exc: Exception, ctx: AdapterContext) -> str:
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
# 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 300자에서 자르면 안내가 잘린다(2026-10-16 메타 #200 진단)
return redact_text(str(getattr(exc, "message", "") or exc), known, max_len=AD_MESSAGE_MAX)
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
cleared: set[str] | None = None) -> dict[str, Any]:
"""values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험, cleared = 화면에서 비운 항목(빈 값으로) —
그때는 상태를 기록하지 않는다."""
src = get_source(code)
if src is None:
return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."}
ctx = self._ctx(code, values=values, user=user, cleared=cleared)
trial = bool(values) or bool(cleared)
try:
src.require_configured(ctx)
msg = src.test_connection(ctx)
ok, status = True, "ok"
except AdapterError as exc:
ok, status, msg = False, exc.status, self._message(exc, ctx)
except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게
logger.exception("ad test failed: %s", code)
ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}"
if not trial:
self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test")
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg,
"unsaved": trial}
def sync(self, code: str, start: date, end: date, *, user: str = "", progress: Any = None) -> dict[str, Any]:
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy.
progress(jobs.ShopProgress) 를 주면 수집(절반) → 저장 → 완료로 알리고, 저장 직전 중지·취소를 받아 Cancelled."""
src = get_source(code)
if src is None:
raise KeyError(code)
lock = _lock(code)
if not lock.acquire(blocking=False):
raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.")
try:
ctx = self._ctx(code, user=user)
try:
src.require_configured(ctx)
if progress is not None:
progress.plan(2, "단계")
days = src.fetch_days(ctx, start, end)
if progress is not None:
progress.step(1, items=len(days))
progress.begin_saving() # 여기까지 받은 [중지]·[취소]는 저장하지 않고 멈춤
except Cancelled:
raise # 오류가 아니다 — 상태 기록 없이 sync_all 이 "중지됨/취소됨"
except AdapterError as exc:
msg = self._message(exc, ctx)
self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync")
return {"ok": False, "code": code, "name": src.name, "status": exc.status,
"label": STATUS_LABELS.get(exc.status, exc.status), "message": msg}
saved = self._store.replace_ad_api_range(
code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API")
self._store.record_ad_status(code, status="ok", ok=True, kind="sync")
return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days),
"from": start.isoformat(), "to": end.isoformat()}
finally:
lock.release()
def sync_all(self, start: date, end: date, *, user: str = "", job: Any = None) -> list[dict[str, Any]]:
"""설정이 끝난 광고 연동 전부([광고비 업데이트]·자동 업데이트 회차). 채널별로 실패를 격리한다.
job(jobs.SyncJob kind="ads") 을 주면 채널별 진행 막대로 알린다."""
codes = [c for c, ok in self.configured().items() if ok]
shops = job.set_targets([(c, get_source(c).name, True) for c in codes], start, end) if job is not None else {}
out = []
for code in codes:
prog = shops.get(code)
if prog is not None and prog.cancel_requested: # 차례가 오기 전에 중지·취소됨
prog.cancelled()
out.append({"ok": False, "code": code, "cancelled": True})
continue
if prog is not None:
prog.start()
try:
res = self.sync(code, start, end, user=user, progress=prog)
except Cancelled:
if prog is not None:
prog.cancelled()
out.append({"ok": False, "code": code, "cancelled": True})
continue
except AdSyncBusy as exc:
res = {"ok": False, "code": code, "skipped": True, "message": str(exc)}
except Exception as exc: # noqa: BLE001 — 다음 채널은 계속
logger.exception("ad sync failed: %s", code)
res = {"ok": False, "code": code, "status": "api_error", "label": STATUS_LABELS["api_error"],
"message": f"가져오기 중 오류: {type(exc).__name__}"}
if prog is not None:
if res.get("ok"):
prog.finish(upserted=int(res.get("days") or 0),
message=f"광고비 ₩{int(res.get('total') or 0):,}")
elif res.get("skipped"):
prog.skip(str(res.get("message") or ""))
else:
prog.fail(status=str(res.get("status") or "api_error"), label=str(res.get("label") or ""),
message=str(res.get("message") or ""))
out.append(res)
return out
def run_ad_job(store: Any, ring_loader: Callable[[], Any], job: Any, start: date, end: date, *,
user: str = "") -> list[dict[str, Any]]:
"""광고비 업데이트 작업 하나를 끝까지 돌리고 job.finish — [광고비 업데이트] 스레드·자동 업데이트 회차가 쓴다."""
error, results = "", []
try:
results = AdSyncService(store, ad_credentials(store, ring_loader)).sync_all(start, end, user=user, job=job)
except Exception as exc: # noqa: BLE001 — 스레드 밖으로 새지 않게, 화면에는 "오류"로
logger.exception("ad sync job failed")
error = f"광고비 업데이트 중 오류: {type(exc).__name__}"
if job is not None:
job.finish(error=error, last_update_at=last_ad_update_at(store))
return results
def last_ad_update_at(store: Any) -> str | None:
"""광고비 마지막 업데이트 — 광고 API 채널의 마지막 성공 가져오기 시각 중 가장 최근(없으면 None)."""
try:
rows = store.ad_source_statuses()
except Exception: # noqa: BLE001 — 007 미적용 등
return None
times = [str(r.get("last_success_sync_at")) for r in rows.values() if r.get("last_success_sync_at")]
return max(times) if times else None
+15
View File
@@ -33,6 +33,7 @@ STATUS_LABELS: dict[str, str] = {
"unknown": "확인 전",
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
"manual": "수동 입력", # 화면 전용 — API 없이 수동 입력만 쓰는 쇼핑몰(manual_only)
}
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
@@ -82,6 +83,7 @@ class CredentialField:
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
multiline=True 면 여러 줄 입력칸(서비스 계정 JSON 키 등).
"""
key: str
@@ -91,6 +93,7 @@ class CredentialField:
help: str = ""
placeholder: str = ""
internal: bool = False
multiline: bool = False
@dataclass
@@ -128,6 +131,16 @@ class SaleEvent:
raise ValueError("취소/반품 금액은 음수(또는 0)여야 합니다.")
def credential_fingerprint(credentials: Any, keys: Iterable[str]) -> str:
"""토큰을 발급한 인증정보 묶음의 지문(SHA-256 16진수) — 원문은 남기지 않는다(2026-10-15 검토 F04).
저장된 토큰은 이 지문이 지금 인증정보(연결 테스트의 새 입력값 포함)와 같을 때만 다시 쓴다 —
계정·키를 바꾸면 이전 계정 토큰을 쓰지 않고, 같은 값을 다시 저장하면 토큰을 새로 받지 않는다."""
import hashlib # noqa: WPS433
raw = "\x1f".join(f"{k}={(credentials.get(k) or '').strip()}" for k in keys)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
class CredentialAccessor(Protocol):
def get(self, key: str) -> str: ...
@@ -175,6 +188,8 @@ class MarketplaceAdapter(ABC):
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
docs_url: str = ""
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
# True 면 API 연동이 없는 수동 입력 전용 쇼핑몰 — 매출 업데이트에서 빠지고, 인증 설정·연결 테스트가 없다.
manual_only: bool = False
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
+10 -5
View File
@@ -488,23 +488,27 @@ class Cafe24Adapter(MarketplaceAdapter):
marketplace_code=target,
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}-PAY", external_order_id=oid,
order_date=_day(order.get("order_date")), payment_date=pay_day, event_date=pay_day,
amount=max(0, order_total(order)), product_name=name,
# 적립금 사용분은 매출에서 뺀다(2026-10-19 사용자 요청) — 결제합계 − 적립금(points_spent_amount)
amount=max(0, order_total(order) - order_amounts(order)["points_spent_amount"]), product_name=name,
quantity=sum(int(i.get("quantity") or 0) for i in items), order_status="결제완료",
discount_amount=sum(order_amounts(order)[k] for k in DISCOUNT_FIELDS + COUPON_FIELDS),
raw={"order_id": oid, "market_id": order.get("market_id"), "order_place_id": order.get("order_place_id"),
"items": len(items), **{f"initial_{k}": v for k, v in order_amounts(order).items()}},
"items": len(items), **{f"initial_{k}": v for k, v in order_amounts(order).items()},
"points": order_amounts(order)["points_spent_amount"], "points_excluded": True},
)]
def normalize_refund(self, refund: dict[str, Any]) -> list[SaleEvent]:
"""환불 → CANCEL/RETURN(−). 원 주문의 market_id 로 결제와 같은 쇼핑몰 열에 넣는다.
금액 = 실제 환불액 + 적립금·예치금 환불(카페24 일별 매출 환불합계와 같음, 실데이터 확인)."""
금액 = 실제 환불액 + 예치금 환불 — 적립금으로 돌려준 금액은 뺀다(2026-10-19, 결제에서 적립금을 빼므로 앞뒤를 맞춤.
예전 = 카페24 일별 매출 환불합계와 같은 실제 + 적립금·예치금)."""
if refund.get("_kind") == "claim":
return self.normalize_claim(refund)
day = _day(refund.get("refund_date"))
code = str(refund.get("refund_code") or "")
if day is None or not code:
return []
amount = refund_total(refund)
points = _won(refund.get("used_points"))
amount = refund_total(refund) - points
return [SaleEvent(
marketplace_code=target_code(refund.get("_market_id"), refund.get("_order_place_id")),
event_type="RETURN" if code.upper().startswith("R") else "CANCEL",
@@ -515,7 +519,8 @@ class Cafe24Adapter(MarketplaceAdapter):
raw={"refund_code": code, "order_id": refund.get("order_id"), "status": refund.get("status"),
"actual_refund_amount": refund.get("actual_refund_amount"),
"used_points": refund.get("used_points"), "used_credits": refund.get("used_credits"),
"quantity": refund.get("quantity"), "order_item_code": refund.get("order_item_code")},
"quantity": refund.get("quantity"), "order_item_code": refund.get("order_item_code"),
"points": -points, "points_excluded": True},
)]
def normalize_claim(self, c: dict[str, Any]) -> list[SaleEvent]:
+475 -35
View File
@@ -8,12 +8,23 @@
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
· 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
· 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
매출 수집 — 맞출 화면: WING → 비즈니스 인사이트 → **판매분석**(판매자배송 + 로켓그로스, 날짜 선택) 의 "매출(원)"
(2026-10-12 사용자 지정). 판매분석 자체를 주는 Open API 는 없다(2026-10-12 developers.coupang.com API 목록 확인) —
그래서 주문 API 두 개를 결제일(한국 시간)로 합친다:
- 판매자배송: 발주서 목록(일단위 페이징) GET /v2/providers/openapi/apis/api/v5/vendors/{vendorId}/ordersheets
?createdAtFrom=yyyy-mm-dd+09:00&createdAtTo=…&status=…&maxPerPage=50&nextToken=
— 주문일 기준·한 번에 31일까지·상태(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING)마다 따로.
결제일(paidAt)로 다시 거른다(주문일 하루 앞부터 조회). 줄 금액 = orderPrice(판매가 × 수량, 쿠폰 할인 전).
완료된 반품·결제 전 취소된 발주서는 이 목록에 없다(쿠팡 안내).
- 로켓그로스: 주문 목록 GET /v2/providers/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders
?paidDateFrom=yyyymmdd&paidDateTo=yyyymmdd&nextToken= — 결제일 기준·30일까지·분당 50회.
줄 금액 = unitSalesPrice × salesQuantity. 쿠팡 안내상 **출고된 주문만** 나온다(오늘 주문은 출고 뒤에 잡힐 수 있음).
- SALE = 주문 하나(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), 날짜 = 결제일.
결제 뒤 취소된 줄(canceled·cancelCount)도 결제일 매출에 둔다(지난 날짜가 나중에 줄지 않게) — 금액은 참고로 따로.
판매분석 "매출" 의 정확한 정의(할인 전·후, 취소 포함 여부)는 공개 문서가 없어 **설정 → 쇼핑몰 원본 데이터 확인**
(reconcile)의 날짜별 후보 금액을 WING 숫자와 비교해 확정한다. 구매자 이름·연락처·주소는 저장·표시하지 않는다.
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 여기에 넣지 않는다.
"""
from __future__ import annotations
@@ -21,19 +32,53 @@ from __future__ import annotations
import hashlib
import hmac
import time
from typing import Any
from datetime import date, datetime, timedelta, timezone
from typing import Any, Iterable
from urllib.parse import quote, urlencode
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .naver import field_summary, flatten
HOST = "https://api-gateway.coupang.com"
ORDERS_PATH = "/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets"
RG_ORDERS_PATH = "/v2/providers/rg_open_api/apis/api/v1/vendors/{vendor}/rg/orders"
EVENT_PREFIX = "coupang:"
RG_PREFIX = "coupang:rg:"
STATUSES = ("ACCEPT", "INSTRUCT", "DEPARTURE", "DELIVERING", "FINAL_DELIVERY", "NONE_TRACKING")
STATUS_KO = {"ACCEPT": "결제완료", "INSTRUCT": "상품준비중", "DEPARTURE": "배송지시", "DELIVERING": "배송중",
"FINAL_DELIVERY": "배송완료", "NONE_TRACKING": "업체직송", "RG": "로켓그로스"}
ORDER_SPAN_DAYS = 31 # 발주서 목록 한 번에 조회할 수 있는 기간(시작·끝 포함)
RG_SPAN_DAYS = 30 # 로켓그로스 주문 목록 한 번에 조회할 수 있는 기간
PAGE_SIZE = 50
MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
RETRY_429 = 3
RETRY_TIMEOUT_1DAY = 2 # 하루 구간도 시간 초과면 잠깐 쉬고 다시 부르는 횟수
PROBE_MAX_DAYS = 31
KST_OFFSET = timedelta(hours=9)
class GatewayTimeout(ApiError):
"""쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다."""
class TooManyPages(ApiError):
"""한 번 조회가 끝까지 받았는지 확인되지 않음(쪽 수 상한·커서 반복) — 조회 기간을 줄여 다시 부른다(F05)."""
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
def signed_date(now: float | None = None) -> str:
@@ -54,14 +99,163 @@ def build_query(params: dict[str, Any]) -> str:
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
def _won(value: Any) -> int:
"""금액 → 원 정수. 쿠팡 Money({"units": 15000, "nanos": 0})·숫자·문자열("27800") 모두."""
if isinstance(value, dict):
return _won(value.get("units")) + int(round((_num(value.get("nanos")) or 0) / 1e9))
n = _num(value)
return int(round(n)) if n is not None else 0
def _num(value: Any) -> float | None:
if value is None or isinstance(value, bool):
return None
try:
return float(str(value).replace(",", "").strip() or 0)
except ValueError:
return None
def _kst_day(value: Any) -> date | None:
"""결제 시각 → 한국 날짜. ISO 문자열("2025-08-01T10:06:12+09:00", 시간대 없으면 한국 시간) 또는
밀리초 타임스탬프(1746093162000, 로켓그로스)."""
if value is None or value == "":
return None
n = _num(value) if not isinstance(value, str) or value.strip().isdigit() else None
if n is not None:
secs = n / 1000 if n > 1e11 else n
return (datetime.fromtimestamp(secs, tz=timezone.utc) + KST_OFFSET).date()
s = str(value).strip().replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(s if "T" in s or " " in s else s[:10])
except ValueError:
try:
return date.fromisoformat(s[:10])
except ValueError:
return None
if dt.tzinfo is not None:
dt = (dt - dt.utcoffset()).replace(tzinfo=None) + KST_OFFSET # type: ignore[operator]
return dt.date()
def spans(start: date, end: date, days: int) -> list[tuple[date, date]]:
"""[start, end] 를 days 일(시작·끝 포함) 이하 구간으로 자른다."""
out, d = [], start
while d <= end:
e = min(end, d + timedelta(days=days - 1))
out.append((d, e))
d = e + timedelta(days=1)
return out
def safe_order(o: dict[str, Any]) -> dict[str, Any]:
"""개인정보 항목을 뺀 발주서(원본 확인·저장용)."""
out = {k: v for k, v in o.items() if k not in PERSONAL_KEYS}
if isinstance(out.get("orderItems"), list):
out["orderItems"] = [{k: v for k, v in it.items() if k not in PERSONAL_ITEM_KEYS}
for it in out["orderItems"] if isinstance(it, dict)]
return out
def line_records(o: dict[str, Any]) -> list[dict[str, str]]:
"""발주서 하나 → 줄(orderItems)마다 평평한 기록 하나 — 원본 확인 표의 항목별 합계용."""
base = flatten({k: v for k, v in safe_order(o).items() if k != "orderItems"})
items = safe_order(o).get("orderItems") or [{}]
return [{**base, **flatten(it, "orderItems")} for it in items]
def seller_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
"""판매자배송 발주서 → 결제일이 [start, end] 인 줄. 같은 발주서가 두 번 와도(상태 사이 이동) 한 번만."""
seen: set[tuple[str, str, str, str]] = set()
out: list[dict[str, Any]] = []
for o in orders:
oid = str(o.get("orderId") or "")
day = _kst_day(o.get("paidAt") or o.get("orderedAt"))
if not oid or day is None or not (start <= day <= end):
continue
box = str(o.get("shipmentBoxId") or "")
first = len(out)
for it in o.get("orderItems") or []:
if not isinstance(it, dict):
continue
key = (oid, box, str(it.get("vendorItemId") or ""), str(it.get("sequenceNo") or ""))
if key in seen:
continue
seen.add(key)
qty = _won(it.get("shippingCount"))
price = _won(it.get("orderPrice")) or _won(it.get("salesPrice")) * qty
cancel_qty = _won(it.get("cancelCount")) + _won(it.get("holdCountForCancel"))
canceled = bool(it.get("canceled")) or (qty > 0 and cancel_qty >= qty)
cancel_amt = price if canceled else (_won(it.get("salesPrice")) * min(cancel_qty, qty) if cancel_qty else 0)
out.append({
"orderId": oid, "_day": day, "order_day": _kst_day(o.get("orderedAt")), "status": str(o.get("status") or ""),
"amount": price, "discount": _won(it.get("discountPrice")), "canceled": cancel_amt, "qty": qty,
"name": str(it.get("sellerProductName") or it.get("vendorItemName") or ""),
"opt": str(it.get("sellerProductItemName") or ""), "ship": 0,
})
# 배송비는 발주서(묶음 배송)마다 한 번 — 그 발주서의 첫 새 줄에(참고용, 매출 제외). 같은 발주서가 또 오면 새 줄이 없어 안 더함
if len(out) > first:
out[first]["ship"] += _won(o.get("shippingPrice")) + _won(o.get("remotePrice"))
return out
def rg_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
"""로켓그로스 주문 → 결제일이 [start, end] 인 줄. 금액 = 단가 × 수량."""
seen: set[tuple[str, str, int]] = set()
out: list[dict[str, Any]] = []
for o in orders:
oid = str(o.get("orderId") or "")
day = _kst_day(o.get("paidAt"))
if not oid or day is None or not (start <= day <= end):
continue
for i, it in enumerate(o.get("orderItems") or []):
if not isinstance(it, dict):
continue
key = (oid, str(it.get("vendorItemId") or ""), i)
if key in seen:
continue
seen.add(key)
qty = _won(it.get("salesQuantity"))
out.append({"orderId": oid, "_day": day, "order_day": day, "status": "RG",
"amount": _won(it.get("unitSalesPrice")) * qty, "discount": 0, "canceled": 0, "qty": qty,
"name": str(it.get("productName") or ""), "opt": "", "ship": 0})
return out
def group_lines(lines: Iterable[dict[str, Any]], prefix: str) -> dict[str, dict[str, Any]]:
"""줄 → 주문 하나(외부 사건 ID 기준)."""
orders: dict[str, dict[str, Any]] = {}
for ln in lines:
eid = f"{prefix}{ln['orderId']}"
o = orders.setdefault(eid, {"event_id": eid, "orderId": ln["orderId"], "_day": ln["_day"],
"order_day": ln.get("order_day"), "amount": 0, "discount": 0, "canceled": 0,
"ship": 0, "qty": 0, "names": [], "opt": "", "statuses": []})
for k in ("amount", "discount", "canceled", "ship", "qty"):
o[k] += int(ln.get(k) or 0)
if ln["name"] and ln["name"] not in o["names"]:
o["names"].append(ln["name"])
o["opt"] = o["opt"] or ln.get("opt") or ""
if ln["status"] and ln["status"] not in o["statuses"]:
o["statuses"].append(ln["status"])
return orders
class CoupangAdapter(MarketplaceAdapter):
code = "coupang"
name = "쿠팡"
name = "쿠팡(윙)"
auth_type = "api_key"
docs_url = "https://developers.coupangcorp.com/"
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://developers.coupang.com/"
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인). 매출은 판매자배송 + 로켓그로스 주문을 "
"결제일로 합칩니다(WING 비즈니스 인사이트 → 판매분석 '매출'과 비교).")
def __init__(self) -> None:
self._last_call = 0.0
self._last_rg_call = 0.0
def credential_fields(self) -> list[CredentialField]:
return [
@@ -71,42 +265,288 @@ class CoupangAdapter(MarketplaceAdapter):
]
# ── 호출 ──────────────────────────────────────────────
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
def _vendor(self, ctx: AdapterContext) -> str:
v = ctx.credentials.get("vendor_id").strip()
if not v:
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
return v
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> dict[str, Any]:
"""GET — 호출 간격 유지(로켓그로스는 분당 50회), 429 는 잠깐 쉬고 다시."""
import httpx # 지연 import
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
if not (access and secret):
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
query = build_query(params)
headers = {"Authorization": authorization("GET", path, query, access, secret),
"Content-Type": "application/json;charset=UTF-8"}
try:
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
try:
body = res.json()
except ValueError:
body = {}
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
if res.status_code in (401, 403):
raise AuthFailed(
f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
if res.status_code >= 400:
raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
return body
what = "로켓그로스 주문" if rg else "발주서"
for attempt in range(RETRY_429 + 1):
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
gap = RG_CALL_INTERVAL_SEC if rg else CALL_INTERVAL_SEC
last = self._last_rg_call if rg else self._last_call
wait = gap - (time.monotonic() - last)
if wait > 0:
time.sleep(wait)
headers = {"Authorization": authorization("GET", path, query, access, secret),
"Content-Type": "application/json;charset=UTF-8"}
try:
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
except httpx.TimeoutException as exc:
raise GatewayTimeout(f"쿠팡 {what} 응답 시간 초과: {type(exc).__name__}") from None
except httpx.HTTPError as exc:
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
finally:
if rg:
self._last_rg_call = time.monotonic()
else:
self._last_call = time.monotonic()
if res.status_code == 429 and attempt < RETRY_429:
time.sleep(2.0 * (2 ** attempt))
continue
try:
body = res.json()
except ValueError:
if res.status_code < 400:
# HTTP 200 이어도 JSON 이 아니면(점검·프록시 안내 페이지 등) 수집 실패 — 빈 목록으로 보면 기간 교체 때
# 그 기간 매출이 지워진다(2026-10-15 검토 F01). 오류 응답(4xx·5xx)은 아래에서 글자로 안내한다.
raise ApiError(f"쿠팡 {what} 응답이 JSON 이 아닙니다(HTTP {res.status_code}) — 점검 중일 수 있어 "
"저장하지 않았습니다. 잠시 뒤 다시 시도하세요.") from None
body = {}
if not isinstance(body, dict):
body = {"data": body}
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()[:300]
if res.status_code in (401, 403):
raise AuthFailed(
f"쿠팡 {what} 조회 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
if res.status_code == 429:
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
if res.status_code in (502, 503, 504):
raise GatewayTimeout(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
if res.status_code >= 400:
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
code = body.get("code")
if isinstance(code, int) and code >= 400:
raise ApiError(f"쿠팡 {what} API 오류({code}): {msg}")
return body
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
@staticmethod
def _page_rows(body: dict[str, Any], what: str) -> list[dict[str, Any]]:
"""한 쪽의 주문 목록 — `data` 가 목록이어야 한다. 목록이 아니면 빈 목록(주문 0건)과 구분해 실패로(F01):
`data` 가 없거나 다른 형식이면 오류, `data: null` 은 성공 표시(code 200·OK/SUCCESS)가 함께 있을 때만 빈 목록."""
data = body.get("data")
if isinstance(data, list):
return [r for r in data if isinstance(r, dict)]
code, msg = body.get("code"), str(body.get("message") or "").strip().upper()
if "data" in body and data is None and (code in (200, "200") or msg in ("OK", "SUCCESS")):
return []
raise ApiError(f"쿠팡 {what} 응답 형식이 예상과 다릅니다(주문 목록 data 없음) — 저장하지 않았습니다. 잠시 뒤 다시 시도하세요.")
def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]:
"""nextToken 으로 끝까지 받는다. 끝(다음 쪽 없음)을 확인하지 못하면 TooManyPages — 일부만 받은 목록으로
기간을 교체하지 않게(2026-10-15 검토 F05). 부르는 쪽이 기간을 나눠 다시 부른다.
- MAX_PAGES 를 다 써도 다음 쪽이 남음 · 같은 nextToken 이 다시 옴(커서 반복) → TooManyPages
- 빈 쪽인데 다음 쪽이 있으면 따라간다(예전엔 거기서 끝난 것으로 봤다)"""
what = "로켓그로스 주문" if rg else "발주서"
out: list[dict[str, Any]] = []
token: str | None = None
seen: set[str] = set()
for _ in range(MAX_PAGES):
body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg)
out.extend(self._page_rows(body, what))
nxt = str(body.get("nextToken") or "").strip()
if not nxt:
return out # 마지막 쪽 확인
if nxt in seen:
raise TooManyPages(f"쿠팡 {what} 다음 쪽 표시가 반복돼 끝까지 받았는지 확인할 수 없습니다 — 저장하지 않았습니다.")
seen.add(nxt)
token = nxt
raise TooManyPages(f"쿠팡 {what} 한 번 조회가 {MAX_PAGES}쪽을 넘었습니다 — 일부만 받은 채 저장하지 않았습니다.")
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가.
건수가 많은 상태(배송완료 등)는 31일을 한 번에 부르면 쿠팡 서버가 504(시간 초과)를 낸다 — 그러면 그 구간을
반으로 줄여 다시 부르고(하루까지), 줄인 크기는 같은 상태의 다음 구간에도 그대로 쓴다(매번 31일로 실패하지 않게)."""
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
out: list[dict[str, Any]] = []
size_by_status = {st: ORDER_SPAN_DAYS for st in STATUSES}
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
for st in STATUSES:
rows: list[dict[str, Any]] = []
d, tries = a, 0
while d <= b:
e = min(b, d + timedelta(days=size_by_status[st] - 1))
try:
part = self._pages(ctx, path, {"createdAtFrom": f"{d.isoformat()}+09:00",
"createdAtTo": f"{e.isoformat()}+09:00",
"status": st, "maxPerPage": PAGE_SIZE})
except GatewayTimeout as exc:
if size_by_status[st] > 1:
size_by_status[st] = max(1, size_by_status[st] // 2)
continue
tries += 1
if tries <= RETRY_TIMEOUT_1DAY:
time.sleep(3.0 * tries)
continue
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] "
"— 잠시 뒤 다시 시도하세요.") from None
except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패
if size_by_status[st] > 1:
size_by_status[st] = max(1, size_by_status[st] // 2)
continue
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루, 상태 {st}]") from None
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None
rows.extend(part)
d, tries = e + timedelta(days=1), 0
out.extend(rows)
ctx.progress.step(items=len(rows))
return out
def _rg_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
out: list[dict[str, Any]] = []
for a, b in spans(start, end, RG_SPAN_DAYS):
rows: list[dict[str, Any]] = []
d, size, tries = a, RG_SPAN_DAYS, 0
while d <= b: # 시간 초과면 판매자배송과 같이 구간을 반으로(하루까지)
e = min(b, d + timedelta(days=size - 1))
try:
part = self._pages(ctx, path, {"paidDateFrom": d.strftime("%Y%m%d"),
"paidDateTo": e.strftime("%Y%m%d")}, rg=True)
except GatewayTimeout as exc:
if size > 1:
size = max(1, size // 2)
continue
tries += 1
if tries <= RETRY_TIMEOUT_1DAY:
time.sleep(3.0 * tries)
continue
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] "
"— 잠시 뒤 다시 시도하세요.") from None
except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패
if size > 1:
size = max(1, size // 2)
continue
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루]") from None
except ApiError as exc:
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None
rows.extend(part)
d, tries = e + timedelta(days=1), 0
out.extend(rows)
ctx.progress.step(items=len(rows))
return out
def _plan(self, ctx: AdapterContext, start: date, end: date) -> None:
ctx.progress.plan(len(spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS)) * len(STATUSES)
+ len(spans(start, end, RG_SPAN_DAYS)), "조회")
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
self._plan(ctx, start, end)
seller = seller_lines(self._seller_orders(ctx, start, end), start, end)
rg = rg_lines(self._rg_orders(ctx, start, end), start, end)
yield from group_lines(seller, EVENT_PREFIX).values()
yield from group_lines(rg, RG_PREFIX).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 []]
if o.get("canceled"):
statuses.append("취소 포함")
return [SaleEvent(
event_type="SALE", external_event_id=str(o["event_id"]), 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
self.authenticate(ctx)
vendor = ctx.credentials.get("vendor_id").strip()
today = today_kst().isoformat()
body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
{"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
vendor = self._vendor(ctx)
today = today_kst()
body = self._get(ctx, ORDERS_PATH.format(vendor=vendor),
{"createdAtFrom": f"{today.isoformat()}+09:00", "createdAtTo": f"{today.isoformat()}+09:00",
"status": "ACCEPT", "maxPerPage": 1})
n = len(body.get("data") or [])
return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
"매출 수집은 다음 단계에서 구현됩니다.")
rg = self._get(ctx, RG_ORDERS_PATH.format(vendor=vendor),
{"paidDateFrom": today.strftime("%Y%m%d"), "paidDateTo": today.strftime("%Y%m%d")}, rg=True)
m = len(rg.get("data") or [])
return (f"쿠팡 연결 정상(판매자배송 발주서·로켓그로스 주문 조회 권한 확인 — 오늘 결제완료 발주서 {'있음' if n else '없음'}, "
f"로켓그로스 오늘 주문 {m}건{'+' if rg.get('nextToken') else ''}).")
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""결제일 기준 기간(최대 31일)의 판매자배송 발주서·로켓그로스 주문을 실제로 불러, 날짜별 후보 금액을 나란히 —
WING 판매분석 '매출(원)'과 같은 열을 찾아 규칙을 확정하는 용도. 저장하지 않고, 개인정보 항목은 빼고 보여 준다."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
self._plan(ctx, day, to)
probes: list[dict[str, Any]] = []
seller_raw: list[dict[str, Any]] = []
rg_raw: list[dict[str, Any]] = []
try:
seller_raw = self._seller_orders(ctx, day, to)
probes.append({"key": "seller", "label": "판매자배송 발주서(주문일 하루 앞부터, 상태 6개)",
"path": ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(seller_raw),
"fields": field_summary([r for o in seller_raw for r in line_records(o)])})
except AdapterError as exc:
probes.append({"key": "seller", "label": "판매자배송 발주서", "path": ORDERS_PATH.format(vendor="{vendorId}"),
"ok": False, "error": exc.message[:300]})
try:
rg_raw = self._rg_orders(ctx, day, to)
probes.append({"key": "rg", "label": "로켓그로스 주문(결제일, 출고된 주문만)",
"path": RG_ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(rg_raw),
"fields": field_summary([{**flatten({k: v for k, v in o.items() if k != "orderItems"}),
**flatten(it, "orderItems")}
for o in rg_raw for it in (o.get("orderItems") or [{}])])})
except AdapterError as exc:
probes.append({"key": "rg", "label": "로켓그로스 주문", "path": RG_ORDERS_PATH.format(vendor="{vendorId}"),
"ok": False, "error": exc.message[:300]})
seller = seller_lines(seller_raw, day, to)
rg = rg_lines(rg_raw, day, to)
dates = [(day + timedelta(days=i)).isoformat() for i in range((to - day).days + 1)]
def per_day(lines: list[dict[str, Any]], fn: Any) -> dict[str, int]:
out = {d: 0 for d in dates}
for ln in lines:
out[ln["_day"].isoformat()] += int(fn(ln))
return out
def count(lines: list[dict[str, Any]], d: str) -> int:
return len({ln["orderId"] for ln in lines if ln["_day"].isoformat() == d})
s_amt, s_net = per_day(seller, lambda x: x["amount"]), per_day(seller, lambda x: x["amount"] - x["discount"])
s_live = per_day(seller, lambda x: x["amount"] - x["canceled"])
s_qty, r_qty = per_day(seller, lambda x: x["qty"]), per_day(rg, lambda x: x["qty"])
s_cancel, s_ship = per_day(seller, lambda x: x["canceled"]), per_day(seller, lambda x: x["ship"])
r_amt = per_day(rg, lambda x: x["amount"])
ok = {p["key"]: p["ok"] for p in probes}
failed = {p["key"]: p.get("error", "") for p in probes if not p["ok"]}
cands = [
{"label": "① 현재 규칙: 판매자배송 판매가 + 로켓그로스", "days": {d: s_amt[d] + r_amt[d] for d in dates}},
{"label": "② 판매자배송 판매가(쿠폰 할인 전)", "days": s_amt, "error": failed.get("seller")},
{"label": "③ 판매자배송 할인 뒤(판매가 − 쿠폰·쿠팡 할인)", "days": s_net, "error": failed.get("seller")},
{"label": "④ 판매자배송 취소분 뺀 판매가", "days": s_live, "error": failed.get("seller")},
{"label": "⑤ 로켓그로스 단가 × 수량", "days": r_amt, "error": failed.get("rg")},
{"label": "판매량: 판매자배송 + 로켓그로스(개)", "days": {d: s_qty[d] + r_qty[d] for d in dates}},
]
if not all(ok.values()):
cands[0]["error"] = "일부 조회 실패 — 위 표 참고"
days = [{"date": d, "orders": count(seller, d) + count(rg, d), "amount": s_amt[d] + r_amt[d],
"claimed": s_cancel[d], "ship": s_ship[d]}
for d in dates]
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"day_cols": {"amount": "매출(현재 규칙)", "claimed": "그중 판매자배송 취소분(참고)", "ship": "판매자배송 배송비(참고, 매출 제외)"},
"refund_candidates": cands, "candidates_title": "매출 후보 비교 — WING 판매분석 '매출(원)'·'판매량'과 같은 열을 알려 주세요",
"rule": "결제일(한국 시간) 기준 — 판매자배송 발주서 orderPrice(판매가 × 수량, 쿠폰 할인 전, 결제 뒤 취소분 포함) + "
"로켓그로스 unitSalesPrice × salesQuantity(출고된 주문만). 배송비 제외"}
+17 -7
View File
@@ -36,6 +36,7 @@ from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
credential_fingerprint,
AdapterContext,
AdapterError,
ApiError,
@@ -143,7 +144,8 @@ class GsshopAdapter(MarketplaceAdapter):
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
def __init__(self) -> None:
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
# (협력사코드·운영 KEY 지문) → 통과한 (키 변형, 암호화 모드). 키를 바꾸면 예전 방식을 쓰지 않는다(검토 F04)
self._mode: dict[str, tuple[str, str]] = {}
def credential_fields(self) -> list[CredentialField]:
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
@@ -191,7 +193,8 @@ class GsshopAdapter(MarketplaceAdapter):
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
sup, key = self._creds(ctx)
known = self._mode.get(sup)
mode_key = self._mode_key(ctx)
known = self._mode.get(mode_key)
if known:
return self._call(ctx, path, params, known)
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
@@ -202,7 +205,7 @@ class GsshopAdapter(MarketplaceAdapter):
except AuthFailed as exc:
last = exc
continue
self._mode[sup] = how
self._mode[mode_key] = how
return body
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
@@ -220,6 +223,9 @@ class GsshopAdapter(MarketplaceAdapter):
out.extend(rows)
if not body.get("hasMorePage") or not rows:
break
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 기간을 교체하지 않게(검토 F05)
raise ApiError(f"GS샵 {s.isoformat()}~{e.isoformat()} 조회가 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — "
"저장하지 않았습니다.")
ctx.progress.step(items=len(out))
s = e + timedelta(days=1)
return out
@@ -261,15 +267,19 @@ class GsshopAdapter(MarketplaceAdapter):
self.authenticate(ctx)
sup, _ = self._creds(ctx)
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
self._mode.pop(self._mode_key(ctx), 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)}).")
f"토큰 {self._how_label(ctx)}).")
def _how_label(self, sup: str) -> str:
v, m = self._mode.get(sup, ("", ""))
@staticmethod
def _mode_key(ctx: AdapterContext) -> str:
return credential_fingerprint(ctx.credentials, ("vendor_code", "api_key"))
def _how_label(self, ctx: AdapterContext) -> str:
v, m = self._mode.get(self._mode_key(ctx), ("", ""))
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
+357 -6
View File
@@ -1,21 +1,372 @@
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인).
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com
Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키
Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키
channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다)
두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."},
판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"},
연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다."
Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”).
매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함):
- 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=)
— 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음).
목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …).
- 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다.
한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시).
- 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`),
날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합.
- 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice
− adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**.
설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다.
- 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다.
- 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만).
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import re
import time
from datetime import date, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .naver import field_summary, flatten
HOST = "https://kapi.kakao.com"
PAID_PATH = "/v2/shopping/orders/paidAt"
ORDER_PATH = "/v1/shopping/order"
EVENT_PREFIX = "kakao:"
DEFAULT_CHANNELS = "101" # 톡스토어
PAGE_SIZE = 100
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히)
RETRY_429 = 3
PROBE_MAX_DAYS = 31
CACHE_MAX = 20000
# 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준).
UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"})
# 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
CLAIMED_STATUS = frozenset({
"PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete",
"ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete",
})
STATUS_KO = {
"Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중",
"PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청",
"PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료",
"UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중",
"ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료",
"ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청",
"ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료",
"TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료",
"BuyDecision": "구매 결정",
}
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:
""""20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간."""
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
def line_amount(op: dict[str, Any]) -> int:
"""상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외."""
qty = max(1, _won(op.get("quantity")))
gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty
return max(0, gross - line_discount(op))
def line_discount(op: dict[str, Any]) -> int:
return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice"))
# 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김).
PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver")
PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment")
def strip_personal(det: dict[str, Any]) -> dict[str, Any]:
out: dict[str, Any] = {}
for k, v in det.items():
if k in PERSONAL_OBJECTS and isinstance(v, dict):
out[k] = {kk: "" for kk in v}
elif isinstance(v, dict):
out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()}
else:
out[k] = v
return out
def order_detail(body: Any) -> dict[str, Any]:
"""주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움).
감싼 모양(data/content)도 받아들인다."""
if not isinstance(body, dict):
return {}
if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict):
return strip_personal(body)
for k in ("data", "content", "contents"):
v = body.get(k)
if isinstance(v, list) and v and isinstance(v[0], dict):
v = v[0]
if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)):
return strip_personal(v)
return {}
def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
"""주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
pays: dict[str, dict[str, Any]] = {}
for it in items:
row, det = it.get("row") or {}, it.get("detail") or {}
base, op = det.get("orderBase") or {}, det.get("orderProduct") or {}
status = str(row.get("orderStatus") or base.get("status") or "")
day = _day(row.get("paidAt") or base.get("paidAt"))
oid = str(row.get("orderId") or base.get("id") or det.get("id") or "")
pid = str(row.get("paymentId") or base.get("paymentId") or oid)
if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op:
continue
p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
"discount": 0, "names": [], "opt": "", "statuses": [], "orders": [],
"order_day": _day(row.get("createdAt") or base.get("createdAt"))})
amt = line_amount(op)
p["amount"] += amt
if status in CLAIMED_STATUS:
p["claimed"] += amt
p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount"))
p["qty"] += max(1, _won(op.get("quantity")))
p["discount"] += line_discount(op)
p["orders"].append(oid)
name = str(op.get("name") or "")
if name and name not in p["names"]:
p["names"].append(name)
p["opt"] = p["opt"] or str(op.get("optionContent") or "")
if status and status not in p["statuses"]:
p["statuses"].append(status)
return pays
def _err_text(body: dict[str, Any], res: Any) -> str:
parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")]
ex = body.get("extras")
if isinstance(ex, dict):
parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")]
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
class KakaoAdapter(MarketplaceAdapter):
code = "kakao"
name = "카카오"
auth_type = "api_key"
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975"
note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. "
"그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. "
"두 키는 서로 다른 앱의 키여야 합니다.")
def __init__(self) -> None:
self._last_call = 0.0
self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보)
def credential_fields(self) -> list[CredentialField]:
# api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게.
return [
CredentialField("seller_id", "판매자(채널) ID"),
CredentialField("api_key", "API Key", secret=True),
CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True,
help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"),
CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True,
help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"),
CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS,
help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"),
]
# ── 호출 ──────────────────────────────────────────────
def _headers(self, ctx: AdapterContext) -> dict[str, str]:
admin = ctx.credentials.get("admin_key").strip()
seller = ctx.credentials.get("api_key").strip()
if not admin or not seller:
raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.")
channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS
return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}",
"channel-ids": channels, "Accept": "application/json"}
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내)."""
import httpx # 지연 import
headers = self._headers(ctx)
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)
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
try:
body = res.json()
except ValueError:
body = {}
if not isinstance(body, dict):
body = {"contents": body}
code = _won(body.get("code")) if body.get("code") not in (None, "") else 0
text = _err_text(body, res)
if code == -2 or "target-authorization" in text.lower():
raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, "
"어드민 키가 REST API 키가 아닌지 확인하세요.")
if code == -401 or "deactivated" in text:
raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.")
if "매핑" in text or "대행사" in text:
raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 "
"끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.")
if res.status_code in (401, 403):
raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, "
"두 키가 맞는지 확인하세요.")
if res.status_code >= 400 or code < 0:
raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}")
return body
raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
"""결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음."""
params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59",
"size": PAGE_SIZE}
out: list[dict[str, Any]] = []
token = ""
seen: set[str] = set()
for _ in range(MAX_PAGES):
body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})})
rows = [r for r in body.get("contents") or [] if isinstance(r, dict)]
out.extend(rows)
token = str(body.get("token") or "")
if not token or not rows:
break
if token in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
raise ApiError(f"카카오 {d.isoformat()} 주문 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
seen.add(token)
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음
raise ApiError(f"카카오 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
return out
def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]:
oid = str(row.get("orderId") or "")
mod = str(row.get("modifiedAt") or "")
hit = self._details.get(oid)
if hit and hit[0] == mod and mod:
return hit[1]
det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid}))
if det:
if len(self._details) >= CACHE_MAX:
self._details.clear()
self._details[oid] = (mod, det)
return det
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}."""
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
d = start
while d <= end:
rows = self._day_rows(ctx, d)
got = []
for r in rows:
if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS:
got.append({"row": r, "detail": {}})
continue
got.append({"row": r, "detail": self._detail(ctx, r)})
ctx.progress.step(items=len(rows))
yield from got
d += timedelta(days=1)
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
yield from group_payments(self._items(ctx, start, end), start, end).values()
def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]:
pid, day = str(p.get("paymentId") or ""), p.get("_day")
if not pid or day is None:
return []
names = p.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 p.get("statuses") or []]
orders = p.get("orders") or []
return [SaleEvent(
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid,
external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day,
amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200],
quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)),
order_status="/".join(statuses)[:50],
)]
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
rows = self._day_rows(ctx, today_kst())
return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)."
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
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": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]}
flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items]
probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}",
"ok": True, "count": len(items), "fields": field_summary(flat)}]
by_status: dict[str, list[dict[str, str]]] = {}
for it, f in zip(items, flat):
by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f)
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 UNPAID_STATUS else
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus",
"ok": True, "count": len(rows),
"fields": [f for f in field_summary(rows)
if f["sum"] is not None and f["name"].startswith("orderProduct.")]})
pays = group_payments(items, day, to)
days = []
d = day
while d <= to:
day_pays = [p for p in pays.values() if p["_day"] == d]
days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays),
"claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, "
"결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}
@@ -0,0 +1,25 @@
"""수동 입력 전용 쇼핑몰 — API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 넣는다.
어댑터는 쇼핑몰의 "종류"만 알린다: 인증 항목이 없고(manual_only), 매출 업데이트(sync_all)에서 빠진다.
DB(perf_marketplaces)에는 manual_input = TRUE 로 넣는다(마이그레이션 003).
"""
from __future__ import annotations
from .base import MarketplaceAdapter
class ManualOnlyAdapter(MarketplaceAdapter):
auth_type = "manual"
manual_only = True
note = "API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 입력합니다."
class CoupangRocketAdapter(ManualOnlyAdapter):
code = "coupang_rocket"
name = "쿠팡(로켓)"
class AtomyAzmallAdapter(ManualOnlyAdapter):
code = "atomy"
name = "애터미아자몰"
+115 -14
View File
@@ -13,9 +13,12 @@
?from=…&to=…&rangeType=PAYED_DATETIME&pageSize=&page= — 결제일 기준, 한 번에 24시간까지(하루씩 부른다),
from 부터 180일 안의 주문만. 응답에 주문·상품주문 상세가 바로 들어 있다(네이버 안내: 소량·조회용 권장 API).
- SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(order.paymentDate).
금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 — 배송비 제외.
금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 **+ 배송비**(배송 묶음마다 deliveryFeeAmount 한 번, 할인 안 뺌 =
판매분석 '배송비', 2026-10-19 사용자 요청·10/18 실데이터 87,500 확인 — 예전엔 배송비 제외). raw = {goods: 상품 결제금액, ship: 배송비}.
- 결제 뒤 취소·반품된 상품주문도 결제일 매출에 그대로 둔다(판매금액(총)). 입금대기·미입금 취소만 뺀다.
그래서 지난 날짜 매출이 나중에 줄지 않는다. 환불(판매금액(순))은 아직 따로 만들지 않는다.
- **환불 = 환불된 날(클레임 완료일)에 뺀다**(2026-10-19): 같은 조회를 rangeType=CLAIM_COMPLETED_DATETIME 으로 하루씩 —
그날 취소·반품 완료(CANCELED·RETURNED)된 상품주문마다 CANCEL/RETURN(`naver:{productOrderId}-RF`), 금액 = −totalPaymentAmount.
판매분석의 환불금액처럼 결제일이 아니라 환불일 매출에서 빠진다.
- 구매자 이름·연락처·주소는 저장하지 않는다.
"""
@@ -28,6 +31,7 @@ from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
credential_fingerprint,
AdapterContext,
AdapterError,
ApiError,
@@ -172,7 +176,9 @@ def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]:
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
"""상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
금액 = totalPaymentAmount 합(할인 뒤 상품 결제금액, 배송비 제외) = 판매분석 "판매금액(총)".
배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
배송비(ship) = **배송 묶음(packageNumber, 없으면 주문)마다 deliveryFeeAmount 한 번**(묶음 안 최댓값), 배송비 할인은 빼지 않음 —
네이버는 배송비·할인을 상품주문마다 반복해 적는다. 10/18 실데이터: 묶음당 한 번 = 87,500 = 판매분석 배송비
(상품주문마다 배송비 − 할인 = 38,500 은 틀림, 2026-10-19 ship_check 로 확인). 취소/반품분은 참고용(claimed)."""
orders: dict[str, dict[str, Any]] = {}
for c in items:
po, od = c.get("productOrder") or {}, c.get("order") or {}
@@ -182,13 +188,15 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
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": [],
"discount": 0, "names": [], "opt": "", "statuses": [], "_ship_pkg": {},
"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"))
pkg = str(po.get("packageNumber") or oid)
o["_ship_pkg"][pkg] = max(o["_ship_pkg"].get(pkg, 0), _won(po.get("deliveryFeeAmount")))
o["ship"] = sum(o["_ship_pkg"].values())
o["qty"] += _won(po.get("quantity"))
o["discount"] += _won(po.get("productDiscountAmount"))
name = str(po.get("productName") or "")
@@ -200,9 +208,67 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
return orders
def ship_check(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, Any]:
"""배송비 계산 후보 비교(진단, 2026-10-19) — 네이버는 배송비·배송비 할인을 상품주문마다 적어 같은 주문·배송 묶음 안에서
반복될 수 있다. 판매분석 '배송비'와 맞는 셈을 실데이터로 고르려고 후보 합계 + 주문별 상품주문 값(개인정보 없음)을 돌려준다."""
rows = []
for c in items:
po, od = c.get("productOrder") or {}, c.get("order") or {}
day = _day(od.get("paymentDate") or po.get("paymentDate"))
status = str(po.get("productOrderStatus") or "")
if day is None or not (start <= day <= end) or status in EXCLUDED_STATUS:
continue
rows.append({"order": str(od.get("orderId") or po.get("orderId") or ""), "package": str(po.get("packageNumber") or ""),
"status": status, "fee": _won(po.get("deliveryFeeAmount")), "discount": _won(po.get("deliveryDiscountAmount")),
"section": _won(po.get("sectionDeliveryFee")), "policy": str(po.get("deliveryPolicyType") or ""),
"pay": _won(po.get("totalPaymentAmount")), "qty": _won(po.get("quantity"))})
def per(key: str) -> dict[str, int]:
groups: dict[str, list[dict[str, Any]]] = {}
for r in rows:
groups.setdefault(r[key] or r["order"], []).append(r)
return {"groups": len(groups),
"max_fee": sum(max(x["fee"] for x in g) for g in groups.values()),
"max_fee_minus_max_discount": sum(max(0, max(x["fee"] for x in g) - max(x["discount"] for x in g)) for g in groups.values()),
"sum_fee_minus_sum_discount": sum(max(0, sum(x["fee"] - x["discount"] for x in g)) for g in groups.values()),
"with_fee": sum(1 for g in groups.values() if max(x["fee"] for x in g) > 0)}
orders: dict[str, list[dict[str, Any]]] = {}
for r in rows:
orders.setdefault(r["order"], []).append({k: r[k] for k in ("package", "status", "fee", "discount", "section", "policy", "pay", "qty")})
return {
"product_orders": len(rows),
"per_product_order": {"fee": sum(r["fee"] for r in rows), "discount": sum(r["discount"] for r in rows),
"fee_minus_discount": sum(r["fee"] - r["discount"] for r in rows),
"section": sum(r["section"] for r in rows)},
"per_order": per("order"), "per_package": per("package"),
"orders": [{"order": k, "lines": v} for k, v in sorted(orders.items())],
"note": "판매분석 '배송비'와 같은 값의 후보 — 지금 매출 규칙은 per_package.max_fee(묶음마다 배송비 한 번, 할인 안 뺌)",
}
def refund_items(items: Iterable[dict[str, Any]], day: date) -> list[dict[str, Any]]:
"""클레임 완료일 조회 결과 → 환불 줄(상품주문 하나 = 한 줄). 취소·반품 완료만, 금액 = 그 상품주문 결제금액."""
out = []
for c in items:
po, od = c.get("productOrder") or {}, c.get("order") or {}
status = str(po.get("productOrderStatus") or "")
if status not in CLAIMED_STATUS:
continue
out.append({"product_order_id": str(po.get("productOrderId") or c.get("productOrderId") or ""),
"order_id": str(od.get("orderId") or po.get("orderId") or ""), "day": day, "status": status,
"amount": _won(po.get("totalPaymentAmount")), "qty": _won(po.get("quantity")),
"name": str(po.get("productName") or ""), "opt": str(po.get("productOption") or ""),
"order_day": _day(od.get("orderDate")), "pay_day": _day(od.get("paymentDate") or po.get("paymentDate"))})
return out
# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint)
TOKEN_KEYS = ("client_id", "client_secret", "account_id")
class NaverAdapter(MarketplaceAdapter):
code = "naver"
name = "네이버 스마트스토어"
name = "네이버"
auth_type = "oauth"
implemented = True
replace_range = True
@@ -222,6 +288,8 @@ class NaverAdapter(MarketplaceAdapter):
help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
# 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04)
CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True),
]
# ── 인증 ──────────────────────────────────────────────
@@ -233,7 +301,8 @@ class NaverAdapter(MarketplaceAdapter):
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:
same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS)
if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC:
return tok
return self._issue_token(ctx)
@@ -266,6 +335,7 @@ class NaverAdapter(MarketplaceAdapter):
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))
ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS))
return tok
def authenticate(self, ctx: AdapterContext) -> None:
@@ -327,11 +397,12 @@ class NaverAdapter(MarketplaceAdapter):
return body
raise ApiError("네이버 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
def _day_items(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
"""결제일이 d(한국 시간 0시~23:59:59.999)인 상품주문 전체 — 모든 상태."""
def _day_items(self, ctx: AdapterContext, d: date, range_type: str = "PAYED_DATETIME") -> list[dict[str, Any]]:
"""기준일(range_type — 결제일 PAYED_DATETIME · 클레임 완료일 CLAIM_COMPLETED_DATETIME)이 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,
"rangeType": range_type, "pageSize": PAGE_SIZE,
}
out: list[dict[str, Any]] = []
for page in range(1, MAX_PAGES + 1):
@@ -340,10 +411,13 @@ class NaverAdapter(MarketplaceAdapter):
out.extend(items)
if not items or not has_next(body, page, len(items)):
break
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 저장하지 않게(검토 F05)
raise ApiError(f"네이버 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
return out
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
def _items(self, ctx: AdapterContext, start: date, end: date, *, plan: tuple[int, str] | None = None) -> Iterable[dict[str, Any]]:
days = (end - start).days + 1
ctx.progress.plan(*(plan or (days, "일"))) # 진행 막대: 하루 = 한 단계(매출 업데이트는 결제 + 환불 조회 = 하루 두 단계)
d = start
while d <= end:
rows = self._day_items(ctx, d)
@@ -353,7 +427,30 @@ class NaverAdapter(MarketplaceAdapter):
# ── 수집 ──────────────────────────────────────────────
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()
days = (end - start).days + 1
yield from group_orders(self._items(ctx, start, end, plan=(days * 2, "일 조회")), start, end).values()
def fetch_refunds(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""환불 — 클레임 완료일이 그날인 상품주문 중 취소·반품 완료(CANCELED·RETURNED)된 것(2026-10-19). 교환·미입금 취소는 아님."""
d = start
while d <= end:
rows = self._day_items(ctx, d, "CLAIM_COMPLETED_DATETIME")
ctx.progress.step(items=len(rows))
yield from refund_items(rows, d)
d += timedelta(days=1)
def normalize_refund(self, r: dict[str, Any]) -> list[SaleEvent]:
if not r.get("amount") or not r.get("product_order_id"):
return []
is_return = r.get("status") == "RETURNED"
return [SaleEvent(
event_type="RETURN" if is_return else "CANCEL", external_event_id=f"{EVENT_PREFIX}{r['product_order_id']}-RF",
external_order_id=str(r.get("order_id") or r["product_order_id"]), external_line_id=str(r["product_order_id"]),
order_date=r.get("order_day"), payment_date=r.get("pay_day"), event_date=r["day"], amount=-int(r["amount"]),
product_name=str(r.get("name") or "")[:200], option_name=str(r.get("opt") or "")[:200],
quantity=-int(r.get("qty") or 0), order_status="반품완료" if is_return else "취소완료",
raw={"product_order_id": r["product_order_id"], "status": r.get("status"), "refund": int(r["amount"])},
)]
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
oid, day = str(o.get("orderId") or ""), o.get("_day")
@@ -362,9 +459,12 @@ class NaverAdapter(MarketplaceAdapter):
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 []]
goods, ship = max(0, int(o.get("amount") or 0)), max(0, int(o.get("ship") or 0))
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)),
# 판매금액(총) + 배송비(2026-10-19) — 환불은 환불일에 따로(fetch_refunds)
order_date=o.get("order_day"), payment_date=day, event_date=day, amount=goods + ship,
raw={"goods": goods, "ship": ship},
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],
)]
@@ -410,5 +510,6 @@ class NaverAdapter(MarketplaceAdapter):
"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,
"ship_check": ship_check(items, day, to),
"rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, "
"미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}
+5 -1
View File
@@ -14,14 +14,17 @@ from .gmarket import GmarketAdapter
from .gsshop import GsshopAdapter
from .kakao import KakaoAdapter
from .lotteon import LotteonAdapter
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
from .naver import NaverAdapter
from .ohouse import OhouseAdapter
from .toss import TossAdapter
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 003)
Cafe24Adapter(),
NaverAdapter(),
CoupangAdapter(),
CoupangAdapter(), # 쿠팡(윙)
CoupangRocketAdapter(), # 쿠팡(로켓) — 수동 입력 전용
OhouseAdapter(),
GmarketAdapter(),
KakaoAdapter(),
@@ -29,6 +32,7 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
ElevenstAdapter(),
LotteonAdapter(),
TossAdapter(),
AtomyAzmallAdapter(), # 애터미아자몰 — 수동 입력 전용
)
_BY_CODE = {a.code: a for a in _ADAPTERS}
+616 -8
View File
@@ -1,22 +1,630 @@
"""토스쇼핑 — 판매자 API.
"""토스쇼핑 — 토스쇼핑 API(shopping-fep).
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
문서: https://shopping-docs.toss.im/dev (전체 목록 llms.txt, 각 쪽 주소 뒤에 .md 를 붙이면 원문)
인증(공식 방식): 토스쇼핑 파트너스 → 상점 이름 > 가맹점·계정 관리 > 자체 개발 → [키 발급](호출 IP 입력) →
Access Key·Secret Key. OAuth2 client_credentials 로 토큰을 받는다.
POST https://oauth2.cert.toss.im/token (form: grant_type=client_credentials, client_id=Access Key,
client_secret=Secret Key, scope=toss-shopping-fep:write)
응답 expires_in 은 약 1년 — 매번 새로 받으면 이용이 제한될 수 있어(문서 안내) 암호화 저장해 두고 재사용,
401 이면 한 번만 새로 받는다. **키 발급 때 넣은 IP(이 서버 외부 IP)에서만 호출된다.**
API 는 https://shopping-fep.toss.im, 헤더 Authorization: Bearer {token}. HTTP 200 + resultType FAIL 로 오류를 준다.
호출 제한: 셀러·API 별 읽기 초당 50회(넘으면 TOO_MANY_REQUEST).
매출 = 토스쇼핑 파트너스 "순 거래액" = 매출 − 환불(2026-10-01 사용자 지정, 9/6 화면: 매출 29,600 − 환불 11,900 = 17,700).
- 매출 SALE — 주문 내역 조회 GET /api/v3/shopping-fep/orders/v2?startDate=&endDate=&limit=50&nextCursor=
(한 번에 31일까지, 상태 생략 = 전체 상태, 커서 페이지). 줄 = 주문상품(orderProductId), 묶음 = 주문(orderId).
주문 하나 = 사건 하나(`toss:{orderId}`), 날짜 = 주문 시각(orderedAt, 한국 날짜 — 토스쇼핑은 주문 = 결제),
금액 = 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외. 할인(totalDiscountPrice = 토스쇼핑 할인 + 토스페이 할인)은
discount_amount 로만 보관. 결제 전(BEFORE_PAYMENT)만 빼고 결제 뒤 취소·반품도 주문일 매출에 둔다(화면 "매출"도 환불 전 금액).
- 환불 CANCEL/RETURN — 환불일에 뺀다. 주문상품 하나에 한 번(사건 ID `toss:R{orderProductId}`). `merge_refunds`:
① 클레임 목록 GET /api/v3/shopping-fep/claims(날짜 조건이 없어 전체를 넘긴다)의 환불 완료(isRefunded) CANCEL·RETURN —
날짜 = refundedDt(한국 날짜). 반품은 이것뿐(주문 내역엔 반품 완료 날짜가 없다).
② 클레임이 없는 결제취소 — 주문 내역의 canceledAt(한국 날짜). 결제완료 단계의 고객 취소는 클레임이 생기지 않는다(문서).
기간보다 CANCEL_LOOKBACK_DAYS(90)일 앞 주문까지 불러 다른 날 주문을 기간 안에 취소한 것도 잡는다.
금액 = 그 주문상품의 price(판매가 × 수량, 매출과 같은 기준), 주문 내역에 없으면(90일보다 오래된 주문) 클레임 order.price.
9/6 실데이터: 9/5 주문(276435356)을 9/6 취소 11,900 — 클레임(CANCEL/COMPLETED)·canceledAt 둘 다 9/6 = 화면 환불 11,900.
정산 건별(settlement-steps)의 REFUND 는 이 취소를 담지 않아(구매확정 전 취소는 정산에 안 올라옴) 쓰지 않는다.
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 날짜별 매출·환불·순 거래액과 환불 출처별(정산·취소 시각·클레임) 비교.
- 구매자·수령인 이름·연락처·주소·요청사항은 저장하지 않는다.
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import re
import time
from datetime import date, datetime, timedelta, timezone
from typing import Any, Iterable
from .base import (
credential_fingerprint,
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
TokenExpired,
)
from .naver import field_summary, flatten
TOKEN_URL = "https://oauth2.cert.toss.im/token"
HOST = "https://shopping-fep.toss.im"
ORDERS_PATH = "/api/v3/shopping-fep/orders/v2"
SETTLEMENT_PATH = "/api/v3/shopping-fep/settlement-steps"
SETTLEMENT_SIZE = 100 # 문서 1~100
SCOPE = "toss-shopping-fep:write"
EVENT_PREFIX = "toss:"
PAGE_SIZE = 50 # 문서 최대 50
WINDOW_DAYS = 31 # 한 번에 31일까지
MAX_PAGES = 2000 # 한 구간 10만 건 — 무한 반복 방지
TOKEN_MARGIN_SEC = 3600 # 만료 1시간 전이면 새로 받는다(토큰은 약 1년)
CALL_INTERVAL_SEC = 0.1 # 읽기 초당 50회 제한 — 넉넉히
RETRY_429 = 3
PROBE_MAX_DAYS = 31
KST = timezone(timedelta(hours=9))
# 결제 전 주문만 매출에서 뺀다. 결제 뒤 취소·반품은 주문일 매출에 두고 원본 확인 표에 참고로 따로 보인다.
EXCLUDED_STATUS = frozenset({"BEFORE_PAYMENT"})
CLAIMED_STATUS = frozenset({"CANCELED_PAYMENT", "COMPLETED_RETURN"})
STATUS_KO = {
"BEFORE_PAYMENT": "결제전", "PAID": "결제완료", "PREPARING_PRODUCT": "상품준비중", "DELIVERING": "배송중",
"DELIVERED": "배송완료", "CONFIRMED_ORDER": "구매확정", "CLAIM_REQUESTED_CANCEL": "취소요청",
"CANCELED_PAYMENT": "결제취소", "CLAIM_REJECTED_CANCEL": "취소거절", "REQUESTED_EXCHANGE": "교환요청",
"ONGOING_EXCHANGE": "교환중", "COMPLETED_EXCHANGE": "교환완료", "CLAIM_REJECTED_EXCHANGE": "교환거절",
"REQUESTED_RETURN": "반품요청", "ONGOING_RETURN": "반품중", "COMPLETED_RETURN": "반품완료",
"CLAIM_REJECTED_RETURN": "반품거절", "CLAIM_COLLECTING": "수거중", "CLAIM_COLLECTED": "수거완료",
"CLAIM_DELIVERING": "재배송중",
}
# 원본 데이터 확인에서 값을 숨기는 항목(개인정보·자유 입력)
PERSONAL_KEYS = frozenset({
"ordererName", "ordererPhone", "ordererRealPhone", "receiverName", "receiverPhone", "receiverRealPhone",
"address", "detailAddress", "zipCode", "shippingNote", "shippingTrackingNumber",
# 클레임 목록(order.* · 수거 주소 · 요청 사유 자유 입력 · 첨부 사진)
"ordererPhoneNumber", "receiverPhoneNumber", "returnAddress", "requestReason", "requestDetailReason",
"requestImages[]",
})
CLAIMS_PATH = "/api/v3/shopping-fep/claims"
CLAIM_PAGE_SIZE = 100
CLAIM_MAX_PAGES = 100 # 클레임 목록은 날짜로 못 거른다(전체를 넘긴다) — 1만 건까지
CANCEL_LOOKBACK_DAYS = 90 # 환불 후보(주문 취소 시각): 이만큼 전 주문까지 본다
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 kst_day(value: Any) -> date | None:
"""주문 시각 → 한국 날짜. 시간대가 붙어 있으면(Z, +00:00 …) 한국 시간으로 바꾸고, 없으면 한국 시간으로 본다."""
s = str(value or "").strip()
if not s:
return None
try:
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
except ValueError:
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
if dt.tzinfo is not None:
dt = dt.astimezone(KST)
return dt.date()
def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
"""주문상품 → 주문 하나로 합침(주문일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
금액 = price(판매가 × 수량) 합(할인 전, 배송비 제외). 할인·배송비·취소/반품분은 참고용으로 모은다.
배송비는 묶음(deliveryFeeGroupId)마다 한 번만 센다."""
orders: dict[str, dict[str, Any]] = {}
ship_groups: set[str] = set()
for it in items:
oid = str(it.get("orderId") or "")
day = kst_day(it.get("orderedAt"))
status = str(it.get("orderProductStatus") 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": []})
price = _won(it.get("price"))
o["amount"] += price
if status in CLAIMED_STATUS:
o["claimed"] += price
group = str(it.get("deliveryFeeGroupId") or f"{oid}-{it.get('orderProductId')}")
if group not in ship_groups:
ship_groups.add(group)
o["ship"] += _won(it.get("deliveryFee"))
o["qty"] += _won(it.get("quantity"))
o["discount"] += _won(it.get("totalDiscountPrice"))
name = str(it.get("productName") or "")
if name and name not in o["names"]:
o["names"].append(name)
o["opt"] = o["opt"] or str(it.get("optionName") or "")
if status and status not in o["statuses"]:
o["statuses"].append(status)
return orders
def refund_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
"""정산 건별 목록 → 환불(stepType REFUND) 상품 줄만, 환불일(transactionTs 한국 날짜)이 [start, end] 인 것.
금액은 양수로(사건에서 − 를 붙인다). 배송비 줄(orderProductId 없음)은 매출에 배송비를 넣지 않으므로 뺀다."""
out = []
for it in items:
if str(it.get("stepType") or "") != "REFUND" or not it.get("orderProductId") or not it.get("orderId"):
continue
day = kst_day(it.get("transactionTs"))
if day is None or not (start <= day <= end):
continue
amount = abs(_won(it.get("orderProductPrice"))) or abs(_won(it.get("stockPrice"))) * max(1, _won(it.get("quantity")))
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it["orderProductId"]),
"_day": day, "_ts": str(it.get("transactionTs") or ""), "amount": amount,
"qty": _won(it.get("quantity")), "name": str(it.get("displayProductName") or ""),
"order_day": kst_day(it.get("originTransactionTs"))})
return out
def cancel_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
"""환불 후보 — 주문 내역의 취소 시각(canceledAt 한국 날짜)이 [start, end] 인 주문상품. 금액 = price(판매가 × 수량)."""
out = []
for it in items:
day = kst_day(it.get("canceledAt"))
if not it.get("orderId") or day is None or not (start <= day <= end):
continue
status = str(it.get("orderProductStatus") or "")
out.append({"orderId": str(it["orderId"]), "orderProductId": str(it.get("orderProductId") or ""), "_day": day,
"amount": _won(it.get("price")), "status": status, "note": STATUS_KO.get(status, status),
"order_day": kst_day(it.get("orderedAt"))})
return out
def claim_rows(items: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
"""환불 후보 — 클레임 목록의 환불 완료(isRefunded, refundedDt 한국 날짜)가 [start, end] 인 것.
금액 = order.price(문서: "상품 가격" — 수량을 곱한 값인지 실데이터로 확인), 수량은 note 에."""
out = []
for it in items:
day = kst_day(it.get("refundedDt"))
order = it.get("order") if isinstance(it.get("order"), dict) else {}
product = it.get("product") if isinstance(it.get("product"), dict) else {}
if not it.get("isRefunded") or day is None or not (start <= day <= end) or not order.get("id"):
continue
out.append({"orderId": str(order["id"]), "orderProductId": str(order.get("orderProductId") or ""), "_day": day,
"amount": _won(order.get("price")), "note": f"{it.get('type') or '?'}/{it.get('status') or '?'} · "
f"수량 {_won(product.get('quantity'))}", "order_day": kst_day(order.get("createdDt"))})
return out
def merge_refunds(order_items: Iterable[dict[str, Any]], claims: Iterable[dict[str, Any]],
start: date, end: date) -> list[dict[str, Any]]:
"""환불 규칙 — 클레임 환불 완료(CANCEL·RETURN, refundedDt) + 클레임이 없는 결제취소(canceledAt), 주문상품마다 한 번.
금액은 주문 내역의 price(판매가 × 수량)를 우선(없으면 클레임 order.price). 날짜가 [start, end] 인 것만.
클레임이 있는 주문상품은 그 클레임 날짜만 쓴다(기간 밖이어도 취소 시각으로 다시 넣지 않음 — 날짜가 바뀌지 않게)."""
order_items = list(order_items)
by_op = {str(it.get("orderProductId")): it for it in order_items if it.get("orderProductId")}
out: dict[str, dict[str, Any]] = {}
claimed_ops: set[str] = set()
for c in claims:
order = c.get("order") if isinstance(c.get("order"), dict) else {}
product = c.get("product") if isinstance(c.get("product"), dict) else {}
kind = str(c.get("type") or "")
op = str(order.get("orderProductId") or "")
if not c.get("isRefunded") or kind not in ("CANCEL", "RETURN") or not order.get("id") or not op:
continue
claimed_ops.add(op)
day = kst_day(c.get("refundedDt"))
if day is None or not (start <= day <= end) or op in out:
continue
it = by_op.get(op) or {}
out[op] = {"orderId": str(order["id"]), "orderProductId": op, "_day": day, "type": kind,
"amount": _won(it["price"]) if "price" in it else _won(order.get("price")),
"qty": _won(it.get("quantity")) or _won(product.get("quantity")),
"name": str(it.get("productName") or product.get("name") or ""),
"order_day": kst_day(it.get("orderedAt") or order.get("createdDt"))}
for r in cancel_rows(order_items, start, end):
op = r["orderProductId"]
if not op or op in claimed_ops or op in out or r["status"] != "CANCELED_PAYMENT":
continue
it = by_op.get(op) or {}
out[op] = {"orderId": r["orderId"], "orderProductId": op, "_day": r["_day"], "type": "CANCEL",
"amount": r["amount"], "qty": _won(it.get("quantity")), "name": str(it.get("productName") or ""),
"order_day": kst_day(it.get("orderedAt"))}
return sorted(out.values(), key=lambda x: (x["_day"], x["orderId"], x["orderProductId"]))
def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""원본 확인 표 — 항목별 채워진 줄·숫자 합계·예시 값(개인정보·자유 입력 항목은 값·합계 숨김)."""
fields = field_summary([flatten(r) for r in rows])
for f in fields:
if f["name"].rsplit(".", 1)[-1] in PERSONAL_KEYS:
f["personal"], f["sample"], f["sum"] = True, "", None
return fields
# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint)
TOKEN_KEYS = ("api_key", "api_secret")
class TossAdapter(MarketplaceAdapter):
code = "toss"
name = "토스쇼핑"
auth_type = "api_key"
note = "입력 항목은 연동 단계에서 토스쇼핑 판매자 API 문서로 확정합니다."
auth_type = "oauth"
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://shopping-docs.toss.im/dev"
note = ("토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발에서 발급한 Access Key·Secret Key 를 입력합니다. "
"키 발급 때 이 서버의 외부 IP 를 등록해야 호출됩니다.")
def __init__(self) -> None:
self._last_call = 0.0
def credential_fields(self) -> list[CredentialField]:
# 키 이름(api_key·api_secret)은 처음 만든 입력칸 그대로 — 이미 저장한 값이 이어진다.
return [
CredentialField("seller_id", "판매자 ID"),
CredentialField("api_key", "API Key", secret=True),
CredentialField("api_secret", "API Secret", secret=True, required=False),
CredentialField("api_key", "Access Key", secret=True,
help="토스쇼핑 파트너스 → 가맹점·계정 관리 → 자체 개발의 Access Key"),
CredentialField("api_secret", "Secret Key", secret=True,
help="같은 화면의 Secret Key"),
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
# 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04)
CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True),
]
# ── 인증 ──────────────────────────────────────────────
def _token(self, ctx: AdapterContext, *, force: bool = False) -> str:
"""저장된 토큰이 1시간 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장."""
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
same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS)
if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC:
return tok
return self._issue_token(ctx)
def _issue_token(self, ctx: AdapterContext) -> str:
import httpx # 지연 import
access_key = ctx.credentials.get("api_key").strip()
secret_key = ctx.credentials.get("api_secret").strip()
if not access_key or not secret_key:
raise NotConfigured("Access Key 와 Secret Key 를 입력하세요.")
form = {"grant_type": "client_credentials", "client_id": access_key, "client_secret": secret_key,
"scope": SCOPE}
try:
res = httpx.post(TOKEN_URL, data=form, timeout=ctx.timeout_sec,
headers={"Accept": "application/json; charset=UTF-8"})
except httpx.HTTPError as exc:
raise ApiError(f"토스 인증 서버 연결 실패: {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}. Access Key·Secret Key 와 "
"키 발급 때 등록한 IP(이 서버 외부 IP)를 확인하세요.")
raise ApiError(f"토스쇼핑 토큰 발급 오류({res.status_code}): {msg}")
tok = str(body["access_token"])
expires_in = _won(body.get("expires_in")) or 24 * 3600
ctx.credentials.set("access_token", tok)
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS))
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:
err = body.get("error")
if isinstance(err, dict):
parts = [str(err.get(k)) for k in ("errorCode", "errorType", "reason", "message") if err.get(k)]
else:
parts = [str(body.get(k)) for k in ("error", "error_description", "code", "message") if body.get(k)]
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·TOO_MANY_REQUEST 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더.
성공이면 success 내용을 돌려준다(토스쇼핑은 HTTP 200 + resultType FAIL 로도 오류를 준다)."""
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()
body = self._json(res)
err = body.get("error") if isinstance(body.get("error"), dict) else {}
limited = res.status_code == 429 or "TOO_MANY" in str(err.get("errorCode") or err.get("errorType") or "")
if limited 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
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)}. 키 발급 때 등록한 IP"
"(이 서버 외부 IP)를 확인하세요.")
if limited:
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
if res.status_code >= 400:
raise ApiError(f"토스쇼핑 API 오류({res.status_code}): {self._err_text(body, res)}")
if body.get("resultType") == "FAIL":
raise ApiError(f"토스쇼핑 API 오류: {self._err_text(body, res)}")
success = body.get("success")
return success if isinstance(success, dict) else {}
raise ApiError("토스쇼핑 API 호출 제한이 계속됩니다. 잠시 뒤 다시 시도하세요.")
def _window_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
"""조회 기간 [a, b](31일 이하)의 주문상품 전체 — 모든 상태, 커서로 끝까지."""
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
out: list[dict[str, Any]] = []
cursor = None
seen: set[str] = set()
for _ in range(MAX_PAGES):
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
out.extend(rows)
cursor = body.get("nextCursor")
if not cursor or not rows:
break
if str(cursor) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
seen.add(str(cursor))
else:
raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
return out
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
"""거래일 기준 [a, b](31일 이하)의 정산 건별 줄 전체(결제·환불·배송비), nextToken 으로 끝까지."""
params: dict[str, Any] = {"dateCondition": "TRANSACTION_DATE", "fromDate": a.isoformat(),
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
out: list[dict[str, Any]] = []
token = None
seen: set[str] = set()
for _ in range(MAX_PAGES):
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
out.extend(rows)
token = body.get("nextToken")
if not token or not rows:
break
if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
seen.add(str(token))
else:
raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
return out
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
out: list[dict[str, Any]] = []
token = None
seen: set[str] = set()
for _ in range(CLAIM_MAX_PAGES):
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
out.extend(rows)
token = body.get("nextToken")
if not token or not rows or body.get("hasNext") is False:
break
if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
raise ApiError("토스 클레임 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
seen.add(str(token))
else:
raise ApiError(f"토스 클레임 목록이 {CLAIM_MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
return out
@staticmethod
def _windows(start: date, end: date) -> list[tuple[date, date]]:
windows = []
a = start
while a <= end:
b = min(end, a + timedelta(days=WINDOW_DAYS - 1))
windows.append((a, b))
a = b + timedelta(days=1)
return windows
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""주문 내역(매출) — 31일 구간마다 진행 막대 한 칸(plan 은 부르는 쪽이 주문 + 정산 구간 수로 정한다)."""
for a, b in self._windows(start, end):
rows = self._window_items(ctx, a, b)
ctx.progress.step(items=len(rows))
yield from rows
def _refund_items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""정산 건별(환불이 들어 있음) — 31일 구간마다 진행 막대 한 칸."""
for a, b in self._windows(start, end):
rows = self._settlement_items(ctx, a, b)
ctx.progress.step(items=len(rows))
yield from rows
def _lookback_items(self, ctx: AdapterContext, start: date) -> list[dict[str, Any]]:
"""기간 앞 CANCEL_LOOKBACK_DAYS 일의 주문상품 — 다른 날 주문을 기간 안에 취소한 것을 찾는 용도."""
out: list[dict[str, Any]] = []
for a, b in self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)):
rows = self._window_items(ctx, a, b)
ctx.progress.step(items=len(rows))
out.extend(rows)
return out
def _plan(self, ctx: AdapterContext, start: date, end: date, extra: int = 0) -> None:
"""진행 막대: 기간 주문 구간 + 앞 90일 주문 구간 + 클레임 목록 1단계 (+ 원본 확인의 정산 구간)."""
back = len(self._windows(start - timedelta(days=CANCEL_LOOKBACK_DAYS), start - timedelta(days=1)))
ctx.progress.plan(len(self._windows(start, end)) + back + 1 + extra, "단계")
def _claims_step(self, ctx: AdapterContext) -> list[dict[str, Any]]:
claims = self._claims(ctx)
ctx.progress.step(items=len(claims))
return claims
# ── 수집 ──────────────────────────────────────────────
def collect(self, ctx: AdapterContext, start: date, end: date) -> tuple[int, list[SaleEvent]]:
"""매출(주문일) + 환불(환불일, merge_refunds). 주문 내역은 환불 금액·취소 시각에도 쓰여 한 번만 부른다."""
self.authenticate(ctx)
self._plan(ctx, start, end)
items = list(self._items(ctx, start, end))
back = self._lookback_items(ctx, start)
claims = self._claims_step(ctx)
events: list[SaleEvent] = []
for o in group_orders(items, start, end).values():
events.extend(self.normalize_order(o))
for r in merge_refunds(back + items, claims, start, end):
events.extend(self.normalize_refund(r))
for ev in events:
ev.validate()
return len(items) + len(claims), events
def normalize_refund(self, r: dict[str, Any]) -> list[SaleEvent]:
oid, day = str(r.get("orderId") or ""), r.get("_day")
if not oid or day is None or not r.get("orderProductId"):
return []
kind = "RETURN" if r.get("type") == "RETURN" else "CANCEL"
return [SaleEvent(
event_type=kind, external_event_id=f"{EVENT_PREFIX}R{r['orderProductId']}", external_order_id=oid,
external_line_id=str(r["orderProductId"]), event_date=day, order_date=r.get("order_day"),
amount=-abs(int(r.get("amount") or 0)), product_name=str(r.get("name") or "")[:200],
quantity=int(r.get("qty") or 0), order_status="반품 환불" if kind == "RETURN" else "취소 환불",
)]
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=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)
today = today_kst()
body = self._get(ctx, ORDERS_PATH, {"startDate": today.isoformat(), "endDate": today.isoformat(), "limit": 1})
n = len(body.get("results") or [])
more = " 이상" if body.get("nextCursor") else ""
return f"토스쇼핑 API 연결 정상(토큰 발급·주문 조회 확인, 오늘 주문상품 {n}건{more})."
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""기간(최대 31일)을 실제로 불러 항목별 합계·상태별 합계와 날짜별 매출·환불·순 거래액(= 저장되는 값)을 돌려준다.
환불은 출처별(클레임 환불 완료·주문 취소 시각·정산 REFUND)로도 나란히 보여 파트너스 화면과 맞춰 볼 수 있게.
개인정보 항목은 값 없이 이름만. 저장하지 않는다."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
self._plan(ctx, day, to, extra=len(self._windows(day, to)))
try:
items = list(self._items(ctx, day, to))
back = self._lookback_items(ctx, day)
except AdapterError as exc:
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
{"key": "orders", "label": "주문 내역", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]}
by_status: dict[str, list[dict[str, Any]]] = {}
for it in items:
by_status.setdefault(str(it.get("orderProductStatus") or "?"), []).append(it)
probes = [{"key": "orders", "label": "주문 내역(전체 상태, 주문상품 단위)", "path": ORDERS_PATH,
"ok": True, "count": len(items), "fields": summary(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": "orderProductStatus", "ok": True, "count": len(rows),
"fields": [f for f in summary(rows) if f["sum"] is not None]})
claims_err = ""
try:
claims = self._claims_step(ctx)
probes.append({"key": "claims", "label": "클레임 목록(전체 — 날짜 조건 없음)", "path": CLAIMS_PATH, "ok": True,
"count": len(claims), "fields": summary(claims)})
except AdapterError as exc:
claims, claims_err = [], exc.message[:300]
probes.append({"key": "claims", "label": "클레임 목록", "path": CLAIMS_PATH, "ok": False, "error": claims_err})
settle_err = ""
try:
settle = list(self._refund_items(ctx, day, to))
probes.append({"key": "settlement", "label": "정산 건별(거래일 기준, 결제·환불·배송비 줄 전체 — 참고)",
"path": SETTLEMENT_PATH + " (TRANSACTION_DATE)", "ok": True, "count": len(settle),
"fields": summary(settle)})
except AdapterError as exc:
settle, settle_err = [], exc.message[:300]
probes.append({"key": "settlement", "label": "정산 건별(참고)", "path": SETTLEMENT_PATH, "ok": False,
"error": settle_err})
refunds = merge_refunds(back + items, claims, day, to) # 저장되는 환불(현재 규칙)
# ── 환불 출처별 — 파트너스 화면 "환불"과 맞춰 보는 용도 ──
candidates: list[dict[str, Any]] = [
{"key": "rule", "label": "적용 규칙(클레임 환불 + 클레임 없는 결제취소)", "rows": [
{**r, "note": "반품" if r["type"] == "RETURN" else "취소"}
for r in refunds], "error": claims_err},
{"key": "claims", "label": "클레임 환불 완료(refundedDt, 금액 order.price)", "rows": claim_rows(claims, day, to),
"error": claims_err},
{"key": "canceled", "label": f"주문 취소 시각(canceledAt, {CANCEL_LOOKBACK_DAYS}일 전 주문까지)",
"rows": cancel_rows(back + items, day, to), "error": ""},
{"key": "settlement", "label": "정산 REFUND 상품 줄(거래일) — 참고", "rows": [
{**r, "note": "정산 REFUND"} for r in refund_rows(settle, day, to)],
"error": settle_err},
]
for c in candidates:
c["days"] = {}
for r in c["rows"]:
k = r["_day"].isoformat()
c["days"][k] = c["days"].get(k, 0) + r["amount"]
c["rows"] = [{"date": r["_day"].isoformat(), "orderDate": r["order_day"].isoformat() if r.get("order_day") else "",
"orderId": r["orderId"], "orderProductId": r["orderProductId"],
"amount": r["amount"], "note": r.get("note") or ""}
for r in sorted(c["rows"], key=lambda x: (x["_day"], x["orderId"]))][:200]
days = []
orders = group_orders(items, day, to)
d = day
while d <= to:
day_orders = [o for o in orders.values() if o["_day"] == d]
sales = sum(o["amount"] for o in day_orders)
refund = sum(r["amount"] for r in refunds if r["_day"] == d)
days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sales, "claimed": refund,
"ship": sales - refund})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"refund_candidates": candidates,
"day_cols": {"amount": "매출(주문일)", "claimed": "환불(환불일)", "ship": "순 거래액(저장되는 매출)"},
"rule": "순 거래액 = 매출 − 환불. 매출 = 주문일(orderedAt) 기준 주문상품 price(판매가 × 수량) 합(할인 전, "
"배송비 제외, 나중에 취소·반품된 주문 포함, 결제 전 제외). 환불 = 클레임 환불 완료(취소·반품, refundedDt) + "
"클레임 없는 결제취소(canceledAt), 주문상품마다 한 번, 금액 = 그 주문상품 price. 환불일 기준"}
+169
View File
@@ -0,0 +1,169 @@
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 같은 회차에 광고비(설정된 광고 API — 구글·메타)도 같은 기간으로 **동시에** 가져온다(2026-10-20, 광고비 진행 창 작업
jobs kind="ads", 실패해도 매출과 무관). 광고비 탭 [광고비 업데이트]를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
환경변수(.env)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
"""
from __future__ import annotations
import logging
import os
import re
import threading
import time
from datetime import datetime, timedelta
from typing import Any
from app.timezone import now_kst
logger = logging.getLogger("performance.auto_sync")
AUTO_USER = "자동 업데이트"
DEFAULT_DAYS = 10
DEFAULT_HOURS = (9, 19)
SLOT_MINUTES = 30
_started = False
_start_lock = threading.Lock()
def _env(name: str) -> str:
return (os.getenv(name, "") or "").strip()
def enabled() -> bool:
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
def sync_days() -> int:
try:
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
except ValueError:
return DEFAULT_DAYS
def hour_window() -> tuple[int, int]:
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
if not m:
return DEFAULT_HOURS
first, last = int(m.group(1)), int(m.group(2))
if not (0 <= first <= last <= 23):
return DEFAULT_HOURS
return first, last
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
first, last = hours
if t.minute % SLOT_MINUTES:
return False
return first <= t.hour < last or (t.hour == last and t.minute == 0)
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
"""after 보다 뒤의 첫 회차 시각."""
t = after.replace(second=0, microsecond=0)
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
if is_slot(t, hours):
return t
t += timedelta(minutes=SLOT_MINUTES)
raise ValueError("회차를 찾을 수 없습니다")
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
"""한 회차 — 오늘 포함 최근 days 일. 매출(진행 창 작업)과 광고비(광고 진행 창 작업)를 동시에.
각각 이미 돌고 있으면 그 종류만 건너뜀."""
from . import common, jobs # noqa: WPS433
from .ad_sync import run_ad_job # noqa: WPS433
from .credentials import CredentialService # noqa: WPS433
from .sync import SyncService # noqa: WPS433
start, end = today - timedelta(days=days - 1), today
ads: list[dict[str, Any]] = []
ad_thread = None
ads_skipped = jobs.running_job("ads") is not None
if not ads_skipped:
ad_job = jobs.create_job(user=AUTO_USER, start=start, end=end, kind="ads")
def _ads() -> None:
ads.extend(run_ad_job(store, common.key_ring, ad_job, start, end, user=AUTO_USER))
ad_thread = threading.Thread(target=_ads, name=f"perf-auto-ads-{ad_job.id}", daemon=True)
ad_thread.start()
sales_skipped = jobs.running_job("sales") is not None
error = ""
results: list[dict[str, Any]] = []
if not sales_skipped:
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
try:
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto 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)
if ad_thread is not None:
ad_thread.join()
if sales_skipped and ads_skipped:
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
ok = sum(1 for r in results if r.get("ok"))
return {"skipped": False, "sales_skipped": sales_skipped, "ads_skipped": ads_skipped,
"from": start.isoformat(), "to": end.isoformat(), "ok": ok,
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error,
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
def start_auto_sync_thread(app_state: Any) -> bool:
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
global _started # noqa: PLW0603
store = getattr(app_state, "performance_store", None)
if store is not None and not _started:
try: # 지난 프로세스가 업데이트 도중 끝나 남은 '진행 중' 기록 정리(자동 업데이트를 꺼 둬도)
n = store.abandon_running_runs()
if n:
logger.warning("매출 업데이트 '진행 중' 기록 %d건 정리(서버 재시작으로 중단)", n)
except Exception: # noqa: BLE001 — DB 가 아직 안 붙었어도 앱은 뜬다
logger.exception("매출 업데이트 진행 기록 정리 실패")
if store is None or not enabled():
return False
with _start_lock:
if _started:
return False
_started = True
hours, days = hour_window(), sync_days()
def _loop() -> None:
due = next_slot(now_kst(), hours)
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
due.strftime("%m-%d %H:%M"))
while True:
wait = (due - now_kst()).total_seconds()
if wait > 0:
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
continue
try:
res = run_once(store, app_state, today=due.date(), days=days)
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
due = next_slot(max(now_kst(), due), hours)
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
return True
+2 -2
View File
@@ -234,7 +234,7 @@ def _row(kind: str, label: str, per_code: dict[str, Money], **extra) -> dict:
def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date, str], Money],
*, today: date, holidays: Mapping[str, str] | None = None) -> list[dict]:
"""일자 × 쇼핑몰 표. 일 행 + 주간합계(일요일 뒤 / 기간 끝) + 기간 합계.
"""일자 × 쇼핑몰 표. 기간 합계(맨 위 — 제목 행 바로 아래, 2026-10-21) + 일 행 + 주간합계(일요일 뒤 / 기간 끝).
연간 보기는 일 대신 월 행(1~12월)으로 줄인다.
"""
@@ -264,7 +264,7 @@ def main_table(period: Period, codes: Sequence[str], cells: Mapping[tuple[date,
rows.append(_row("week", label, week_codes, **{"from": ws.isoformat(), "to": d.isoformat()}))
week_codes = {c: Money() for c in codes}
if period.kind != "week" and period.days > 1:
rows.append(_row("total", "기간 합계", by_code(cells, codes, period.start, period.end)))
rows.insert(0, _row("total", "기간 합계", by_code(cells, codes, period.start, period.end)))
return rows
+48 -13
View File
@@ -16,29 +16,38 @@ from .adapters.base import MarketplaceAdapter
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
def aad_for(code: str, key: str) -> str:
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터."""
return f"perf:{code}:{key}"
def aad_for(code: str, key: str, ns: str = "") -> str:
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터. ns = 이름 공간(광고 API 인증정보는 "ad:") —
쇼핑몰 암호문과 광고 암호문을 서로 바꿔 넣어도 복호화되지 않는다."""
return f"perf:{ns}{code}:{key}"
class CredentialAccessor:
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None:
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "",
aad_ns: str = "", cleared: set[str] | None = None) -> None:
self._store = store
self._code = code
self._ns = aad_ns
self._ring_loader = ring_loader
self._rows = store.credential_rows(code) if store is not None else {}
self._cache: dict[str, str] = {}
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
# 연결 테스트에서 화면 칸을 비운 항목 — 저장값이 있어도 빈 값으로(저장하지 않음)
self._cleared = {k for k in (cleared or set()) if k not in self._overrides}
self._persist = persist
self._user = user
def has(self, key: str) -> bool:
if key in self._cleared:
return False
return bool(self._overrides.get(key)) or key in self._rows
def get(self, key: str) -> str:
if key in self._cleared:
return ""
if key in self._overrides:
return self._overrides[key]
if key in self._cache:
@@ -46,7 +55,7 @@ class CredentialAccessor:
row = self._rows.get(key)
if not row:
return ""
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader())
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key, self._ns), ring=self._ring_loader())
self._cache[key] = value
return value
@@ -57,7 +66,7 @@ class CredentialAccessor:
return
ring = self._ring_loader()
self._store.upsert_credential(
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring),
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key, self._ns), ring=ring),
key_version=ring.current_version, user=self._user or "system",
)
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
@@ -68,14 +77,17 @@ class CredentialAccessor:
class CredentialService:
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None:
"""store = 인증정보 저장소(쇼핑몰: PerformanceStore, 광고 API: db.AdCredentialTable). aad_ns = 암호문 이름 공간."""
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing], *, aad_ns: str = "") -> None:
self._store = store
self._ring_loader = ring_loader
self._ns = aad_ns
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
user: str = "") -> CredentialAccessor:
user: str = "", cleared: set[str] | None = None) -> CredentialAccessor:
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
persist=persist, user=user)
persist=persist, user=user, aad_ns=self._ns, cleared=cleared)
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
@@ -87,11 +99,12 @@ class CredentialService:
item: dict[str, Any] = {
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
"multiline": bool(getattr(f, "multiline", False)),
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
}
if row is not None and not f.secret:
try:
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key),
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key, self._ns),
ring=self._ring_loader())
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
item["value"] = ""
@@ -127,23 +140,45 @@ class CredentialService:
"""빈 칸 = 기존 값 유지. clear 에 든 항목은 삭제. 저장한 항목 키 목록 반환."""
allowed = {f.key for f in adapter.visible_fields()}
ring = self._ring_loader()
rows = self._store.credential_rows(adapter.code)
saved = []
changed = False # 화면 항목이 실제로 바뀌었나 — 바뀌었으면 그 인증정보로 받은 토큰 등 내부 값을 지운다(F04)
for key, raw in values.items():
if key not in allowed:
continue
v = (raw or "").strip()
if not v:
continue
if not changed and self._stored_value(adapter.code, key, rows) != v:
changed = True
self._store.upsert_credential(
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key), ring=ring),
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring),
key_version=ring.current_version, user=user,
)
saved.append(key)
for key in clear or []:
if key in allowed and key not in saved:
if key in rows:
changed = True
self._store.delete_credential(adapter.code, key)
if changed:
# 계정·키가 바뀌면 예전 계정으로 받은 토큰·만료 시각을 남기지 않는다. 같은 값을 다시 저장했으면 그대로 둔다
# (토큰을 불필요하게 다시 받지 않게). 어댑터도 토큰을 발급 인증정보 지문에 묶어 한 번 더 막는다.
for f in adapter.credential_fields():
if f.internal and f.key in rows:
self._store.delete_credential(adapter.code, f.key)
return saved
def _stored_value(self, code: str, key: str, rows: dict[str, Any]) -> str | None:
"""저장된 값 원문(서버 안에서만, 비교용) — 없거나 복호화할 수 없으면 None(= 바뀐 것으로 본다)."""
row = rows.get(key)
if not row:
return None
try:
return decrypt(row["encrypted_value"], aad=aad_for(code, key, self._ns), ring=self._ring_loader())
except Exception: # noqa: BLE001 — 키 교체·손상 등: 비교할 수 없으니 바뀐 것으로
return None
# ── 마스터 키 교체 후 재암호화 ─────────────────────────
def reencrypt_all(self) -> dict[str, int]:
"""예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수)."""
@@ -155,12 +190,12 @@ class CredentialService:
continue
code, key = row["marketplace_code"], row["credential_key"]
try:
plain = decrypt(token, aad=aad_for(code, key), ring=ring)
plain = decrypt(token, aad=aad_for(code, key, self._ns), ring=ring)
except Exception: # noqa: BLE001
failed += 1
continue
self._store.upsert_credential(
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring),
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key, self._ns), ring=ring),
key_version=ring.current_version, user="rekey",
)
done += 1
+112 -17
View File
@@ -6,7 +6,7 @@ HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권
from __future__ import annotations
from datetime import date, timedelta
from decimal import Decimal
from decimal import ROUND_HALF_UP, Decimal
from typing import Any, Mapping, Sequence
from . import calc
@@ -25,11 +25,100 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
if not marketplace.get("enabled"):
return "disabled"
adapter = get_adapter(marketplace["code"])
if adapter is not None and adapter.manual_only:
return "manual"
if adapter is not None and not adapter.uses_shared_integration and not configured:
return "not_configured"
return (status_row or {}).get("status") or "unknown"
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
UNIT_COOKIE = "perf_unit"
def normalize_unit(value: Any) -> str:
return value if value in UNITS else "won"
def amount_text(value: Any, unit: str = "won") -> str:
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
div, places, _ = UNITS[normalize_unit(unit)]
if div == 1:
return f"{int(value):,}"
q = (Decimal(int(value)) / div).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
return f"{q:,.{places}f}"
def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any],
period: Any, q_start: date, q_end: date) -> None:
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
from . import ad_spend # noqa: WPS433
by_code = sales_ad_channels()
want = {ch for c in codes for ch, _ in by_code.get(c, ())}
for r in table:
r["ads"], r["ads_total"] = {}, None
if not want:
return
try:
amounts, _ = store.ad_amounts(q_start, q_end)
reader = getattr(store, "ad_roas", None)
roas_map = reader(q_start, q_end) if reader else {}
except Exception: # noqa: BLE001 — 광고비 표가 없어도 매출 화면은 그대로
return
spend_by: dict[str, list[tuple[date, int]]] = {}
for (d, ch), v in amounts.items():
if ch in want and v:
spend_by.setdefault(ch, []).append((d, int(v)))
sales_by: dict[str, list[tuple[date, int]]] = {}
for (d, c), m in cells.items():
sales_by.setdefault(c, []).append((d, int(m.gross)))
def spend(ch: str, s: date, e: date) -> int:
return sum(v for d, v in spend_by.get(ch, ()) if s <= d <= e)
def sales(c: str, s: date, e: date) -> int:
return sum(v for d, v in sales_by.get(c, ()) if s <= d <= e)
for r in table:
s = date.fromisoformat(r["from"]) if r.get("from") else period.start
e = date.fromisoformat(r["to"]) if r.get("to") else period.end
tot_spend = 0
for c in codes:
lines = []
for ch, label in by_code.get(c, ()):
amt = spend(ch, s, e)
if not amt:
continue
rs = ad_spend.channel_roas(ch, lambda m: sales(m, s, e), amt,
lambda f: ad_spend.file_roas(f, roas_map, amounts, s, e))
lines.append({"label": label, "amount": amt, "roas": rs})
tot_spend += amt
if lines:
r["ads"][c] = lines
if tot_spend:
tot = r.get("total") or {}
r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot.get("gross") or 0, tot_spend),
"roas_net": ad_spend.roas(tot.get("net") or 0, tot_spend)}
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
from . import ad_spend # noqa: WPS433
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
for ch, c in ad_spend.ROAS_SALES_CODE.items():
out[c] = out.get(c, ()) + ((ch, ""),)
return out
def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None,
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
@@ -58,31 +147,29 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
q_end = max(period.end, year_period.end)
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
manual_amounts = getattr(store, "manual_amounts", None)
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
# 계산식으로 입력한 수동 칸(마이그레이션 008) — "날짜|쇼핑몰" → 식
manual_formulas = getattr(store, "manual_formulas", None)
formula_cells = {f"{d.isoformat()}|{c}": f for (d, c), f in
(manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items()
if f"{d.isoformat()}|{c}" in manual_cells}
cur = calc.sum_range(cells, codes, period.start, period.end)
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
has_prev = prev.gross != 0 or prev.commission != 0
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
"month": "이번달" if period.start <= today <= period.end else "해당 월",
"year": "올해" if period.start <= today <= period.end else "해당 연도",
"custom": "선택 기간"}[period.kind]
# KPI 는 수수료 차감 매출 하나만(2026-10-19) — 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %).
# 총매출·수수료·월 누적·연 누적 카드는 뺐다(아래 표·월/연 누적 카드에 같은 값이 있다).
kpis = [
{"key": "gross", "label": f"{period_word} 총매출", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label},
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
{"key": "commission", "label": f"{period_word} 수수료", "value": cur.commission,
"delta": calc.pct_change(cur.commission, prev.commission) if has_prev else None, "cmp": cmp_label,
"invert": True},
{"key": "mtd", "label": f"{month_period.label} 누적 매출", "value": mtd.gross,
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label},
{"key": "ytd", "label": f"{year_period.label} 누적 매출", "value": ytd.gross,
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label},
]
share = calc.by_code(cells, codes, period.start, period.end)
@@ -98,6 +185,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"error": (statuses.get(m["code"]) or {}).get("last_error", "")})
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
_ad_lines(store, table, codes, cells, period, q_start, q_end)
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if kind == "custom":
@@ -137,12 +226,17 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"short_names": short,
"selected_all": len(codes) == len(all_codes),
"kpis": kpis,
"table": calc.main_table(period, codes, cells, today=today, holidays=holidays),
"table": table,
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
"chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
"problems": problems,
"manual_codes": manual_codes,
"manual_cells": manual_cells,
"formula_cells": formula_cells,
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
"last_update_at": store.last_update_at(),
"running": store.running_codes(),
"no_marketplaces": not all_codes,
@@ -175,10 +269,11 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
has_rate = bool(rates.get(adapter.code))
rows.append({
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
"include_in_sales": m["include_in_sales"],
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
"rate": _fmt_rate(cur_rate) if has_rate else "",
"rate_history": len(rates.get(adapter.code, ())),
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
"manual_only": adapter.manual_only,
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
"configured": configured.get(adapter.code, False),
"via_cafe24": adapter.code in via_cafe24,
+437 -8
View File
@@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Any, Iterable
from psycopg import errors as pg_errors
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
@@ -25,6 +26,28 @@ from app.timezone import to_kst_iso
STALE_RUN_AFTER = timedelta(minutes=30)
class ManualMigrationNeeded(Exception):
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
def _set_formulas(conn: Any, table: str, key_col: str, date_col: str,
rows: list[tuple[str, date, str | None]]) -> None:
"""날짜 칸 계산식(마이그레이션 008) 덮어쓰기 — 식이 없으면 지움. 008 미적용이면 조용히 건너뛴다
(savepoint 라 바깥 트랜잭션은 그대로, 금액은 저장된다). table·열 이름은 코드 상수만 넘긴다."""
if not rows:
return
try:
with conn.transaction():
with conn.cursor() as cur:
cur.executemany(
f"UPDATE {table} SET formula = %s WHERE {key_col} = %s AND {date_col} = %s "
"AND formula IS DISTINCT FROM %s",
[(f, k, d, f) for k, d, f in rows],
)
except pg_errors.UndefinedColumn:
pass
def _iso(v: Any) -> Any:
if isinstance(v, datetime):
return to_kst_iso(v)
@@ -56,8 +79,12 @@ class PerformanceDBStore:
return [{k: _iso(v) for k, v in r.items()} for r in rows]
def update_marketplace(self, code: str, *, enabled: bool | None = None,
include_in_sales: bool | None = None) -> dict[str, Any] | None:
include_in_sales: bool | None = None,
manual_input: bool | None = None) -> dict[str, Any] | None:
sets, params = [], []
if manual_input is not None:
sets.append("manual_input = %s")
params.append(bool(manual_input))
if enabled is not None:
sets.append("enabled = %s")
params.append(bool(enabled))
@@ -67,10 +94,13 @@ class PerformanceDBStore:
if not sets:
return None
params.append(code)
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
).fetchone()
try:
with self._pool.connection() as conn:
row = conn.execute(
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
).fetchone()
except pg_errors.UndefinedColumn:
raise ManualMigrationNeeded() from None
return {k: _iso(v) for k, v in row.items()} if row else None
# ════════════════════════════════════════════════════════════
@@ -281,6 +311,8 @@ class PerformanceDBStore:
"""
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
"""날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다
(실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다)."""
if not codes:
return {}
with self._pool.connection() as conn:
@@ -290,7 +322,217 @@ class PerformanceDBStore:
"GROUP BY sales_date, marketplace_code",
(start, end, codes),
).fetchall()
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
out.update(self.manual_amounts(start, end, codes))
return out
# ════════════════════════════════════════════════════════════
# 수동 입력 매출(마이그레이션 002)
# ════════════════════════════════════════════════════════════
def manual_amounts(self, start: date, end: date, codes: list[str], *,
active_only: bool = True) -> dict[tuple[date, str], int]:
"""수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음."""
if not codes:
return {}
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s "
"JOIN perf_marketplaces m ON m.code = s.marketplace_code "
"WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)"
+ (" AND m.manual_input" if active_only else ""),
(start, end, codes),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows}
def api_amount(self, code: str, day: date) -> int:
"""그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events "
"WHERE marketplace_code = %s AND sales_date = %s", (code, day),
).fetchone()
return int(row["amount"] or 0)
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "",
formula: str | None = None) -> None:
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값). formula = 계산식(008, 없으면 숫자 입력)."""
try:
with self._pool.connection() as conn:
if amount is None:
conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s",
(code, day))
else:
conn.execute(
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
(code, day, int(amount), user),
)
_set_formulas(conn, "perf_manual_sales", "marketplace_code", "sales_date", [(code, day, formula)])
except pg_errors.UndefinedTable:
raise ManualMigrationNeeded() from None
def set_manual_sales_bulk(self, entries: list[tuple[str, date, int]], *, user: str = "") -> int:
"""엑셀 업로드 — (쇼핑몰, 날짜, 금액) 여러 개를 한 트랜잭션으로 저장(덮어씀). 하나라도 실패하면 모두 취소."""
if not entries:
return 0
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
[(code, day, int(amount), user) for code, day, amount in entries],
)
# 업로드 값은 숫자 — 예전에 넣은 계산식은 지운다
_set_formulas(conn, "perf_manual_sales", "marketplace_code", "sales_date",
[(code, day, None) for code, day, _ in entries])
except pg_errors.UndefinedTable:
raise ManualMigrationNeeded() from None
return len(entries)
def manual_formulas(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], str]:
"""계산식으로 입력한 수동 칸 (날짜, 쇼핑몰) → 식. 008 미적용이면 비어 있음."""
if not codes:
return {}
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT sales_date, marketplace_code, formula FROM perf_manual_sales "
"WHERE sales_date BETWEEN %s AND %s AND marketplace_code = ANY(%s) AND formula IS NOT NULL",
(start, end, codes),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
return {(r["sales_date"], r["marketplace_code"]): r["formula"] for r in rows}
# ════════════════════════════════════════════════════════════
# 광고비(마이그레이션 005)
# ════════════════════════════════════════════════════════════
def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]:
"""(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, channel_code, amount, source FROM perf_ad_spend "
"WHERE spend_date BETWEEN %s AND %s", (start, end),
).fetchall()
except pg_errors.UndefinedTable:
raise AdMigrationNeeded() from None
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "",
formula: str | None = None) -> None:
"""광고비 한 칸 저장(amount None = 지움). formula = 계산식(008, 없으면 숫자 입력)."""
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user,
formulas={day: formula} if formula else None)
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
user: str = "", roas: dict[date, Any] | None = None,
metrics: dict[date, dict[str, Any]] | None = None,
formulas: dict[date, str] | None = None) -> int:
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다.
formulas = 날짜 칸 계산식(008) — 저장하는 날 중 없는 날은 계산식을 지운다(업로드·API·숫자 입력)."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
if not entries:
return 0
report = roas is not None or metrics is not None
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
gone = [(code, d) for d, a in entries if a is None]
if gone:
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
if report:
keep6 = [(code, d, int(a), source, user, (roas or {}).get(d),
Jsonb((metrics or {}).get(d)) if (metrics or {}).get(d) is not None else None)
for d, a in entries if a is not None]
if keep6:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
keep6,
)
else:
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
if keep:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
keep,
)
_set_formulas(conn, "perf_ad_spend", "channel_code", "spend_date",
[(code, d, (formulas or {}).get(d)) for d, a in entries if a is not None])
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return len(entries)
def ad_formulas(self, start: date, end: date) -> dict[tuple[date, str], str]:
"""계산식으로 입력한 광고비 칸 (날짜, 채널) → 식. 005·008 미적용이면 비어 있음."""
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, channel_code, formula FROM perf_ad_spend "
"WHERE spend_date BETWEEN %s AND %s AND formula IS NOT NULL", (start, end),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
return {(r["spend_date"], r["channel_code"]): r["formula"] for r in rows}
def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
"""(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이).
roas 가 비었어도 보관된 보고서 항목(metrics)에 광고수익률·전환매출액이 있으면 그것으로 구한다
(네이버 파일 열 위치가 달라 고정 12열이 비어 저장됐던 예전 업로드 — 다시 올리지 않아도 보이게, 2026-10-20)."""
from .ad_spend import roas_from_metrics # noqa: WPS433
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, channel_code, amount, roas, metrics FROM perf_ad_spend "
"WHERE spend_date BETWEEN %s AND %s AND (roas IS NOT NULL OR metrics IS NOT NULL)", (start, end),
).fetchall()
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
return {}
out: dict[tuple[date, str], Decimal] = {}
for r in rows:
value = r["roas"] if r["roas"] is not None else roas_from_metrics(r["metrics"], r["amount"])
if value is not None:
out[(r["spend_date"], r["channel_code"])] = value
return out
def ad_details(self, code: str, start: date, end: date) -> list[dict[str, Any]]:
"""한 채널의 일자별 광고비·ROAS·보고서 항목(날짜 순). 006 미적용이면 AdMigrationNeeded."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT spend_date, amount, roas, metrics, source FROM perf_ad_spend "
"WHERE channel_code = %s AND spend_date BETWEEN %s AND %s ORDER BY spend_date",
(code, start, end),
).fetchall()
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return [{"date": r["spend_date"].isoformat(), "amount": int(r["amount"]), "roas": r["roas"],
"metrics": r["metrics"] or {}, "source": r["source"]} for r in rows]
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
@@ -317,12 +559,24 @@ class PerformanceDBStore:
rows = conn.execute(
"SELECT id, event_type, external_order_id, external_line_id, order_date, payment_date, "
" event_date, sales_date, product_name, option_name, quantity, amount, "
" discount_amount, order_status, is_sample "
" discount_amount, order_status, is_sample, "
# 주문 내역 칸(2026-10-19) — 카페24 적립금(결제 +, 환불 −) · 네이버 배송비 · 네이버 환불금액(raw_data 의 숫자만)
" raw_data ->> 'points' AS points, raw_data ->> 'ship' AS ship, raw_data ->> 'refund' AS refund, "
" raw_data ->> 'goods' AS goods " # 네이버 판매금액(배송비 뺀 값) — 주문 내역 '판매금액' 칸
"FROM perf_sales_events WHERE marketplace_code = %s AND sales_date BETWEEN %s AND %s "
"ORDER BY sales_date, external_order_id, event_type LIMIT %s",
(code, start, end, limit),
).fetchall()
return [{k: _iso(v) for k, v in r.items()} for r in rows]
out = []
for r in rows:
row = {k: _iso(v) for k, v in r.items()}
for k in ("points", "ship", "refund", "goods"):
try:
row[k] = int(round(float(row[k]))) if row.get(k) not in (None, "") else None
except (TypeError, ValueError):
row[k] = None
out.append(row)
return out
def sample_count(self) -> int:
with self._pool.connection() as conn:
@@ -375,6 +629,15 @@ class PerformanceDBStore:
).fetchone()
return _iso(row["t"]) if row and row["t"] else None
def abandon_running_runs(self) -> int:
"""서버 시작 때 1번(2026-10-19) — 남아 있는 running 행은 지난 프로세스가 업데이트 도중 끝난 것(앱은 프로세스 하나,
진행 작업은 메모리에만)이라 '중단됨'으로 정리한다. 안 하면 30분(STALE_RUN_AFTER) 동안 [매출 업데이트]가 '업데이트 중'으로
보이고 그 쇼핑몰 업데이트가 '이미 진행 중'으로 건너뛰어진다. 정리한 행 수."""
with self._pool.connection() as conn:
cur = conn.execute("UPDATE perf_sync_runs SET status = 'failed', finished_at = now(), "
"error = '중단됨(서버 재시작)' WHERE status = 'running'")
return cur.rowcount
def running_codes(self) -> list[str]:
with self._pool.connection() as conn:
rows = conn.execute(
@@ -383,3 +646,169 @@ class PerformanceDBStore:
(STALE_RUN_AFTER,),
).fetchall()
return [r["marketplace_code"] for r in rows]
# ════════════════════════════════════════════════════════════
# 광고 API 연동(마이그레이션 007) — 인증정보(암호문)·연결 상태·가져온 광고비
# 읽기는 007 미적용이면 빈 값(설정 화면은 안내만), 쓰기는 AdMigrationNeeded("007").
# ════════════════════════════════════════════════════════════
def ad_api_ready(self) -> bool:
try:
with self._pool.connection() as conn:
conn.execute("SELECT 1 FROM perf_ad_credentials LIMIT 1").fetchall()
except pg_errors.UndefinedTable:
return False
return True
def ad_credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT credential_key, encrypted_value, key_version, updated_at, updated_by "
"FROM perf_ad_credentials WHERE channel_code = %s", (code,),
).fetchall()
except pg_errors.UndefinedTable:
return {}
return {r["credential_key"]: r for r in rows}
def ad_credential_keys_by_code(self) -> dict[str, set[str]]:
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT channel_code, credential_key FROM perf_ad_credentials").fetchall()
except pg_errors.UndefinedTable:
return {}
out: dict[str, set[str]] = {}
for r in rows:
out.setdefault(r["channel_code"], set()).add(r["credential_key"])
return out
def upsert_ad_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
conn.execute(
"""
INSERT INTO perf_ad_credentials (channel_code, credential_key, encrypted_value, key_version, updated_by)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (channel_code, credential_key) DO UPDATE
SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version,
updated_by = EXCLUDED.updated_by
""",
(code, key, encrypted_value, key_version, user),
)
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("007") from None
def delete_ad_credential(self, code: str, key: str) -> None:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
try:
with self._pool.connection() as conn:
conn.execute("DELETE FROM perf_ad_credentials WHERE channel_code = %s AND credential_key = %s", (code, key))
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("007") from None
def all_ad_credential_rows(self) -> list[dict[str, Any]]:
try:
with self._pool.connection() as conn:
return conn.execute(
"SELECT channel_code AS marketplace_code, credential_key, encrypted_value, key_version "
"FROM perf_ad_credentials"
).fetchall()
except pg_errors.UndefinedTable:
return []
def ad_source_statuses(self) -> dict[str, dict[str, Any]]:
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT * FROM perf_ad_source_status").fetchall()
except pg_errors.UndefinedTable:
return {}
return {r["channel_code"]: {k: _iso(v) for k, v in r.items()} for r in rows}
def record_ad_status(self, code: str, *, status: str, ok: bool, error: str = "", kind: str = "test") -> None:
"""연결 테스트(kind=test) 또는 가져오기(kind=sync) 결과. 오류가 없으면 예전 오류 문구는 그대로 둔다."""
if kind == "sync":
sql = """
INSERT INTO perf_ad_source_status (channel_code, status, last_sync_at, last_success_sync_at, last_error, last_error_at)
VALUES (%(c)s, %(s)s, now(), CASE WHEN %(ok)s THEN now() END, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
ON CONFLICT (channel_code) DO UPDATE
SET status = EXCLUDED.status, last_sync_at = now(),
last_success_sync_at = CASE WHEN %(ok)s THEN now() ELSE perf_ad_source_status.last_success_sync_at END,
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
"""
else:
sql = """
INSERT INTO perf_ad_source_status (channel_code, status, last_test_at, last_test_ok, last_error, last_error_at)
VALUES (%(c)s, %(s)s, now(), %(ok)s, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
ON CONFLICT (channel_code) DO UPDATE
SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = %(ok)s,
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
"""
try:
with self._pool.connection() as conn:
conn.execute(sql, {"c": code, "s": status, "ok": ok, "e": error})
except pg_errors.UndefinedTable:
return # 007 미적용 — 상태 기록만 못 함(가져오기 자체는 막지 않음)
def replace_ad_api_range(self, code: str, start: date, end: date,
days: list[tuple[date, int, Any, dict[str, Any] | None]], *, user: str = "") -> int:
"""광고 API 로 가져온 기간을 한 트랜잭션으로 반영 — days 의 날은 덮어쓰고(source='api', ROAS·보고서 항목 포함,
직접 입력·업로드 값이 있던 날도 API 값으로), 기간 안에서 API 가 돌려주지 않은 날은 **예전 API 값만** 지운다
(직접 입력·업로드 값은 그대로). days = [(날짜, 금액, ROAS, 항목)]. 반영한 날 수."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
keep = {d for d, _, _, _ in days}
try:
with self._pool.connection() as conn:
with conn.transaction():
with conn.cursor() as cur:
old = cur.execute(
"SELECT spend_date FROM perf_ad_spend WHERE channel_code = %s AND source = 'api' "
"AND spend_date BETWEEN %s AND %s", (code, start, end),
).fetchall()
gone = [(code, r["spend_date"]) for r in old if r["spend_date"] not in keep]
if gone:
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s "
"AND source = 'api'", gone)
rows = [(code, d, int(a), "api", user, r, Jsonb(m) if m is not None else None) for d, a, r, m in days]
if rows:
cur.executemany(
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
rows,
)
_set_formulas(conn, "perf_ad_spend", "channel_code", "spend_date",
[(code, d, None) for d, _, _, _ in days])
except pg_errors.UndefinedTable:
raise AdMigrationNeeded("005") from None
except pg_errors.UndefinedColumn:
raise AdMigrationNeeded("006") from None
return len(days)
class AdCredentialTable:
"""광고 API 인증정보 표(perf_ad_credentials)를 쇼핑몰 인증정보 저장소와 같은 이름으로 — credentials.CredentialService 가
그대로 쓴다(저장·요약·재암호화). 채널 코드가 쇼핑몰 코드 자리에 들어간다."""
def __init__(self, store: Any) -> None:
self._store = store
def credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
return self._store.ad_credential_rows(code)
def credential_keys_by_code(self) -> dict[str, set[str]]:
return self._store.ad_credential_keys_by_code()
def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
self._store.upsert_ad_credential(code, key, encrypted_value=encrypted_value, key_version=key_version, user=user)
def delete_credential(self, code: str, key: str) -> None:
self._store.delete_ad_credential(code, key)
def all_credential_rows(self) -> list[dict[str, Any]]:
return self._store.all_ad_credential_rows()
+106
View File
@@ -0,0 +1,106 @@
"""매출·광고비 날짜 칸 입력 — 숫자 또는 엑셀 같은 계산식(= 없이 바로 `1000+2000`).
parse_amount("12,000") → (12000, None) 숫자 그대로
parse_amount("1000+2000*2") → (5000, "1000+2000*2") 계산식 — 결과(원, 반올림)와 식을 함께 저장해 다시 누르면 식이 보인다
쓸 수 있는 것: 숫자(쉼표·소수), + - * / ( ), ×·÷·x 는 곱하기·나누기로. 그 밖의 글자는 오류.
"""
from __future__ import annotations
import re
from decimal import ROUND_HALF_UP, Decimal, DivisionByZero, InvalidOperation
MAX_FORMULA_LEN = 200
_OPS = {"×": "*", "x": "*", "X": "*", "÷": "/"}
_TOKEN = re.compile(r"\d+(?:\.\d+)?|\.\d+|[-+*/()]")
class FormulaError(ValueError):
pass
def _tokens(text: str) -> list[str]:
out: list[str] = []
pos = 0
while pos < len(text):
m = _TOKEN.match(text, pos)
if not m:
raise FormulaError("숫자와 + - * / ( ) 만 입력할 수 있습니다.")
out.append(m.group())
pos = m.end()
return out
class _Parser:
"""식 := 항 (('+'|'-') 항)* · 항 := 인자 (('*'|'/') 인자)* · 인자 := ('+'|'-') 인자 | 숫자 | '(' 식 ')'"""
def __init__(self, tokens: list[str]):
self.t = tokens
self.i = 0
def peek(self) -> str | None:
return self.t[self.i] if self.i < len(self.t) else None
def take(self) -> str:
tok = self.peek()
if tok is None:
raise FormulaError("계산식이 끝나지 않았습니다.")
self.i += 1
return tok
def expr(self) -> Decimal:
v = self.term()
while self.peek() in ("+", "-"):
v = v + self.term() if self.take() == "+" else v - self.term()
return v
def term(self) -> Decimal:
v = self.factor()
while self.peek() in ("*", "/"):
if self.take() == "*":
v = v * self.factor()
else:
d = self.factor()
if d == 0:
raise FormulaError("0으로 나눌 수 없습니다.")
v = v / d
return v
def factor(self) -> Decimal:
tok = self.take()
if tok in ("+", "-"):
v = self.factor()
return v if tok == "+" else -v
if tok == "(":
v = self.expr()
if self.take() != ")":
raise FormulaError("괄호가 맞지 않습니다.")
return v
if tok in ("*", "/", ")"):
raise FormulaError("계산식이 올바르지 않습니다.")
return Decimal(tok)
def parse_amount(raw: object) -> tuple[int | None, str | None]:
"""칸 입력 → (원 단위 금액, 계산식). 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
text = str(raw if raw is not None else "").strip()
for a, b in _OPS.items():
text = text.replace(a, b)
text = re.sub(r"[,\s원]", "", text)
if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다
text = text[1:]
if text == "":
return None, None
if len(text) > MAX_FORMULA_LEN:
raise FormulaError("계산식이 너무 깁니다.")
tokens = _tokens(text)
p = _Parser(tokens)
try:
value = p.expr()
except (InvalidOperation, DivisionByZero):
raise FormulaError("계산할 수 없는 식입니다.") from None
if p.peek() is not None:
raise FormulaError("계산식이 올바르지 않습니다.")
amount = int(value.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
# 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다
is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(")
return amount, (text if is_formula else None)
+90
View File
@@ -0,0 +1,90 @@
"""외화 → 원화 날짜별 환율(2026-10-16 사용자 요청: 메타 USD 광고 계정 — "그날 환율로 원화 환산").
출처: Frankfurter(https://frankfurter.dev, API 키 없음) v2 `GET /v2/rates?base=USD&quotes=KRW&from=&to=`
— 여러 나라 중앙은행 고시 환율을 합친 값(blended)이고 주말·공휴일 포함 매일 있다. 서울외국환중개 매매기준율과는
조금(보통 0.5% 안쪽) 다를 수 있다. 응답: [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1357.92}, …]
그날 값이 없으면(오늘처럼 아직 안 나온 날 등) 그 앞 가장 가까운 날 값을 쓴다(LOOKBACK_DAYS 안).
지난 날(2일 이상 지난) 환율은 프로세스 안에 기억해 30분마다 도는 자동 업데이트가 같은 날을 다시 묻지 않게 한다.
"""
from __future__ import annotations
import threading
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
import httpx
from app.timezone import today_kst
FX_API = "https://api.frankfurter.dev/v2/rates"
SOURCE_LABEL = "Frankfurter(중앙은행 고시 환율 종합)"
LOOKBACK_DAYS = 10 # 그날 환율이 없으면 이만큼 앞까지 찾는다
_SETTLED_AFTER = 2 # 오늘에서 이만큼 지난 날 환율만 기억(최근 값은 나중에 고시될 수 있음)
_cache_lock = threading.Lock()
_cache: dict[tuple[str, date], Decimal] = {}
class FxError(Exception):
"""환율을 가져오지 못함 — 문구는 화면에 그대로 보인다."""
def krw_rates(client: httpx.Client, currency: str, start: date, end: date, *, today: date | None = None) -> dict[date, Decimal]:
"""start~end(양 끝 포함) 날마다 1 {currency} = ? 원. 하루라도 못 정하면 FxError(일부만 환산해 저장하지 않게)."""
cur = (currency or "").upper()
if cur == "KRW":
return {start + timedelta(days=i): Decimal(1) for i in range((end - start).days + 1)}
days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
with _cache_lock:
known = {d: _cache[(cur, d)] for d in days if (cur, d) in _cache}
if len(known) == len(days):
return known
fetched = _fetch(client, cur, start - timedelta(days=LOOKBACK_DAYS), end)
today = today or today_kst()
out: dict[date, Decimal] = {}
for d in days:
rate = next((fetched[d - timedelta(days=k)] for k in range(LOOKBACK_DAYS + 1) if d - timedelta(days=k) in fetched), None)
if rate is None:
raise FxError(f"{d.isoformat()} 의 {cur}→KRW 환율을 찾지 못했습니다({SOURCE_LABEL}).")
out[d] = rate
with _cache_lock:
for d, rate in out.items():
if d in fetched and (today - d).days >= _SETTLED_AFTER:
_cache[(cur, d)] = rate
return out
def _fetch(client: httpx.Client, cur: str, start: date, end: date) -> dict[date, Decimal]:
try:
resp = client.get(FX_API, params={"base": cur, "quotes": "KRW", "from": start.isoformat(), "to": end.isoformat()})
except httpx.HTTPError as exc:
raise FxError(f"환율 서버({SOURCE_LABEL})에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
try:
msg = str((resp.json() or {}).get("message") or "")
except ValueError:
msg = ""
raise FxError(f"환율을 가져오지 못했습니다(HTTP {resp.status_code}{': ' + msg[:120] if msg else ''}).")
try:
rows = resp.json()
except ValueError:
raise FxError("환율 서버 응답을 읽을 수 없습니다.") from None
out: dict[date, Decimal] = {}
for r in rows if isinstance(rows, list) else []:
if not isinstance(r, dict) or str(r.get("quote") or "").upper() != "KRW":
continue
try:
d = date.fromisoformat(str(r.get("date")))
rate = Decimal(str(r.get("rate")))
except (ValueError, InvalidOperation):
continue
if rate > 0:
out[d] = rate
return out
def clear_cache() -> None:
"""테스트용."""
with _cache_lock:
_cache.clear()
+55 -11
View File
@@ -9,6 +9,8 @@
- [업데이트 취소]: SyncJob.cancel() → 각 쇼핑몰이 다음 API 호출 직전(ShopProgress.check)에 Cancelled 로 멈춘다.
수집 중에 멈춘 쇼핑몰은 DB 에 아무것도 쓰지 않는다(저장은 수집이 끝난 뒤 한 트랜잭션). 저장 중이면 그 저장은 끝낸다.
아직 차례가 안 온 쇼핑몰은 "취소됨"으로 건너뛴다.
- 쇼핑몰별 [중지]: SyncJob.stop_shop(code) → 그 쇼핑몰만 같은 방식(다음 API 호출 직전, 저장 안 함)으로 멈추고 "중지됨",
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰을 미리 중지하면 차례가 왔을 때 건너뛴다. 저장 중이면 못 멈춘다.
"""
from __future__ import annotations
@@ -39,8 +41,17 @@ class ShopProgress(Progress):
self.unit = "단계"
self.status = self.label = self.message = ""
self.started_at = self.finished_at = 0.0
self.stop_requested = False # 쇼핑몰별 [중지] — 이 쇼핑몰만 멈추고 다음 쇼핑몰로
self._lock = threading.Lock()
def stop(self) -> bool:
"""[중지] — 대기·수집 중일 때만(저장 중·끝난 뒤엔 못 멈춤). 받아들였으면 True."""
with self._lock:
if self.state not in ("waiting", "running"):
return False
self.stop_requested = True
return True
# ── 어댑터가 부르는 쪽(Progress) ──
def plan(self, total: int, unit: str = "단계") -> None:
with self._lock:
@@ -52,11 +63,18 @@ class ShopProgress(Progress):
def check(self) -> None:
if self.cancel_requested and self.state == "running":
raise Cancelled("사용자가 업데이트를 취소했습니다.")
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
"사용자가 업데이트를 취소했습니다.")
@property
def cancel_requested(self) -> bool:
return bool(self.job is not None and self.job.cancel_requested)
"""멈춰야 하나 — 업데이트 전체 취소 또는 이 쇼핑몰만 중지."""
return self.stop_requested or bool(self.job is not None and self.job.cancel_requested)
@property
def stopped_only(self) -> bool:
"""이 쇼핑몰만 중지(전체 취소가 아님) — 업데이트는 다음 쇼핑몰로 계속된다."""
return self.stop_requested and not (self.job is not None and self.job.cancel_requested)
def step(self, n: int = 1, *, items: int = 0) -> None:
self.check()
@@ -75,6 +93,17 @@ class ShopProgress(Progress):
with self._lock:
self.state = "saving"
def begin_saving(self) -> None:
"""수집이 끝나 저장으로 넘어간다 — 중지·취소 확인과 running → saving 전환을 **같은 잠금 안에서** 한다.
stop() 도 같은 잠금으로 state 를 보고 받아들이므로, [중지]가 이 전환보다 먼저면 여기서 Cancelled(저장 안 함),
나중이면 stop() 이 False(저장 중이라 중지 불가)를 돌려준다 — 둘 다 받아들여지는 틈이 없다(2026-10-15 검토 F06).
마지막 API 호출 중이나 collect() 정리 중에 받아들인 [중지]도 여기서 반영된다."""
with self._lock:
if self.cancel_requested:
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
"사용자가 업데이트를 취소했습니다.")
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"
@@ -91,7 +120,8 @@ class ShopProgress(Progress):
def cancelled(self) -> None:
with self._lock:
self.state, self.status, self.message = "cancelled", "cancelled", "취소됨"
self.state, self.status = "cancelled", "cancelled"
self.message = "중지됨" if self.stopped_only else "취소됨"
self.finished_at = time.time()
def skip(self, message: str) -> None:
@@ -118,14 +148,20 @@ class ShopProgress(Progress):
"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),
"stop_requested": self.stop_requested, "fraction": round(self.fraction(), 4),
"elapsed": round((self.finished_at or time.time()) - self.started_at, 1) if self.started_at else 0,
}
# 작업 종류 — 매출 업데이트(sales, 쇼핑몰별) · 광고비 업데이트(ads, 광고 채널별, 2026-10-20). 진행 창·취소·중지 API 는 같고
# "지금 돌고 있는 작업"은 종류별로 따로 본다(매출 업데이트 중에도 광고비 업데이트는 따로 시작·합류).
KINDS = ("sales", "ads")
class SyncJob:
def __init__(self, *, user: str, start: date | None, end: date | None) -> None:
def __init__(self, *, user: str, start: date | None, end: date | None, kind: str = "sales") -> None:
self.id = uuid.uuid4().hex[:12]
self.kind = kind if kind in KINDS else "sales"
self.user, self.start, self.end = user, start, end
self.created_at = time.time()
self.finished_at = 0.0
@@ -148,6 +184,14 @@ class SyncJob:
if not self.finished_at and not self.cancel_requested:
self.cancel_requested, self.cancelled_by = True, user
def stop_shop(self, code: str) -> bool:
"""쇼핑몰별 [중지] — 그 쇼핑몰만 멈추고 다음 쇼핑몰로. 끝난 작업·없는 쇼핑몰·저장 중·끝난 쇼핑몰은 False."""
with self._lock:
if self.finished_at:
return False
shop = next((s for s in self.shops if s.code == code), None)
return bool(shop is not None and shop.stop())
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()
@@ -161,7 +205,7 @@ class SyncJob:
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,
"id": self.id, "kind": self.kind, "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),
@@ -176,8 +220,8 @@ class SyncJob:
}
def create_job(*, user: str, start: date | None, end: date | None) -> SyncJob:
job = SyncJob(user=user, start=start, end=end)
def create_job(*, user: str, start: date | None, end: date | None, kind: str = "sales") -> SyncJob:
job = SyncJob(user=user, start=start, end=end, kind=kind)
with _LOCK:
_JOBS[job.id] = job
if len(_JOBS) > MAX_JOBS: # 오래된 끝난 작업부터 정리
@@ -194,8 +238,8 @@ def get_job(job_id: str) -> SyncJob | None:
return _JOBS.get(job_id)
def running_job() -> SyncJob | None:
"""지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
def running_job(kind: str = "sales") -> SyncJob | None:
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
with _LOCK:
live = [j for j in _JOBS.values() if not j.finished]
live = [j for j in _JOBS.values() if not j.finished and j.kind == kind]
return max(live, key=lambda j: j.created_at) if live else None
+200
View File
@@ -0,0 +1,200 @@
"""수동 입력 매출 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글(샘플: upload_sample.xlsx).
규칙
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜도 됨(2026-10-21).
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
HTTP·DB 와 무관한 순수 함수 — 라우터가 파일 바이트와 쇼핑몰 목록을 넘긴다.
"""
from __future__ import annotations
import io
import re
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Iterable, Mapping
MAX_FILE_BYTES = 5 * 1024 * 1024
MAX_DATA_ROWS = 2000
MAX_ERRORS = 30
MAX_AMOUNT = 10 ** 12 # 라우터 MAX_MANUAL_AMOUNT 와 같은 상한(원)
_EXCEL_EPOCH = date(1899, 12, 30)
_DATE_RE = re.compile(r"^(\d{4})\s*[-./년]\s*(\d{1,2})\s*[-./월]\s*(\d{1,2})")
_COMPACT_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?!\d)")
class UploadError(ValueError):
"""파일 자체를 읽을 수 없음(형식·크기·머리글)."""
@dataclass
class ParseResult:
entries: list[tuple[str, date, int]] = field(default_factory=list) # (쇼핑몰 코드, 날짜, 금액)
errors: list[str] = field(default_factory=list)
ignored: list[str] = field(default_factory=list) # 건너뛴 열(머리글 + 이유)
columns: list[str] = field(default_factory=list) # 반영 대상 쇼핑몰 코드(열 순서)
def _norm(text: Any) -> str:
return re.sub(r"\s+", "", str(text or "")).lower()
def _cell_ref(row: int, col: int) -> str:
letters = ""
n = col
while n:
n, r = divmod(n - 1, 26)
letters = chr(65 + r) + letters
return f"{letters}{row}"
def parse_date(value: Any) -> date | None:
"""날짜 칸 → date. 읽을 수 없으면 ValueError, 빈 칸이면 None."""
if value is None or (isinstance(value, str) and not value.strip()):
return None
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
if isinstance(value, (int, float)) and not isinstance(value, bool):
n = int(value)
if 19000101 <= n <= 29991231: # 20261012
return parse_date(str(n))
if 20000 <= n <= 80000: # 엑셀 날짜 일련번호(서식 없는 날짜)
return _EXCEL_EPOCH + timedelta(days=n)
raise ValueError
text = str(value).strip()
m = _DATE_RE.match(text) or _COMPACT_RE.match(text)
if not m:
raise ValueError
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
def parse_amount(value: Any) -> int | None:
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
if value is None or isinstance(value, bool):
if value is None:
return None
raise ValueError
if isinstance(value, (int, float, Decimal)):
num = Decimal(str(value))
else:
text = re.sub(r"[,\s원₩]", "", str(value))
if text == "":
return None
try:
num = Decimal(text)
except InvalidOperation:
raise ValueError from None
if not num.is_finite():
raise ValueError
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
"""머리글로 쓸 수 있는 이름 → 쇼핑몰 코드. markets: code·name, extra_names: 코드별 다른 이름(어댑터 이름·짧은 이름)."""
out: dict[str, str] = {}
for m in markets:
code = str(m["code"])
for alias in (code, m.get("name"), *((extra_names or {}).get(code) or ())):
key = _norm(alias)
if key:
out.setdefault(key, code)
return out
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
if not content:
raise UploadError("빈 파일입니다.")
if len(content) > MAX_FILE_BYTES:
raise UploadError("파일이 너무 큽니다(5MB 이하).")
try:
import openpyxl # noqa: WPS433
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
raise UploadError("엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.") from None
try:
ws = wb.worksheets[0]
rows = ws.iter_rows(values_only=True)
header = next(rows, None)
if not header or len(header) < 2:
raise UploadError("1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.")
aliases = header_aliases(markets, extra_names)
by_code = {str(m["code"]): m for m in markets}
res = ParseResult()
col_code: dict[int, str] = {} # 열 번호(0부터) → 반영할 쇼핑몰 코드
for idx, title in enumerate(header[1:], start=1):
if title is None or not str(title).strip():
continue
label = str(title).strip()
code = aliases.get(_norm(label))
if code is None:
res.ignored.append(f"{label}(알 수 없는 쇼핑몰)")
elif not by_code[code].get("manual_input"):
res.ignored.append(f"{label}(수동 입력 꺼짐)")
elif code in col_code.values():
res.errors.append(f"{_cell_ref(1, idx + 1)} {label}: 같은 쇼핑몰 열이 두 번 있습니다.")
else:
col_code[idx] = code
res.columns.append(code)
if not col_code and not res.errors:
raise UploadError("반영할 쇼핑몰 열이 없습니다. 머리글을 수동 입력이 켜진 쇼핑몰 이름으로 적어 주세요."
+ (f" (건너뛴 열: {', '.join(res.ignored)})" if res.ignored else ""))
seen: dict[tuple[str, date], str] = {}
data_rows = 0
for r, row in enumerate(rows, start=2):
row = tuple(row or ())
cells = {i: (row[i] if i < len(row) else None) for i in col_code}
amounts: dict[int, int] = {}
for i, raw in cells.items():
try:
amt = parse_amount(raw)
except ValueError:
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
continue
if amt is None:
continue
if abs(amt) > MAX_AMOUNT:
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 너무 큽니다.")
continue
amounts[i] = amt
raw_day = row[0] if row else None
try:
day = parse_date(raw_day)
except ValueError:
res.errors.append(f"{_cell_ref(r, 1)}: 날짜를 읽을 수 없습니다({raw_day}).")
continue
if day is None:
if amounts:
res.errors.append(f"{r}행: 날짜가 비어 있습니다.")
continue
if not amounts:
continue
data_rows += 1
if data_rows > MAX_DATA_ROWS:
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
for i, amt in amounts.items():
code = col_code[i]
where = _cell_ref(r, i + 1)
if (code, day) in seen:
res.errors.append(f"{where}: {by_code[code]['name']} {day.isoformat()} 이 {seen[(code, day)]} 와 겹칩니다.")
continue
seen[(code, day)] = where
res.entries.append((code, day, amt))
if len(res.errors) > MAX_ERRORS:
break
return res
finally:
wb.close()
+516 -20
View File
@@ -2,6 +2,7 @@
화면
GET /performance/ 대시보드(모듈 권한)
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
GET /performance/settings 실적 설정(관리자)
JSON API — 모듈 권한
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
@@ -10,8 +11,21 @@ JSON API — 모듈 권한
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
POST /performance/api/ad-sync [광고비 업데이트] — 설정된 광고 API 전부, 보는 기간(오늘까지), 진행 창 작업
(jobs kind="ads", 진행·취소·중지는 /api/sync/jobs/… 그대로), 92일 넘으면 관리자
GET /performance/api/ad-sync/current 진행 중인 광고비 업데이트(수동·자동) — 버튼이 진행 창을 다시 연다
POST /performance/api/ad-sources/{code}/sync 광고 API 채널 하나 가져오기(예전 [구글/메타 광고 불러오기], 화면 버튼은 2026-10-20 삭제)
JSON API — 관리자
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
DELETE /performance/api/marketplaces/{code}/rates/{id}
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
@@ -26,12 +40,13 @@ JSON API — 관리자
from __future__ import annotations
from datetime import date
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Body, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi import APIRouter, Body, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from app.timezone import today_kst
@@ -44,6 +59,21 @@ MAX_EVENT_DAYS = 31
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
MAX_BACKFILL_DAYS = 366
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원)
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
"먼저 적용해야 합니다.")
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007"
"(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.")
def _ad_migration_help(exc: Exception) -> str:
text = str(exc)
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
@@ -89,7 +119,7 @@ def dashboard_page(
from_: str | None = Query(None, alias="from"),
to: str | None = None,
m: list[str] = Query(default=[]),
metric: str = "gross",
metric: str = "net",
):
from app.main import render_template # noqa: WPS433
@@ -107,29 +137,123 @@ def dashboard_page(
custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m,
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
)
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
ctx["auto_sync"] = _auto_sync_ctx()
_unit_ctx(request, ctx)
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
def _auto_sync_ctx() -> dict[str, Any] | None:
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. 회차가 지나면 화면이 같은 규칙
(hours·slot, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정. 자동 업데이트가 꺼져 있으면 None."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
if not auto_sync.enabled():
return None
hours = auto_sync.hour_window()
now = now_kst()
return {"next_at": auto_sync.next_slot(now, hours).isoformat(), "now": now.isoformat(timespec="milliseconds"),
"hours": list(hours), "slot": auto_sync.SLOT_MINUTES}
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
ctx["unit"] = unit
ctx["unit_label"] = UNITS[unit][2]
ctx["amt"] = lambda v: amount_text(v, unit)
@router.get("/ads", response_class=HTMLResponse)
def ads_page(
request: Request,
period: str = "month",
d: str | None = None,
from_: str | None = Query(None, alias="from"),
to: str | None = None,
):
from app.main import render_template # noqa: WPS433
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
from .ad_spend import build_ad_dashboard # noqa: WPS433
from .dashboard import _sales_marketplaces # noqa: WPS433
today = today_kst()
ctx = build_ad_dashboard(
store, kind=period, anchor=_parse_date(d) or today, today=today,
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
)
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
from . import jobs # noqa: WPS433
from .ad_sources.registry import get_source # noqa: WPS433
from .ad_sync import last_ad_update_at # noqa: WPS433
_, ad_sync = _ad_services(store)
try:
configured = ad_sync.configured()
except Exception: # noqa: BLE001 — 007 미적용 등: 버튼만 숨김
configured = {}
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in configured.items() if ok]
ctx["ad_last_update_at"] = last_ad_update_at(store)
ctx["ad_running"] = jobs.running_job("ads") is not None
ctx["auto_sync"] = _auto_sync_ctx()
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@router.get("/settings", response_class=HTMLResponse)
def settings_page(request: Request):
from app.main import render_template # noqa: WPS433
g = common.guard(request, admin=True)
# 모듈 권한자 누구나 들어온다 — 일반 사용자는 수수료율만(쇼핑몰 표의 다른 칸·다른 카드는 템플릿이 관리자에게만 그린다).
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
from .dashboard import build_settings # noqa: WPS433
creds, _ = common.services(request, store)
ad_creds, ad_sync = _ad_services(store)
versions = creds.key_versions_in_use()
for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키
versions[v] = versions.get(v, 0) + n
ctx = build_settings(
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
key_versions_in_use=versions, sample_count=store.sample_count(),
)
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
ctx["ad_api_ready"] = store.ad_api_ready()
_unit_ctx(request, ctx)
return render_template(request, "performance/settings.html",
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
from .ad_sources.registry import all_sources # noqa: WPS433
from .adapters.base import STATUS_LABELS # noqa: WPS433
statuses = store.ad_source_statuses()
rows = []
for s in all_sources():
st = statuses.get(s.code, {})
status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured")
rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status,
"status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"),
"last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"),
"last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")})
return rows
# ════════════════════════════════════════════════════════════
# JSON API — 모듈 권한
# ════════════════════════════════════════════════════════════
@@ -227,6 +351,25 @@ def api_sync_cancel(request: Request, job_id: str) -> JSONResponse:
return JSONResponse({"job": job.snapshot()})
@router.post("/api/sync/jobs/{job_id}/shops/{code}/stop")
def api_sync_stop_shop(request: Request, job_id: str, code: str) -> JSONResponse:
"""쇼핑몰별 [중지] — 시작한 사람 또는 관리자. 그 쇼핑몰만 다음 API 호출 직전에 멈추고(저장 안 함, 기존 매출 그대로)
업데이트는 다음 쇼핑몰로 넘어간다. 차례가 안 온 쇼핑몰은 차례가 오면 건너뛴다. 저장 중·끝난 쇼핑몰은 409."""
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="업데이트를 시작한 사람이나 관리자만 중지할 수 있습니다.")
if not job.stop_shop(code):
raise HTTPException(status_code=409, detail="이미 끝났거나 저장 중인 쇼핑몰은 중지할 수 없습니다.")
return JSONResponse({"job": job.snapshot()})
@router.get("/api/sync/current")
def api_sync_current(request: Request) -> JSONResponse:
common.require_store(request)
@@ -250,24 +393,363 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
def _cell_amount(raw: Any) -> tuple[int | None, str | None]:
"""날짜 칸 입력(매출 수동 입력·광고비) → (금액, 계산식). 빈 칸 = 지움."""
from .formula import FormulaError, parse_amount # noqa: WPS433
try:
amount, formula = parse_amount(raw)
except FormulaError as exc:
raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None
if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT:
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
return amount, formula
@router.put("/api/manual-sales/{code}/{day}")
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞으로의 날도 가능(2026-10-21). amount 가 비면 지움(그날은 다시 API 값).
amount 는 숫자 또는 계산식(1000+2000 — formula.parse_amount)."""
from .db import ManualMigrationNeeded # noqa: WPS433
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
_code_or_404(store, code)
d = _parse_date(day)
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
if not m.get("manual_input"):
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
amount, formula = _cell_amount(payload.get("amount"))
try:
store.set_manual_sale(code, d, amount, user=user.get("email", ""), formula=formula)
except ManualMigrationNeeded:
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
api_amount = store.api_amount(code, d)
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount, "formula": formula,
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
@router.get("/api/manual-sales/sample.xlsx")
def api_manual_sample(request: Request) -> Any:
common.require_store(request)
if not MANUAL_SAMPLE_PATH.is_file():
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@router.post("/api/manual-sales/upload")
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
from . import manual_upload # noqa: WPS433
from .dashboard import _short_name # noqa: WPS433
from .db import ManualMigrationNeeded # noqa: WPS433
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
known = {a.code: a for a in all_adapters()}
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
try:
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
except manual_upload.UploadError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
names = {m["code"]: m["name"] for m in markets}
if res.errors:
return JSONResponse(status_code=400, content={
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
try:
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
except ManualMigrationNeeded:
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
counts: dict[str, int] = {}
for code, _, _ in res.entries:
counts[code] = counts.get(code, 0) + 1
days = sorted({d for _, d, _ in res.entries})
return JSONResponse({
"ok": True, "saved": saved,
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
"ignored": res.ignored,
})
# ════════════════════════════════════════════════════════════
# JSON API — 관리자(설정)
# JSON API — 광고비(모듈 권한자 누구나)
# ════════════════════════════════════════════════════════════
def _ad_channel(channel: str) -> str:
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
if channel not in CHANNEL_NAMES:
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
return channel
@router.put("/api/ad-spend/{channel}/{day}")
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
store, user = common.require_store(request)
_ad_channel(channel)
d = _parse_date(day)
if d is None:
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
amount, formula = _cell_amount(payload.get("amount"))
try:
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""), formula=formula)
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, "formula": formula,
"amount": amount or 0})
@router.get("/api/ad-spend/{channel}/details")
def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
"""일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
from . import ad_spend # noqa: WPS433
store, _ = common.require_store(request)
_ad_channel(channel)
if channel not in ad_spend.DETAIL_CHANNELS:
raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
if start is None or end is None or end < start or (end - start).days > 365:
raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
try:
rows = store.ad_details(channel, start, end)
except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
@router.post("/api/ad-spend/upload")
def api_ad_spend_upload(
request: Request,
channel: str = Query(...),
files: list[UploadFile] | None = File(None),
file: UploadFile | None = File(None),
modified: list[str] = Form(default=[]),
) -> JSONResponse:
"""광고비 파일 업로드(여러 파일 가능, 2026-10-14) — 파일에 있는 날만 덮어쓴다. 같은 날짜가 여러 파일에 있으면
파일 날짜(브라우저가 보낸 수정 시각 modified, 파일 순서대로 ms)가 최신인 파일 값. 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다."""
from . import ad_spend # noqa: WPS433
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
store, user = common.require_store(request)
_ad_channel(channel)
parser = ad_spend.PARSERS.get(channel)
if parser is None:
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
uploads = list(files or []) + ([file] if file is not None else [])
if not uploads:
raise HTTPException(status_code=400, detail="파일을 고르세요.")
if len(uploads) > ad_spend.MAX_UPLOAD_FILES:
raise HTTPException(status_code=400, detail=f"한 번에 {ad_spend.MAX_UPLOAD_FILES}개 파일까지 올릴 수 있습니다.")
parsed = []
for i, up in enumerate(uploads):
name = up.filename or f"파일{i + 1}"
try:
mtime = float(modified[i]) if i < len(modified) and str(modified[i]).strip() else 0.0
except ValueError:
mtime = 0.0
try:
parsed.append((name, mtime, parser(up.file.read(MAX_FILE_BYTES + 1), today=today_kst(), filename=name)))
except UploadError as exc:
raise HTTPException(status_code=400, detail=(f"[{name}] " if len(uploads) > 1 else "") + str(exc)) from None
res, overlap = ad_spend.merge_results(parsed)
if res.errors:
return JSONResponse(status_code=400, content={
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
"errors": res.errors[:60]})
report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
try:
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
days = sorted(d for d, _ in res.entries)
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
# ════════════════════════════════════════════════════════════
# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자)
# ════════════════════════════════════════════════════════════
def _ad_services(store: Any):
"""(광고 인증정보 서비스, 광고 가져오기 서비스)."""
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
creds = ad_credentials(store, common.key_ring)
return creds, AdSyncService(store, creds)
def _ad_source_or_404(code: str):
from .ad_sources.registry import get_source # noqa: WPS433
src = get_source(code)
if src is None:
raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.")
return src
@router.get("/api/ad-sources/{code}/credentials")
def api_ad_source_credentials(request: Request, code: str) -> JSONResponse:
"""입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양."""
store, _ = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
creds, _ = _ad_services(store)
info = creds.describe(src)
if not store.ad_api_ready():
info["decrypt_error"] = AD_MIGRATION_HELP_007
return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url,
"key": common.key_status(), **info})
@router.put("/api/ad-sources/{code}/credentials")
def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
from .ad_spend import AdMigrationNeeded # noqa: WPS433
store, user = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
if not common.key_status()["ok"]:
raise HTTPException(status_code=503, detail=common.key_status()["message"])
creds, _ = _ad_services(store)
values = _clean_values(src, payload)
clear = [str(k) for k in (payload.get("clear") or [])]
merged = creds.merged_values(src, values)
for k in clear:
if k in merged and not values.get(k):
merged[k] = ""
errors = src.validate_credentials(merged)
if errors:
raise HTTPException(status_code=400, detail=" ".join(errors))
try:
saved = creds.save(src, values, clear=clear, user=user["email"])
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"saved": saved, **creds.describe(src)})
@router.post("/api/ad-sources/{code}/test")
def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값)."""
store, user = common.require_store(request, admin=True)
src = _ad_source_or_404(code)
_, ad_sync = _ad_services(store)
values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()}
cleared = _cleared_keys(src, payload, values)
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
def _ad_sync_period(payload: dict[str, Any], user: dict[str, Any]) -> tuple[date, date]:
"""광고 가져오기 기간 — from·to(없으면 최근 N일), 오늘 뒤는 자름. 모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
from app.store import is_admin # noqa: WPS433
from .auto_sync import sync_days # noqa: WPS433
today = today_kst()
end = _parse_date(payload.get("to"), field="종료일") or today
start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1))
if end < start:
start, end = end, start
end = min(end, today)
if start > end:
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
days = (end - start).days + 1
if days > MAX_BACKFILL_DAYS:
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
return start, end
@router.post("/api/ad-sync")
def api_ad_sync(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""[광고비 업데이트](2026-10-20) — 설정된 광고 API 전부를 백그라운드 진행 창 작업으로. 이미 돌고 있는 광고비 업데이트
(다른 사람·자동 업데이트)가 있으면 새로 시작하지 않고 그 작업을 돌려준다(joined)."""
import threading # noqa: WPS433
from . import jobs # noqa: WPS433
from .ad_sync import run_ad_job # noqa: WPS433
store, user = common.require_store(request)
live = jobs.running_job("ads")
if live is not None:
return JSONResponse({"job": live.snapshot(), "joined": True})
start, end = _ad_sync_period(payload, user)
_, ad_sync = _ad_services(store)
if not any(ad_sync.configured().values()):
raise HTTPException(status_code=400, detail="설정된 광고 API 가 없습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
job = jobs.create_job(user=user["email"], start=start, end=end, kind="ads")
threading.Thread(target=run_ad_job, args=(store, common.key_ring, job, start, end),
kwargs={"user": user["email"]}, name=f"perf-ad-sync-{job.id}", daemon=True).start()
return JSONResponse({"job": job.snapshot(), "joined": False})
@router.get("/api/ad-sync/current")
def api_ad_sync_current(request: Request) -> JSONResponse:
common.require_store(request)
from . import jobs # noqa: WPS433
job = jobs.running_job("ads")
return JSONResponse({"job": job.snapshot() if job else None})
@router.post("/api/ad-sources/{code}/sync")
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""광고 API 채널 하나 가져오기(진행 창 없이) — 기간(from·to, 없으면 최근 N일). 오늘 뒤는 잘라낸다.
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만. 화면은 [광고비 업데이트](/api/ad-sync)를 쓴다."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
from .ad_sync import AdSyncBusy # noqa: WPS433
store, user = common.require_store(request)
src = _ad_source_or_404(code)
start, end = _ad_sync_period(payload, user)
_, ad_sync = _ad_services(store)
if not ad_sync.configured().get(code):
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
try:
res = ad_sync.sync(code, start, end, user=user["email"])
except AdSyncBusy as exc:
raise HTTPException(status_code=409, detail=str(exc)) from None
except AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
if not res.get("ok"):
return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res})
return JSONResponse(res)
# ════════════════════════════════════════════════════════════
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
@router.put("/api/marketplaces/{code}")
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
_code_or_404(store, code)
row = store.update_marketplace(
code,
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
)
from .db import ManualMigrationNeeded # noqa: WPS433
adapter = get_adapter(code)
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
try:
row = store.update_marketplace(
code,
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
)
except ManualMigrationNeeded:
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
return JSONResponse({"marketplace": row})
@router.post("/api/marketplaces/{code}/rates")
def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
store, user = common.require_store(request, admin=True)
store, user = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
raw = str(payload.get("rate_percent", "")).strip().rstrip("%").strip()
try:
@@ -288,14 +770,14 @@ def api_set_rate(request: Request, code: str, payload: dict[str, Any] = Body(...
@router.get("/api/marketplaces/{code}/rates")
def api_list_rates(request: Request, code: str) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
return JSONResponse({"rates": store.list_rates(code)})
@router.delete("/api/marketplaces/{code}/rates/{rate_id}")
def api_delete_rate(request: Request, code: str, rate_id: int) -> JSONResponse:
store, _ = common.require_store(request, admin=True)
store, _ = common.require_store(request) # 수수료 설정은 모듈 권한자 누구나
_code_or_404(store, code)
if not store.delete_rate(code, rate_id):
raise HTTPException(status_code=404, detail="수수료 이력을 찾지 못했습니다.")
@@ -346,15 +828,23 @@ def api_save_credentials(request: Request, code: str, payload: dict[str, Any] =
@router.post("/api/marketplaces/{code}/test")
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용)."""
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용), clear = 화면에서 비운 항목은 빈 값으로.
광고 API 시험(/api/ad-sources/{code}/test)과 같은 요청·응답 계약 — 공통 설정 창이 둘 다 쓴다(검토 F09)."""
store, user = common.require_store(request, admin=True)
adapter = _code_or_404(store, code)
_, sync = common.services(request, store)
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
result = sync.test_connection(code, values=values or None, user=user["email"])
cleared = _cleared_keys(adapter, payload, values)
result = sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None)
return JSONResponse(result)
def _cleared_keys(source: Any, payload: dict[str, Any], values: dict[str, str]) -> set[str]:
"""요청의 clear 중 이 연동의 화면 항목이면서 새 값이 없는 것 — 연결 시험에서 빈 값으로 본다."""
allowed = {f.key for f in source.visible_fields()}
return {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values}
@router.get("/api/marketplaces/{code}/reconcile")
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
@@ -408,4 +898,10 @@ def api_rekey(request: Request) -> JSONResponse:
if not common.key_status()["ok"]:
raise HTTPException(status_code=503, detail=common.key_status()["message"])
creds, _ = common.services(request, store)
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
ad_creds, _ = _ad_services(store)
shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키
versions = creds.key_versions_in_use()
for v, n in ad_creds.key_versions_in_use().items():
versions[v] = versions.get(v, 0) + n
return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"],
"versions_in_use": versions})
+22 -14
View File
@@ -58,8 +58,8 @@ class SyncService:
self._app_state = app_state
def _ctx(self, adapter: MarketplaceAdapter, *, overrides: dict[str, str] | None = None,
persist: bool = True, user: str = "") -> AdapterContext:
acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user)
persist: bool = True, user: str = "", cleared: set[str] | None = None) -> AdapterContext:
acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user, cleared=cleared)
return AdapterContext(code=adapter.code, credentials=acc, app_state=self._app_state)
@staticmethod
@@ -72,15 +72,17 @@ class SyncService:
return "api_error", redact_text(f"예상하지 못한 오류: {type(exc).__name__}: {exc}", known)
# ── 연결 테스트 ─────────────────────────────────────────
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]:
"""values 를 주면 저장하지 않은 새 입력값으로 시험(저장된 상태는 바꾸지 않음)."""
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
cleared: set[str] | None = None) -> dict[str, Any]:
"""values 를 주면 저장하지 않은 새 입력값으로, cleared = 화면에서 비운 항목은 저장값 대신 빈 값으로 시험한다.
둘 중 하나라도 있으면 저장하지 않은 시험이라 연결 상태·토큰을 저장하지 않는다(광고 API 시험과 같은 계약, 검토 F09)."""
adapter = get_adapter(code)
if adapter is None:
return {"ok": False, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
unsaved = bool(values)
unsaved = bool(values) or bool(cleared)
ctx = None
try:
ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user)
ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user, cleared=cleared)
message = adapter.test_connection(ctx)
status, ok = "ok", True
except Exception as exc: # noqa: BLE001 — 어떤 오류든 상태로 바꿔 화면에 보여 준다
@@ -102,9 +104,9 @@ class SyncService:
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: # [업데이트 취소] 뒤 차례가 온 쇼핑몰
if progress is not None and progress.cancel_requested: # [업데이트 취소]·쇼핑몰 [중지] 뒤 차례가 온 쇼핑몰
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
return {**result, "cancelled": True, "status": "cancelled", "message": progress.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:
@@ -119,7 +121,8 @@ class SyncService:
ctx.progress = progress
fetched, events = adapter.collect(ctx, start, end)
if progress is not None:
progress.saving()
# 중지 확인과 저장 시작을 한 잠금에서 — collect() 끝 무렵에 받아들인 [중지]면 여기서 Cancelled(저장 안 함)
progress.begin_saving()
known = ctx.credentials.known_secrets()
rows = [event_row(ev, known) for ev in events]
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
@@ -140,11 +143,13 @@ class SyncService:
return {**result, "ok": True, "status": "ok", "fetched": fetched, "upserted": upserted,
"message": f"{upserted}건 반영"}
except Cancelled:
# 수집 중 취소 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
self._store.finish_run(run_id, ok=False, error="업데이트 취소")
# 수집 중 취소·중지 — 아직 아무것도 저장하지 않았다. 연결 상태(오류 표시)는 바꾸지 않는다.
# 쇼핑몰 [중지]면 이 쇼핑몰만 멈추고 sync_all 이 다음 쇼핑몰로 넘어간다.
stopped = progress is not None and progress.stopped_only
self._store.finish_run(run_id, ok=False, error="쇼핑몰 중지" if stopped else "업데이트 취소")
if progress is not None:
progress.cancelled()
return {**result, "cancelled": True, "status": "cancelled", "message": "취소됨"}
return {**result, "cancelled": True, "status": "cancelled", "message": "중지됨" if stopped else "취소됨"}
except Exception as exc: # noqa: BLE001 — 한 쇼핑몰 실패가 전체를 멈추지 않게
status, message = self._failure(exc, ctx)
logger.warning("performance sync %s failed: %s %s", code, status, message)
@@ -159,8 +164,11 @@ class SyncService:
"""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 for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
# 설정에서 수동 입력을 켠 쇼핑몰은 API 가 설정돼 있어도 매출 업데이트(수동·자동·과거 매출 가져오기)에서 뺀다
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"] and not m.get("manual_input")}
# 수동 입력 전용 쇼핑몰(manual_only)은 가져올 API 가 없어 매출 업데이트에서 뺀다
targets = [a for a in all_adapters()
if a.code in enabled and not a.manual_only and (not codes or a.code in codes)]
progress: dict[str, Any] = {}
if job is not None:
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
@@ -1,7 +1,16 @@
{# 실적 모듈 탭 — 설정 탭은 관리자에게만(서버도 관리자만 허용). #}
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<nav class="perf-tabs" aria-label="실적 메뉴">
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
{% if is_admin %}
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">설정</a>
{% endif %}
<div class="perf-tabs-main" role="tablist">
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
</div>
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
</nav>
@@ -0,0 +1,241 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
{%- endmacro -%}
{% block content %}
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
{% include "performance/_tabs.html" %}
<div class="perf-toolbar">
<div class="perf-quick" role="group" aria-label="기간 선택">
{% for q in nav.quick %}
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
{% endfor %}
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
</div>
<div class="perf-nav">
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
<span class="perf-nav-label">{{ period.label }}</span>
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
</div>
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(매출과 같은 회차)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %}
<div class="perf-update">
<span class="perf-muted" id="perf-last-update" title="광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }}) 마지막 업데이트">마지막 업데이트
<b>{{ (ad_last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
{% if auto_sync %}
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다(매출과 같은 시각)">다음 업데이트까지 <b>—</b></span>
{% endif %}
<button type="button" class="erp-btn erp-btn-primary{% if ad_running %} is-running{% endif %}" id="perf-ad-sync-btn"
title="{% if ad_running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 광고비·ROAS 를 광고 API({{ ad_sync_sources | map(attribute='name') | join('·') }})에서 다시 가져옵니다{% endif %}">
{% if ad_running %}업데이트 중 · 진행 보기{% else %}광고비 업데이트{% endif %}
</button>
</div>
{% endif %}
</div>
<div class="perf-notice" id="perf-sync-result" hidden></div>
{% if migration_needed %}
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
{% endif %}
<!-- ── KPI ── -->
<div class="perf-kpis">
{% for k in kpis %}
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
<div class="perf-kpi-label">{{ k.label }}</div>
{% if k.key == 'ratio' %}
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
{% else %}
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
<div class="perf-kpi-delta">
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
{% set up = k.delta > 0 %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
</div>
{% endif %}
</div>
{% endfor %}
</div>
<!-- ── 일자 × 채널 ── -->
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
<div class="perf-ad-actions">
{% if upload_channels %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
{% endif %}
</div>
</div>
<div class="erp-table-wrap perf-table-wrap">
<table class="perf-table perf-main">
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
<tbody>
{% for r in table %}
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
{% for c in codes %}
{% set v = r.cells[c].gross %}
{% if r.kind == 'day' and not migration_needed %}
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %}
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}"
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %} tabindex="0"
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% elif fx %}계산식 {{ fx }} — 눌러 고치기{% else %}눌러 광고비 입력(1000+2000 같은 계산식도 됨, 비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% else %}
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if period_kind != 'year' %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% endif %}
</div>
<!-- ── 그래프 ── -->
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">채널별 비중</h2>
<span class="perf-muted">{{ period.label }}</span></div>
<div class="perf-chart" id="perf-chart-share"></div>
</div>
</div>
<!-- ── 월 누적 · 연간 누적 ── -->
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 채널별 광고비</h2></div>
<div class="erp-table-wrap">
<table class="perf-table">
<thead><tr><th class="perf-th-label">채널</th><th>광고비</th><th>ROAS</th><th>비중</th></tr></thead>
<tbody>
{% for r in month.rows %}
<tr>
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
<td class="perf-num">{{ won(r.gross) }}</td>
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
<td class="perf-num perf-share">
{% if r.share is not none %}<span class="perf-bar" style="--w: {{ [r.share, 0] | max }}%"></span>{{ "%.1f" | format(r.share) }}%{% else %}<span class="perf-zero">–</span>{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="perf-row-total">
<th class="perf-td-label" scope="row">합계</th>
<td class="perf-num">{{ won(month.total.gross) }}</td>
<td class="perf-num">{% if month.total.roas is not none %}{{ "{:,}".format(month.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
<td class="perf-num">{% if month.total.share is not none %}100%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
</tr>
</tfoot>
</table>
</div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
<div class="perf-year-sum">
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
</div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
<thead><tr><th class="perf-th-label">월</th><th>광고비</th><th>ROAS</th></tr></thead>
<tbody>
{% for r in year.rows %}
<tr class="{% if r.future %}is-future{% endif %}">
<th class="perf-td-label" scope="row">{{ r.label }}</th>
<td class="perf-num">{{ won(r.gross) }}</td>
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% elif not r.future %}<span class="perf-zero">–</span>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="perf-row-total">
<th class="perf-td-label" scope="row">합계</th>
<td class="perf-num">{{ won(year.total.gross) }}</td>
<td class="perf-num">{% if year.total.roas is not none %}{{ "{:,}".format(year.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
<p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
</p>
</section>
<script type="application/json" id="perf-data">{{ {
"names": names,
"codes": codes,
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind,
"today": today,
"manual_api": "/performance/api/ad-spend/",
"manual_word": "광고비",
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"period_label": period.label,
"empty_text": "기간 내 광고비가 없습니다.",
"upload_channels": upload_channels,
"auto_sync": auto_sync
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261021a" defer></script>{% endblock %}
@@ -1,11 +1,27 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
{%- else -%}{{ amt(v) }}{%- endif -%}
{%- endmacro -%}
{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#}
{%- macro money(v) -%}
{%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
{%- endmacro -%}
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
{%- macro adl(lines) -%}
{%- for a in lines or [] -%}<span class="perf-adl" title="{{ (a.label ~ ' ') if a.label }}광고비 {{ '{:,}'.format(a.amount) }}원{% if a.roas is not none %} · ROAS {{ '{:,}'.format(a.roas) }}%{% endif %}">{% if a.label %}<i>{{ a.label }}</i>{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}<em>({{ "{:,}".format(a.roas) }}%)</em>{% endif %}</span>{%- endfor -%}
{%- endmacro -%}
{#- 일 합계 광고비(ROAS%) — ROAS = 일 합계 금액 ÷ 일 합계 광고비. 수수료 차감 매출 보기면 차감 매출 기준, 그 밖엔 총매출 기준 -#}
{%- macro adl_total(a) -%}
{%- for key, cls in (("roas", "for-gross"), ("roas_net", "for-net")) -%}
{%- set rs = a[key] -%}
<span class="perf-adl perf-adl-tot {{ cls }}" title="광고비 합계 {{ '{:,}'.format(a.amount) }}원{% if rs is not none %} · ROAS {{ '{:,}'.format(rs) }}% (일 합계 {{ '수수료 차감 매출' if key == 'roas_net' else '총매출' }} ÷ 광고비){% endif %}">{{ amt(a.amount) }}{% if rs is not none %}<em>({{ "{:,}".format(rs) }}%)</em>{% endif %}</span>
{%- endfor -%}
{%- endmacro -%}
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
@@ -64,9 +80,14 @@
<div class="perf-update">
<span class="perf-muted" id="perf-last-update">마지막 업데이트
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
<button type="button" class="erp-btn erp-btn-primary" id="perf-sync-btn"{% if running %} disabled{% endif %}
title="지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다">
{% if running %}업데이트 중…{% else %}매출 업데이트{% endif %}
{% if auto_sync %}
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다">다음 업데이트까지 <b>—</b></span>
{% endif %}
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
title="{% if running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다{% endif %}">
{% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %}
</button>
</div>
</div>
@@ -84,29 +105,29 @@
{% endif %}
<div class="perf-notice" id="perf-sync-result" hidden></div>
<!-- ── KPI ── -->
<div class="perf-kpis">
{% for k in kpis %}
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
<div class="perf-kpi-label">{{ k.label }}</div>
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
<div class="perf-kpi-delta">
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
{% set up = k.delta > 0 %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
</div>
</div>
{% endfor %}
<!-- ── KPI — 수수료 차감 매출 한 줄(금액 + 비교 기간 대비 %, 2026-10-19) ── -->
{% for k in kpis %}
<div class="perf-kpi-line" title="{{ k.label }}">
<b class="perf-kpi-line-value">{{ money(k.value) }}</b>
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %}
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif k.delta > 0 %}is-up{% else %}is-down{% endif %}">
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
</div>
{% endfor %}
<!-- ── 일자 × 쇼핑몰 ── -->
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
<span class="perf-head-notes">{% if unit != 'won' %}<span class="perf-muted">단위: {{ unit_label }}</span>{% endif %}
<span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 카페24 는 구글·메타"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
{% if manual_upload_names %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
{% endif %}
<div class="perf-metric" role="group" aria-label="표시 기준">
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
@@ -118,7 +139,7 @@
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% for c in codes %}<th title="{{ names[c] }}">{{ short_names[c] }}</th>{% endfor %}
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
</tr>
</thead>
@@ -130,15 +151,27 @@
</th>
{% for c in codes %}
{% set m = r.cells[c] %}
{% if r.kind == 'day' and c in manual_codes %}
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %} tabindex="0"
title="{% if fx %}계산식 {{ fx }} — 눌러 고치기{% elif is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력(1000+2000 같은 계산식도 됨){% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% else %}
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if manual_codes and period_kind != 'year' %}
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
비우고 저장하면 다시 API 수집값. <b>1000+2000</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
{% endif %}
</div>
<!-- ── 그래프 ── -->
@@ -158,7 +191,7 @@
<!-- ── 월 누적 · 연간 누적 ── -->
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2></div>
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</div>
<div class="erp-table-wrap">
<table class="perf-table">
<thead><tr><th class="perf-th-label">쇼핑몰</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th><th>매출 비중</th></tr></thead>
@@ -189,11 +222,11 @@
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</div>
<div class="perf-year-sum">
<div><span>총매출</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
<div><span>수수료</span><b>₩{{ "{:,}".format(year.total.commission) }}</b></div>
<div><span>수수료 차감 매출</span><b>₩{{ "{:,}".format(year.total.net) }}</b></div>
<div><span>총매출</span><b>{{ money(year.total.gross) }}</b></div>
<div><span>수수료</span><b>{{ money(year.total.commission) }}</b></div>
<div><span>수수료 차감 매출</span><b>{{ money(year.total.net) }}</b></div>
</div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
@@ -235,8 +268,11 @@
"period_kind": period_kind,
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"today": today
"today": today,
"unit": unit,
"manual_upload_names": manual_upload_names,
"auto_sync": auto_sync
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261021a" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20260930g" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261021a" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -8,7 +8,8 @@
<section class="perf perf-settings" id="perf-settings">
{% include "performance/_tabs.html" %}
{% if not key_info.ok %}
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
{% if is_admin and not key_info.ok %}
<div class="perf-notice is-warn">
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
@@ -18,26 +19,33 @@
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">쇼핑몰 설정</h2>
<span class="perf-muted">사용 · 매출 집계 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.</span>
{% if is_admin %}
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span>
{% else %}
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
{% endif %}
</div>
<div class="erp-table-wrap">
<table class="perf-table perf-set-table">
<thead>
<tr>
<th class="perf-th-label">쇼핑몰</th>
<th>사용</th>
{% if is_admin %}<th>사용</th>
<th>매출 집계</th>
<th>수동 입력</th>{% endif %}
<th>수수료율</th>
<th>API 설정</th>
<th>연결 상태</th>
{% if is_admin %}<th>API 설정</th>
<th>연결 상태</th>{% endif %}
<th>마지막 동기화</th>
<th></th>
{% if is_admin %}<th></th>{% endif %}
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr data-code="{{ r.code }}" data-name="{{ r.name }}">
<th class="perf-td-label" scope="row">{{ r.name }}</th>
{% if is_admin %}
<td class="perf-center">
<label class="perf-switch" title="사용 여부">
<input type="checkbox" data-field="enabled"{% if r.enabled %} checked{% endif %} /><span></span>
@@ -48,13 +56,21 @@
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
</label>
</td>
<td class="perf-center">
<label class="perf-switch" title="{% if r.manual_only %}수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다{% else %}수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신), 매출 업데이트(수동·자동)에서 빠짐{% endif %}">
<input type="checkbox" data-field="manual_input"{% if r.manual_input or r.manual_only %} checked{% endif %}{% if r.manual_only %} disabled{% endif %} /><span></span>
</label>
</td>
{% endif %}
<td class="perf-rate-cell">
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
</td>
{% if is_admin %}
<td>
{% if r.shared %}<span class="perf-pill">공통 연동</span>
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
{% elif r.shared %}<span class="perf-pill">공통 연동</span>
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
{% else %}<span class="perf-pill">미설정</span>{% endif %}
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
@@ -65,7 +81,76 @@
<i></i>{{ r.status_label }}</span>
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
</td>
{% endif %}
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
{% if is_admin %}
<td class="perf-nowrap">
{% if not r.manual_only %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="perf-foot perf-muted">
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
</p>
</div>
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
<div class="erp-card perf-card" id="perf-view-opts">
<div class="perf-card-head">
<h2 class="perf-h">보기 설정</h2>
<span class="perf-muted">매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
</div>
<div class="perf-opt-row">
<span class="perf-opt-label">매출 단위</span>
<div class="perf-quick" role="radiogroup" aria-label="매출 단위">
{% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %}
<button type="button" class="perf-seg{% if unit == k %} is-active{% endif %}" role="radio"
aria-checked="{{ 'true' if unit == k else 'false' }}" data-unit="{{ k }}">{{ label }}</button>
{% endfor %}
</div>
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
</div>
</div>
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
<div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
(scripts/sql/performance_db_007_ad_api.sql)을 적용해야 저장할 수 있습니다.</div>
{% endif %}
<div class="erp-table-wrap">
<table class="perf-table perf-set-table">
<thead>
<tr><th class="perf-th-label">광고</th><th>API 설정</th><th>연결 상태</th><th>마지막 가져오기</th><th></th></tr>
</thead>
<tbody>
{% for a in ad_sources %}
<tr data-code="{{ a.code }}" data-name="{{ a.name }}" data-api="ad-sources">
<th class="perf-td-label" scope="row">{{ a.name }}</th>
<td>{% if a.configured %}<span class="perf-pill is-ok">설정완료</span>{% else %}<span class="perf-pill">미설정</span>{% endif %}</td>
<td>
<span class="perf-status st-{{ a.status }}"
title="마지막 연결 테스트: {{ when(a.last_test_at) }}{% if a.last_error %}&#10;최근 오류({{ when(a.last_error_at) }}): {{ a.last_error }}{% endif %}">
<i></i>{{ a.status_label }}</span>
{% if a.last_error and a.status not in ('ok',) %}<div class="perf-err">{{ a.last_error }}</div>{% endif %}
</td>
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(a.last_sync_at) }}">{{ when(a.last_success_sync_at) }}</td>
<td class="perf-nowrap">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
@@ -76,8 +161,9 @@
</table>
</div>
<p class="perf-foot perf-muted">
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.<br>
메타 광고: 광고비 = 광고 관리자의 "지출 금액" 그대로(메타 금액은 이미 부가세 포함), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 "구매 ROAS"). 광고 계정이 여러 개면 날짜별로 합칩니다. 날짜는 광고 계정 시간대 기준이며, 달러 등 외화 계정은 그날 환율로 원화로 바꿔 넣습니다(중앙은행 고시 환율 종합, 그날 값이 없으면 직전 값).
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
</p>
</div>
@@ -98,7 +184,7 @@
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
{% endif %}
<p class="perf-foot perf-muted">
API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
</p>
</div>
@@ -116,51 +202,6 @@
<div class="perf-notice" id="perf-backfill-result" hidden></div>
</div>
<div class="erp-card perf-card perf-card-wide">
<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">불러오기</button>
</div>
<div id="perf-probe-result"></div>
</div>
<div class="erp-card perf-card perf-card-wide">
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.</p>
<div class="perf-sample-form">
<input class="erp-input perf-date" type="date" id="perf-recon-date" value="{{ default_sample_to }}" />
<button type="button" class="erp-btn erp-btn-outline" id="perf-recon">대조</button>
</div>
<div id="perf-recon-result"></div>
<h3 class="perf-h" style="margin:18px 0 6px">일별 한 번에 비교</h3>
<p class="perf-muted">카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
[API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.</p>
<textarea class="erp-input perf-paste" id="perf-daily-paste" rows="5"
placeholder="2026-09-29(화) 47 116 2,475,300 … 2,477,800 158,000 2,319,800"></textarea>
<div class="perf-sample-form" style="margin-top:6px">
<label class="perf-muted"><input type="checkbox" id="perf-daily-live" /> API 값도 계산(느림)</label>
<button type="button" class="erp-btn erp-btn-outline" id="perf-daily-check">비교</button>
</div>
<div id="perf-daily-result"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
@@ -174,7 +215,8 @@
</div>
</div>
</div>
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930zb" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261021a" defer></script>{% endblock %}
@@ -0,0 +1,426 @@
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
from __future__ import annotations
import io
from datetime import date
from decimal import Decimal
import openpyxl
import pytest
from app.modules.performance import ad_spend as ads
from app.modules.performance.manual_upload import UploadError
TODAY = date(2026, 10, 13)
# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄
ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세)
전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494
2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,,
2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,,
2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,,
"""
def _xlsx(text: str) -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
for line in text.strip().splitlines():
ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")])
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
@pytest.mark.parametrize("content,name", [
(ROCKET_CSV.encode("utf-8-sig"), "report.csv"),
(ROCKET_CSV.encode("cp949"), "report.csv"),
(_xlsx(ROCKET_CSV), "report.xlsx"),
])
def test_rocket_report_reads_date_and_col19(content, name):
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
assert not res.errors
assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)]
assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개
def test_rocket_report_errors_block_everything():
bad = ROCKET_CSV + "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
bad += "2026년 10월 08일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n" # 금액이 숫자 아님
bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜 — 됨(2026-10-21)
res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY)
joined = " / ".join(res.errors)
assert len(res.errors) == 2, res.errors
assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" not in joined
assert (date(2026, 10, 20), 5) in res.entries
def test_coupang_report_date_rows_col19_summed_empty_skipped():
"""쿠팡(윙) 보고서처럼 캠페인 줄에도 1열 날짜가 있고 19열이 비어 있어도 — 날짜가 있는 줄의 19열 값만, 같은 날은 더한다
(2026-10-14 사용자 확인: "쿠팡은 모두 1열에서 날짜가 있는 행의 19열 값"). 값이 한 줄도 없는 날은 empty_days."""
head = ROCKET_CSV.splitlines()[0]
wing = "\n".join([
head,
"2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 날짜 있고 19열 빈 줄
"2026-03-01,,,,VENDOR,PA,매출 성장,2,캠페인B,Adcost,DAILY_SOFT,1000,20,0,20,0,20,,",
"2026-03-01,RETAIL,Taxable,,,,,,,,,,30,0,30,30,30,3,33", # 값 있는 줄
"2026-03-01,RETAIL,Tax-free,,,,,,,,,,5,0,5,5,5,0,5", # 같은 날 값 한 줄 더 → 더함
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 값 없는 날
"2026-03-03,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,1,100", # 19열 = 1 (20열은 무시)
]) + "\n"
for content, name in ((wing.encode("utf-8"), "w.csv"), (_xlsx(wing), "w.xlsx")):
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
assert not res.errors, res.errors
assert res.entries == [(date(2026, 3, 1), 38), (date(2026, 3, 3), 1)]
assert res.empty_days == [date(2026, 3, 2)]
# 청구금액이 한 줄도 없는 파일(날짜 줄만) — 오류 없이 넘어감(반영할 날 없음)
none = "\n".join([head, "2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,",
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,"]) + "\n"
r0 = ads.parse_coupang_rocket(_xlsx(none), today=TODAY, filename="march.xlsx")
assert r0.entries == [] and not r0.errors and r0.empty_days == [date(2026, 3, 1), date(2026, 3, 2)]
m, _ = ads.merge_results([("a.xlsx", 1.0, ads.parse_coupang_rocket(wing.encode("utf-8"), today=TODAY)),
("b.csv", 2.0, ads.ParseResult(entries=[(date(2026, 3, 2), 7)]))])
assert m.empty_days == [] and dict(m.entries)[date(2026, 3, 2)] == 7 # 다른 파일에 값이 있으면 빈 날 아님
def test_rocket_report_wrong_file():
with pytest.raises(UploadError):
ads.parse_coupang_rocket(b"", today=TODAY)
with pytest.raises(UploadError): # 날짜 줄이 하나도 없음
ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY)
other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류
assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0]
with pytest.raises(UploadError):
ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx")
class _Store:
def __init__(self, missing=False):
self.missing = missing
def ad_amounts(self, start, end):
if self.missing:
raise ads.AdMigrationNeeded()
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"),
(date(2026, 10, 2), "google"): (50000, "manual"),
(date(2026, 9, 1), "meta"): (100000, "manual")}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
def daily_amounts(self, start, end, codes):
rows = {(date(2026, 10, 5), "cafe24"): 2_700_000, (date(2026, 10, 1), "coupang_rocket"): 550_000,
(date(2026, 10, 3), "coupang_rocket"): 110_000}
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
def test_ad_dashboard_month():
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24"])
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
k = {x["key"]: x for x in ctx["kpis"]}
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
assert ctx["api_cells"] == []
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
assert ctx["table"][0]["kind"] == "total" and ctx["table"][0]["total"]["gross"] == 270000 # 기간 합계 = 맨 위
# ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0%
assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None
day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02")
assert day2["roas"]["google"] is None # 구글·메타는 ROAS 계산 안 함(따로 입력)
total = ctx["table"][0]
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] is None # 660,000÷220,000
assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes)
m = {r["code"]: r for r in ctx["month"]["rows"]}
assert m["coupang_rocket"]["roas"] == 300 and m["naver"]["roas"] is None and ctx["month"]["total"]["roas"] == 1000
assert ctx["year"]["rows"][9]["roas"] == 1000 and ctx["year"]["rows"][10]["roas"] is None # 11월 = 앞으로
assert ctx["roas_basis"]["google"] == "" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
assert {r["code"]: r for r in ctx["month"]["rows"]}["google"]["roas"] is None
assert ads.roas(1, 3) == 33 and ads.roas(1, 200) == 1 and ads.roas(5, 0) is None # 0.5% 반올림 → 1
assert ctx["nav"]["quick"][2]["active"] # 이번달
def test_ad_dashboard_year_and_missing_table():
ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
rows = {r["label"]: r for r in ctx["table"]}
assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000
assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음
miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0
def test_ad_spend_endpoints(monkeypatch):
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
칸 저장(source=manual)·지우기·계산식, 모르는 채널 404, 앞으로의 날도 됨, 005 미적용 503."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class Store:
def __init__(self):
self.saved, self.missing = [], False
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
self.report = (roas, metrics)
if self.missing:
raise ads.AdMigrationNeeded()
self.saved.extend((code, d, a, source) for d, a in entries)
return len(entries)
def set_ad_spend(self, code, day, amount, *, source="manual", user="", formula=None):
self.formula = formula
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
store = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200, r.text
assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12"
assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload")
store.saved.clear()
r = client.post("/performance/api/ad-spend/upload?channel=coupang_wing", files={"file": ("w.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200 and r.json()["name"] == "쿠팡(윙)" # 윙도 같은 양식
assert store.saved[0] == ("coupang_wing", date(2026, 10, 1), 220000, "upload") and len(store.saved) == 3
store.saved.clear()
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n"
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))})
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")})
assert r.status_code == 400 and "양식" in r.json()["detail"]
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000
assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200
assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")]
assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404
assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 200 # 앞날도 됨
store.saved.clear()
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "(10000+5000)×2"})
assert r.json()["amount"] == 30000 and r.json()["formula"] == "(10000+5000)*2" and store.formula == "(10000+5000)*2"
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400
store.missing = True
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1})
assert r.status_code == 503 and "005" in r.json()["detail"]
# 사용자 제공 네이버 광고 보고서(2026-10-14) — 앞 9줄 + 머리글
NAVER_CSV = """광고 계정 이름,광고 계정 ID,기간,총비용,노출수,클릭수,클릭률(%),총 전환수,구매완료 수,장바구니 담기 수,총 전환매출액,구매완료 광고수익률(%)
0_미라네주방,38461,2026.09.30.,0,0,0,0.00,46,6,40,8218000,0.00
0_미라네주방,38461,2026.09.24.,0,0,0,0.00,36,6,30,6331500,0.00
0_미라네주방,38461,2026.09.23.,300672,30043,461,1.53,71,13,58,7830100,67.58
0_미라네주방,38461,2026.09.22.,299817,31061,441,1.42,125,20,105,15040200,198.79
0_미라네주방,38461,2026.09.21.,299199,25641,416,1.62,159,44,115,19878020,501.11
"""
def test_naver_report_reads_date_cost_roas_and_metrics():
for content, name in ((NAVER_CSV.encode("utf-8-sig"), "n.csv"), (NAVER_CSV.encode("cp949"), "n.csv"), (_xlsx(NAVER_CSV), "n.xlsx")):
res = ads.parse_naver(content, today=TODAY, filename=name)
assert not res.errors, res.errors
assert res.entries[:3] == [(date(2026, 9, 30), 0), (date(2026, 9, 24), 0), (date(2026, 9, 23), 300672)]
assert str(res.roas[date(2026, 9, 23)]) == "67.58" and res.roas[date(2026, 9, 30)] == 0
m = res.metrics[date(2026, 9, 21)]
assert m["노출수"] == 25641 and m["클릭률(%)"] == 1.62 and m["총 전환매출액"] == 19878020
assert m["구매완료 광고수익률(%)"] == 501.11 and "광고 계정 이름" not in m and "기간" not in m
assert res.columns[0] == "총비용" and res.columns[-1] == "구매완료 광고수익률(%)"
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n"
errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors)
assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" not in errs
def test_naver_report_finds_columns_by_header():
"""열 구성을 바꾼 보고서 — 총비용·광고수익률이 4열·12열이 아니어도 머리글로 찾는다(2026-10-20: 12열이 비어 ROAS 누락)."""
csv_text = ("광고 계정 이름,광고 계정 ID,기간,노출수,클릭수,총비용,구매완료 광고수익률(%),구매완료 전환매출액\n"
"0_미라네주방,38461,2026.09.23.,30043,461,300672,67.58,203194\n")
res = ads.parse_naver(csv_text.encode("utf-8"), today=TODAY, filename="n.csv")
assert not res.errors, res.errors
assert res.entries == [(date(2026, 9, 23), 300672)] and str(res.roas[date(2026, 9, 23)]) == "67.58"
def test_naver_report_without_roas_column_computes_from_purchase_revenue():
csv_text = ("광고 계정 이름,광고 계정 ID,기간,총비용,노출수,구매완료 전환매출액,총 전환매출액\n"
"0_미라네주방,38461,2026.09.22.,299817,31061,596016,15040200\n"
"0_미라네주방,38461,2026.09.24.,0,0,0,6331500\n")
res = ads.parse_naver(csv_text.encode("utf-8"), today=TODAY, filename="n.csv")
assert not res.errors, res.errors
assert str(res.roas[date(2026, 9, 22)]) == "198.79" # 596,016 ÷ 299,817 × 100 (총 전환매출액은 안 씀)
assert date(2026, 9, 24) not in res.roas # 광고비 0 — 계산 안 함
def test_roas_from_metrics_for_stored_rows():
assert ads.roas_from_metrics({"구매완료 광고수익률(%)": 501.11}, 299199) == Decimal("501.11")
assert ads.roas_from_metrics({"구매완료 광고수익률(%)": None, "구매완료 전환매출액": 600000}, 300000) == Decimal("200.00")
assert ads.roas_from_metrics({"총 전환매출액": 600000}, 300000) is None
assert ads.roas_from_metrics(None, 1) is None and ads.roas_from_metrics({"구매완료 전환매출액": 5}, 0) is None
def test_naver_roas_from_report_weighted():
"""네이버 칸 ROAS = 보고서 값(계산 안 함), 여러 날 = Σ(ROAS×광고비)÷Σ광고비, 광고비 0 인 날은 빼고."""
class S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 9, 22), "naver"): 299817, (date(2026, 9, 23), "naver"): 300672,
(date(2026, 9, 24), "naver"): 0}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "upload" for k in rows}
def ad_roas(self, start, end):
rows = {(date(2026, 9, 22), "naver"): Decimal("198.79"), (date(2026, 9, 23), "naver"): Decimal("67.58"),
(date(2026, 9, 24), "naver"): Decimal("0")}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def daily_amounts(self, start, end, codes):
return {(date(2026, 9, 22), "naver"): 9_999_999} if "naver" in codes else {}
ctx = ads.build_ad_dashboard(S(), kind="week", anchor=date(2026, 9, 23), today=TODAY, sales_codes=["naver"])
by = {r.get("date"): r for r in ctx["table"]}
assert by["2026-09-22"]["roas"]["naver"] == 199 and by["2026-09-23"]["roas"]["naver"] == 68
assert by["2026-09-24"]["roas"]["naver"] is None # 광고비 0
week = next(r for r in ctx["table"] if r["kind"] == "week")
want = round((Decimal("198.79") * 299817 + Decimal("67.58") * 300672) / (299817 + 300672))
assert week["roas"]["naver"] == want == 133 # 매출 실적(9,999,999)으로 계산하지 않음
assert ctx["roas_basis"]["naver"] == ""
assert {r["code"]: r for r in ctx["month"]["rows"]}["naver"]["roas"] == 133
def test_naver_detail_table_totals():
rows = [{"date": "2026-09-22", "amount": 299817, "roas": Decimal("198.79"),
"metrics": {"총비용": 299817, "노출수": 31061, "클릭수": 441, "클릭률(%)": 1.42, "구매완료 광고수익률(%)": 198.79}},
{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"),
"metrics": {"총비용": 300672, "노출수": 30043, "클릭수": 461, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 67.58}},
{"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0,
"클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}]
t = ads.detail_table(rows)
# ROAS(12열)는 광고비(총비용) 바로 오른쪽, 머리글은 "ROAS(%)"(값 키는 파일 머리글 그대로)
assert t["columns"] == ["총비용", "구매완료 광고수익률(%)", "노출수", "클릭수", "클릭률(%)"]
assert t["labels"] == {"구매완료 광고수익률(%)": "ROAS(%)"}
assert t["total"]["총비용"] == 600489 and t["total"]["노출수"] == 61104 and t["total"]["클릭수"] == 902
assert t["total"]["클릭률(%)"] == round(902 * 100 / 61104, 2) # 가중: 클릭수 ÷ 노출수
assert t["total"]["구매완료 광고수익률(%)"] == 133.09 # 광고비 가중 평균 (198.79×299,817 + 67.58×300,672) ÷ 600,489
assert t["rows"][0]["values"]["노출수"] == 31061 and t["rows"][1]["roas"] == 67.58
def test_naver_upload_and_details_endpoints(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class Store:
def __init__(self):
self.saved, self.kw, self.missing = [], {}, ""
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
if self.missing:
raise ads.AdMigrationNeeded(self.missing)
self.saved.extend((code, d, a, source) for d, a in entries)
self.kw = {"roas": roas, "metrics": metrics}
return len(entries)
def ad_details(self, code, start, end):
if self.missing:
raise ads.AdMigrationNeeded(self.missing)
return [{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), "metrics": {"노출수": 30043}}]
store = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8-sig"))})
assert r.status_code == 200, r.text
assert r.json()["saved"] == 5 and r.json()["total"] == 300672 + 299817 + 299199
assert store.saved[2] == ("naver", date(2026, 9, 23), 300672, "upload")
assert str(store.kw["roas"][date(2026, 9, 23)]) == "67.58" and store.kw["metrics"][date(2026, 9, 21)]["클릭수"] == 416
store.saved.clear()
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
assert r.status_code == 200 and store.kw == {"roas": None, "metrics": None} # 쿠팡은 금액만
d = client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()
assert d["name"] == "네이버" and d["columns"] == ["노출수"] and d["rows"][0]["roas"] == 67.58
assert client.get("/performance/api/ad-spend/coupang_rocket/details?from=2026-09-01&to=2026-09-30").status_code == 400
assert client.get("/performance/api/ad-spend/naver/details?from=2026-09-30&to=2026-09-01").status_code == 400
store.missing = "006"
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8"))})
assert r.status_code == 503 and "006" in r.json()["detail"]
assert "006" in client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()["detail"]
def test_merge_results_newest_file_wins():
"""여러 파일 — 같은 날짜는 파일 날짜(수정 시각)가 최신인 파일 값, 같으면 나중 파일. ROAS·상세도 그 파일 것."""
a = ads.ParseResult(entries=[(date(2026, 9, 1), 100), (date(2026, 9, 2), 200)],
roas={date(2026, 9, 2): Decimal("10")}, metrics={date(2026, 9, 2): {"노출수": 1}}, columns=["노출수"])
b = ads.ParseResult(entries=[(date(2026, 9, 2), 999), (date(2026, 9, 3), 300)],
roas={date(2026, 9, 2): Decimal("99")}, metrics={date(2026, 9, 2): {"노출수": 9}}, columns=["노출수", "클릭수"])
m, overlap = ads.merge_results([("new.csv", 2000.0, a), ("old.csv", 1000.0, b)]) # a 가 최신
assert m.entries == [(date(2026, 9, 1), 100), (date(2026, 9, 2), 200), (date(2026, 9, 3), 300)]
assert m.roas[date(2026, 9, 2)] == Decimal("10") and m.metrics[date(2026, 9, 2)] == {"노출수": 1}
assert overlap == [date(2026, 9, 2)] and m.columns == ["노출수", "클릭수"]
m2, _ = ads.merge_results([("a.csv", 1000.0, a), ("b.csv", 1000.0, b)]) # 같은 시각 → 나중 파일
assert dict(m2.entries)[date(2026, 9, 2)] == 999
bad = ads.ParseResult(errors=["3행: 오류"])
m3, _ = ads.merge_results([("a.csv", 1.0, a), ("bad.csv", 2.0, bad)])
assert m3.errors == ["[bad.csv] 3행: 오류"]
def test_upload_multiple_files_endpoint(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class Store:
saved: list = []
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
self.saved = list(entries)
self.roas = roas
return len(entries)
store = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
old = NAVER_CSV
new = NAVER_CSV.replace("2026.09.23.,300672", "2026.09.23.,111111").replace(",67.58", ",12.34")
files = [("files", ("new.csv", new.encode("utf-8"))), ("files", ("old.csv", old.encode("utf-8")))]
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["2000", "1000"]})
assert r.status_code == 200, r.text
body = r.json()
assert body["files"] == 2 and body["overlap_days"] == 5 and body["saved"] == 5
assert dict(store.saved)[date(2026, 9, 23)] == 111111 and str(store.roas[date(2026, 9, 23)]) == "12.34" # 최신 파일
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["1000", "2000"]})
assert dict(store.saved)[date(2026, 9, 23)] == 300672 # 이번엔 old 가 최신
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
r = client.post("/performance/api/ad-spend/upload?channel=naver",
files=[("files", ("ok.csv", old.encode("utf-8"))), ("files", ("bad.csv", bad.encode("utf-8")))])
assert r.status_code == 400 and r.json()["errors"][0].startswith("[bad.csv]")
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("one.csv", old.encode("utf-8"))})
assert r.status_code == 200 and r.json()["files"] == 1 # 예전 file 한 개도
assert client.post("/performance/api/ad-spend/upload?channel=naver").status_code in (400, 422)
@@ -0,0 +1,127 @@
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
from __future__ import annotations
from datetime import date, datetime, timedelta, timezone
from app.modules.performance import auto_sync as au
KST = timezone(timedelta(hours=9))
H = (9, 19)
def _t(h, m, d=13):
return datetime(2026, 10, d, h, m, tzinfo=KST)
def test_slots_every_half_hour_9_to_19():
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
def test_next_slot():
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
def test_env_parsing(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
assert au.hour_window() == (8, 20)
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
from app.modules.performance import jobs
from app.modules.performance.sync import SyncService
calls = []
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
calls.append((start, end, trigger, user, job is not None))
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
class Store:
def last_update_at(self):
return "2026-10-13T09:00:05+09:00"
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
assert res == {"skipped": False, "sales_skipped": False, "ads_skipped": False, "from": "2026-10-04",
"to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "", "ads": []}
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object())
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
assert len(calls) == 1
# 광고비 업데이트만 돌고 있으면 매출은 그 회차에 그대로 돈다(종류별로 따로)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": object() if kind == "ads" else None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
assert res["ads_skipped"] and not res["sales_skipped"] and len(calls) == 2
def test_run_once_runs_ads_as_progress_job(monkeypatch):
"""자동 회차의 광고비 = 광고비 진행 창 작업(kind=ads) — 채널별 진행·마지막 업데이트 시각."""
from app.modules.performance import ad_sync, jobs
from app.modules.performance.sync import SyncService
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: [])
seen = {}
def fake_all(self, start, end, *, user="", job=None):
seen["job"] = job
return [{"code": "google", "ok": True, "days": 10, "total": 1000}]
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", fake_all)
class Store:
def last_update_at(self):
return None
def ad_source_statuses(self):
return {"google": {"last_success_sync_at": "2026-10-13T09:00:07+09:00"},
"meta": {"last_success_sync_at": "2026-10-13T08:30:02+09:00"}}
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
job = seen["job"]
assert job.kind == "ads" and job.finished and job.last_update_at == "2026-10-13T09:00:07+09:00"
assert res["ads"] == [{"code": "google", "ok": True}] and jobs.running_job("ads") is None
def test_startup_clears_orphan_running_runs(monkeypatch):
"""서버 시작 때 지난 프로세스가 남긴 '진행 중' 기록을 정리(2026-10-19) — 자동 업데이트를 꺼 둬도, DB 오류여도 앱은 뜬다."""
from types import SimpleNamespace
from app.modules.performance import auto_sync as a
calls = []
class Store:
def abandon_running_runs(self):
calls.append(1)
return 2
monkeypatch.setattr(a, "_started", False)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Store())) is False
assert calls == [1]
class Broken:
def abandon_running_runs(self):
raise RuntimeError("db down")
assert a.start_auto_sync_thread(SimpleNamespace(performance_store=Broken())) is False # 예외가 새지 않음
@@ -0,0 +1,91 @@
"""쿠팡 발주서 — 504(시간 초과)면 조회 구간을 반으로 줄여 다시 부른다."""
from __future__ import annotations
from datetime import date, timedelta
import pytest
from app.modules.performance.adapters import coupang as cp
from app.modules.performance.adapters.base import AdapterContext, ApiError
class Creds:
def get(self, key):
return {"vendor_id": "A001", "access_key": "ak", "secret_key": "sk"}[key]
def has(self, key):
return True
def _ctx():
return AdapterContext(code="coupang", credentials=Creds())
def _days(params):
a = date.fromisoformat(params["createdAtFrom"][:10])
b = date.fromisoformat(params["createdAtTo"][:10])
return a, b
def test_seller_window_halves_on_timeout_and_remembers(monkeypatch):
calls = []
def fake_pages(self, ctx, path, params, *, rg=False):
a, b = _days(params)
calls.append((params["status"], a, b))
if params["status"] == "FINAL_DELIVERY" and (b - a).days + 1 > 7:
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
return [{"orderId": f"{params['status']}-{a}-{b}"}]
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
ad = cp.CoupangAdapter()
start, end = date(2026, 1, 1), date(2026, 3, 31) # 주문일 2025-12-31 ~ 3-31 = 91일 → 31일 구간 3개
ad._seller_orders(_ctx(), start, end)
fd = [(a, b) for st, a, b in calls if st == "FINAL_DELIVERY"]
ok = [(a, b) for a, b in fd if (b - a).days + 1 <= 7]
# 성공한 구간이 빈틈·겹침 없이 전체 주문일을 덮는다
d = start - timedelta(days=1)
for a, b in ok:
assert a == d
d = b + timedelta(days=1)
assert d == end + timedelta(days=1)
# 31 → 15 → 7 로 줄인 뒤엔 다음 31일 구간도 처음부터 7일로(실패는 첫 구간의 두 번뿐)
assert len(fd) - len(ok) == 2
# 다른 상태는 31일 그대로
assert sum(1 for st, a, b in calls if st == "ACCEPT") == 3
def test_one_day_timeout_retries_then_fails(monkeypatch):
sleeps = []
monkeypatch.setattr(cp.time, "sleep", lambda s: sleeps.append(s))
def fake_pages(self, ctx, path, params, *, rg=False):
if params["status"] == "FINAL_DELIVERY":
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
return []
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
with pytest.raises(ApiError) as ei:
cp.CoupangAdapter()._seller_orders(_ctx(), date(2026, 1, 5), date(2026, 1, 5))
assert "하루도 시간 초과" in ei.value.message and "FINAL_DELIVERY" in ei.value.message
assert sleeps == [3.0, 6.0]
def test_rg_window_halves_on_timeout(monkeypatch):
got = []
def fake_pages(self, ctx, path, params, *, rg=False):
a = date(int(params["paidDateFrom"][:4]), int(params["paidDateFrom"][4:6]), int(params["paidDateFrom"][6:]))
b = date(int(params["paidDateTo"][:4]), int(params["paidDateTo"][4:6]), int(params["paidDateTo"][6:]))
if (b - a).days + 1 > 10:
raise cp.GatewayTimeout("쿠팡 로켓그로스 주문 API 오류(504)")
got.append((a, b))
return [{"orderId": str(a)}]
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
cp.CoupangAdapter()._rg_orders(_ctx(), date(2026, 1, 1), date(2026, 1, 30))
assert got[0][0] == date(2026, 1, 1) and got[-1][1] == date(2026, 1, 30)
assert all((b - a).days + 1 <= 10 for a, b in got)
assert all(got[i + 1][0] == got[i][1] + timedelta(days=1) for i in range(len(got) - 1))
@@ -0,0 +1,200 @@
"""매출 실적 화면 — 매출 칸 아래 광고비(ROAS%)·매출 단위(원·천원·백만원) (2026-10-19)."""
from __future__ import annotations
from datetime import date
from app.modules.performance import dashboard
TODAY = date(2026, 10, 7)
class _Store:
"""build_dashboard 가 읽는 것만 — 카페24·네이버·쿠팡 매출 + 구글·메타·네이버·쿠팡(윙) 광고비."""
def __init__(self, ads_missing=False):
self.ads_missing = ads_missing
def list_marketplaces(self):
return [{"code": c, "name": n, "enabled": True, "include_in_sales": True}
for c, n in (("cafe24", "카페24"), ("naver", "네이버 스마트스토어"), ("coupang", "쿠팡"))]
def daily_amounts(self, start, end, codes):
rows = {(date(2026, 10, 5), "cafe24"): 2_000_000, (date(2026, 10, 5), "coupang"): 600_000,
(date(2026, 10, 6), "naver"): 1_234_567}
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
def rate_table(self):
return {}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
if self.ads_missing:
raise RuntimeError("perf_ad_spend 없음")
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "meta"): 50_000,
(date(2026, 10, 5), "coupang_wing"): 200_000, (date(2026, 10, 6), "naver"): 300_000}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def ad_roas(self, start, end):
rows = {(date(2026, 10, 5), "google"): 412.5, (date(2026, 10, 6), "naver"): 150}
return {k: v for k, v in rows.items() if start <= k[0] <= end}
def test_sales_ad_channels_mapping():
m = dashboard.sales_ad_channels()
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"))
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
def test_ad_lines_under_sales_cells():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
# 카페24 = 구글·메타 두 줄, ROAS 는 광고 보고서 값(구글 412.5 → 413), 메타는 보고서 ROAS 없음
assert day5["ads"]["cafe24"] == [{"label": "구글", "amount": 100_000, "roas": 413},
{"label": "메타", "amount": 50_000, "roas": None}]
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 일 합계 금액 ÷ 일 합계 광고비(총매출·수수료 차감 매출 두 기준, 2026-10-19)
assert day5["ads_total"] == {"amount": 350_000, "roas": 743, "roas_net": 743} # 2,600,000 ÷ 350,000(수수료율 없음)
day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06")
assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}]
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert [a["amount"] for a in week["ads"]["cafe24"]] == [100_000, 50_000] and week["ads_total"]["amount"] == 650_000
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-07")
assert day1["ads"] == {} and day1["ads_total"] is None
def test_ad_lines_follow_shop_filter_and_missing_table():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"])
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300, "roas_net": 300}
ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY)
assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로
def test_amount_text_units():
assert dashboard.amount_text(2_475_300) == "2,475,300"
assert dashboard.amount_text(2_475_300, "thousand") == "2,475"
assert dashboard.amount_text(2_475_500, "thousand") == "2,476"
assert dashboard.amount_text(2_475_300, "million") == "2.5"
assert dashboard.amount_text(158_000, "million") == "0.2"
assert dashboard.amount_text(-158_000, "thousand") == "-158"
assert dashboard.amount_text(1_234_567_890, "million") == "1,234.6"
assert dashboard.amount_text(5, "nope") == "5" and dashboard.normalize_unit("x") == "won"
def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class _Creds:
def configured_codes(self, adapters):
return {}
store = _Store()
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True}))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
html = client.get("/performance/?period=week&d=2026-10-07").text
assert "2,000,000" in html
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
client.cookies.set("perf_unit", "thousand")
html = client.get("/performance/?period=week&d=2026-10-07").text
assert "단위: 천원" in html and "2,000<" in html and "<i>구글</i>100<em>(413%)</em>" in html
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
client.cookies.set("perf_unit", "million")
html = client.get("/performance/?period=week&d=2026-10-07").text
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
def test_total_roas_uses_whole_day_total():
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
class _S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 5), "google"): 100_000}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def ad_roas(self, start, end):
return {}
ctx = dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["total"]["gross"] == 2_600_000 # 카페24 2,000,000 + 쿠팡 600,000(광고비 없음)
assert day5["ads_total"] == {"amount": 100_000, "roas": 2600, "roas_net": 2600}
def test_kpi_is_net_only():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
assert [k["key"] for k in ctx["kpis"]] == ["net"]
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
"""2026-10-21 — 계산식 칸(is-formula·data-formula), 오늘 뒤 날짜도 입력 칸, 이번달 기간 합계 = 제목 행 바로 아래."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
class _S(_Store):
def list_marketplaces(self):
return [{**m, "manual_input": m["code"] == "coupang"} for m in super().list_marketplaces()]
def manual_amounts(self, start, end, codes, *, active_only=True):
return {(date(2026, 10, 5), "coupang"): 600_000}
def manual_formulas(self, start, end, codes):
return {(date(2026, 10, 5), "coupang"): "500000+100000"}
def ad_formulas(self, start, end):
return {(date(2026, 10, 5), "meta"): "20000+30000"}
class _Creds:
def configured_codes(self, adapters):
return {}
store = _S()
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True}))
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
for url, code, fx in (("/performance/?period=month&d=2026-10-07", "coupang", "500000+100000"),
("/performance/ads?period=month&d=2026-10-07", "meta", "20000+30000")):
r = client.get(url)
assert r.status_code == 200, r.text
body = r.text.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
assert body.lstrip().startswith('<tr class="perf-row-total') and "기간 합계" in body.split("</tr>", 1)[0]
cell = body.split(f'data-manual-code="{code}" data-date="2026-10-05"', 1)
assert len(cell) == 2 and "is-formula" in cell[0].rsplit("<td", 1)[1] and f'data-formula="{fx}"' in cell[1].split(">", 1)[0]
assert f'data-manual-code="{code}" data-date="2026-10-20"' in body # 오늘(10/7) 뒤 날짜도 입력 칸

Some files were not shown because too many files have changed in this diff Show More