201 Commits

Author SHA1 Message Date
king 4171d61db1 feat(카페24): 소스 편집기 이미지 파일명 번호 단축키
img 태그 안에서 커서 바로 뒤가 .jpg/.gif/.png 일 때 Ctrl+위/아래로
파일명 번호를 바꾼다(없음 → _2 → _3 …, 내리면 _2 다음은 원래 이름).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:24:18 +09:00
king 677bf8f1d1 Merge branch 'feat/live-lang-toggle' 2026-11-04 17:35:24 +09:00
king 15dcabc538 feat(라이브커머스): 한글·영문 전환 버튼과 메인 카드 제목 표기
스케줄표·달력·호스트 설정 위에 한글/EN 버튼을 두고 화면·창·오류·확인
문구를 모두 전환한다(쿠키 live_lang, 브라우저마다 기억). 메인 카드 제목은
"라이브 커머스 · Live Commerce"로 표기한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 17:35:16 +09:00
king 25c885d5dd Merge branch 'feat/live-calendar' 2026-11-04 16:58:12 +09:00
king 61f5b3c320 feat(라이브커머스): 달력 보기와 호스트 비용 계산 추가
2시간 칸 × 날짜 달력(카드 머리 = Tiktok Handle, SALES·COM·Fee), 끌어 옮기기·
맞바꾸기, Jump to Date, 날짜별 합계·광고비·ROAS 를 넣는다.
호스트 비용 = 시간 × RM 25 + 판매금액 10%, 표 보기에도 표시한다.
끝 시간을 필수로 바꾸고 광고비 표는 마이그레이션 002 로 추가한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:58:07 +09:00
king 5d55081464 Merge branch 'feat/live-commerce-module' 2026-11-04 16:41:42 +09:00
king f54f19fa45 feat(라이브커머스): 라이브 커머스 모듈 추가
말레이시아 라이브 방송의 호스트 정보와 방송 스케줄을 관리하는 새 모듈.
호스트 설정(이름·연락처·주소·계좌·틱톡)은 ERP 관리자만 다루고,
스케줄표에서 등록된 호스트를 골라 날짜·시간·장소·판매금액(RM)·결과
이미지를 저장한다. 권한키 live, DB live_db(LIVE_DB_URL), 미설정이면
설정 필요 안내만 표시한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:41:37 +09:00
king 876d9758bd Merge branch 'feat/inout-simple-order-mail' 2026-11-04 15:43:39 +09:00
king 0ba6192e95 feat(입출고): 대성화학·인천공장 발주 메일 표를 간단하게
공장 이름에 대성화학·인천공장이 들어가면 품목 표를 번호·제품 코드·
제품명·수량·박스당 수량·박스 수·비고로 만들고, 요약 표와 글 본문에서도
금액·무게·PP·은을 뺀다. 박스 값은 메일을 만들 때의 상품 정보로 계산한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:43:19 +09:00
king dd5010019d Merge branch 'feat/inout-bag-pallet-picture' 2026-11-04 15:35:00 +09:00
king 57745e114e feat(입출고): 봉투·백 합계 줄에 파렛트 그림 표시
새 발주서 합계 줄의 봉투·백도 통처럼 파렛트 그림으로 보여 주고,
"통·뚜껑과 따로 셈" 글자를 뺀다. 1파렛트 박스 수가 다른 상품이 섞이면
가장 큰 값으로 환산해 잔량은 %만 표시하고, 그림은 60칸까지만 그린다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:34:54 +09:00
king 307a0c31b1 Merge branch 'feat/inout-bag-no-price-columns' 2026-11-04 15:29:30 +09:00
king cfb6878bea feat(입출고): 봉투·백 표에서 단가·무게·은 열 제거
봉투·백에는 단가·무게·은이 없어 표에서 네 열을 뺀다. 전에 넣은 값은
숨은 칸으로 저장 때 그대로 보내 지우지 않는다.
새 발주서·발주서 화면·발주 메일의 단가 미입력 안내에서도 봉투·백을 뺀다.
은 칸이 없는 줄에서 그룹을 바꿔도 색상 표시가 덮이지 않게 고친다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:29:20 +09:00
king b0f559907f Merge branch 'feat/inout-bag-pallet' 2026-11-04 15:17:53 +09:00
king b6c8173899 feat(입출고): 미라클 봉투·미라클백 상품을 표로 분리하고 파렛트 입력 추가
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 옵션 → 상품 정보에서
별도 표로 나누고 박스당 수량·1파렛트당 박스 수량을 입력한다.
새 발주서 합계 줄에 봉투·백 박스·파렛트를 통·뚜껑과 따로 표시한다.
마이그레이션 008 필요, 미적용이면 모두 일반 상품으로 동작한다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:17:47 +09:00
king d0e3e3622b Merge branch 'feat/inout-list-status-per-user' 2026-11-04 11:27:07 +09:00
king 6055d50dbe feat(입출고): 발주 목록 상태 보기를 사람마다 기억
진행 중·완료·종결·취소·전체 중 고른 보기를 다음 접속에도 유지한다.
inout_settings 에 list_status:{이메일} 키로 저장해 마이그레이션은 없고,
005 미적용이면 기억만 하지 않는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:27:01 +09:00
king 321041b65a Merge branch 'feat/cafe24-img-preview-name' 2026-11-03 15:38:54 +09:00
king faed6581fd feat(카페24): 이미지 미리보기 시 태그 오렌지 표시·레이어 상단 파일명
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:38:54 +09:00
king 6b04b7ab6e Merge branch 'fix/cafe24-img-preview-width' 2026-11-03 15:33:07 +09:00
king a85d562fa7 fix(카페24): 이미지 미리보기 레이어 폭 500px 고정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:33:07 +09:00
king 889522d935 Merge branch 'feat/cafe24-img-hover-preview' 2026-11-03 15:29:56 +09:00
king 5e5586a25c feat(카페24): 상세 소스의 img 태그 hover 시 오른쪽에 이미지 미리보기
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:29:55 +09:00
king 5cf1a33e98 Merge branch 'fix/vacation-mail-gmail-retry'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:26:13 +09:00
king f4b80e8abc fix(휴가): 메일 실패 시 Gmail 연결 안내·다시 보내기 — 휴가 권한 없는 협의자 포함
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:26:13 +09:00
king 7e86e9c91b Merge branch 'fix/vacation-holiday-name-size'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:52:50 +09:00
king 4ecde312f9 fix(휴가): 신청 달력 공휴일 이름 크게(9→10.5px), 달력 폭 380px
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:52:49 +09:00
king 0c17b02468 Merge branch 'feat/vacation-consult-photo-rotate'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:46:25 +09:00
king 97f4a904cd feat(휴가): 협의자 결재·신청 화면 개편(라디오·붙박이 달력·결재 라인)·내 신청 내역
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:46:19 +09:00
king f7a3afcebf feat(입출고): 입고증 사진 왼쪽·오른쪽 회전 — 돌린 상태로 저장
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:46:18 +09:00
king b3001c3051 fix(실적): 수기 입력 뒤 새로고침해도 스크롤 위치 유지
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:46:17 +09:00
king 443fa56671 Merge branch 'feat/perf-cafe24-real' 2026-11-02 12:21:35 +09:00
king 884e654bea feat(실적): 카페24(실적) 열·합계 기준 통일·공통 보기 설정·일 합계 고정
매출 실적
- "카페24" 열 → "카페24(전체)", 바로 오른쪽 "카페24(실적)" = 전체 − 자사몰(공동구매),
  광고비 줄은 카페24(전체)의 구글·메타 그대로 (예전 "공구 제외" 열 대체)
- 합계 기준 통일: 일 합계·ROAS·KPI·추이·비중·월/연 누적 = 카페24(실적) + 공동구매 + 나머지
  (카페24(전체)에 공동구매가 들어 있어 이중 합산 제거, 그래프·누적의 카페24 줄 = 카페24(실적))
- 실적 설정 "공통 보기 설정"(관리자, perf_settings, 모든 사용자 적용):
  매출 단위(예전 브라우저 쿠키 perf_unit 대체), 표 열 숨기기(열만, 합계 그대로)
  표 열 너비는 사람(브라우저)마다 그대로

매출 실적·광고비 공통
- 일 합계 열을 날짜 오른쪽으로, 날짜와 함께 가로 고정
- 이전달·다음달 = 날짜 바로 옆 진한 회색 화살표 SVG(글자 높이)
- 광고비 탭 매출 대비 광고비·합계 ROAS 도 공동구매 이중 합산 제거

CSS·JS 캐시 버전 20261102a. 새 마이그레이션 없음(011 perf_settings 사용).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:21:33 +09:00
king ff3b36bf77 Merge branch 'feat/outreach-dm-bodies' 2026-10-30 16:51:12 +09:00
king 48cd7f0878 feat(안내문 발송): DM 수동 보내기 — 이름 지우기·본문 편집·저장한 본문 목록
- 이름 목록: × 한 명씩 빼기·[전체 삭제], 이름 넣기는 목록에 더함
- 본문: 바로 고침(plaintext-only), {이름} 자리 = 분홍 칩, 이름 누르면 고친 글 + 이름 복사
- 저장한 본문(본문 오른쪽): 설정 DM 문구 + 저장한 것, 고르기·[저장]·[새 본문으로 저장]·× 지우기
- outreach_db 마이그레이션 002 outreach_dm_bodies + POST/PUT/DELETE /outreach/api/dm-bodies
  (002 미적용이면 목록 안내만, API 503)
- 캐시 버전 20261030c, 단위·API·실제 PG·브라우저 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:51:10 +09:00
king 456dfe376f Merge branch 'feat/outreach-dm-tab' 2026-10-30 16:38:24 +09:00
king 64e19e8c3e feat(안내문 발송): DM 수동 보내기를 별도 탭(/outreach/dm)으로
- 탭 [발송 리스트] [DM 수동 보내기] + 맨 오른쪽 설정 톱니(_tabs.html)
- /outreach/dm: 왼쪽 이름 넣기·이름 목록, 오른쪽 본문 — 이름 누르면 {이름} 바뀌고 복사 + 짧은 안내
- 리스트 화면의 DM 수동 버튼·창은 뺌
- outreach.js/css 캐시 버전 20261030b, 화면·브라우저 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:38:23 +09:00
king 6543ce3f0f Merge branch 'feat/outreach-dm-manual' 2026-10-30 16:28:49 +09:00
king 3a43f699f5 feat(안내문 발송): DM 수동 보내기 + 설정 톱니 아이콘
- [+ 리스트 추가] 오른쪽 [DM 수동 보내기]: 이름 붙여 넣기·.txt/.csv → 왼쪽 이름 목록,
  누르면 오른쪽 DM 문구 {이름} 이 그 이름으로 바뀌고 클립보드 복사 + 짧은 안내
  (문구 = 설정 DM 문구, 리스트에 저장 안 함)
- 설정 버튼 → 맨 오른쪽 톱니 아이콘(공용 material-symbols)
- 공용 .erp-card display:flex 가 hidden 을 덮어 [리스트 추가] 창이 늘 열려 있던 것 고침
- outreach.js/css 캐시 버전 20261030a, 브라우저 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:28:48 +09:00
king c13f529721 Merge branch 'feat/project-desc-link-format' 2026-10-30 15:41:48 +09:00
king f904d5935c feat(프로젝트): 설명란 하이퍼링크 글자 크기·굵기 변경
- 링크는 한 글자처럼 잠겨(contenteditable=false) execCommand 서식이 안 들어갔다
- 고른 범위의 링크는 링크 안쪽 span style 로 크기(글자 크기 도구)·굵기(굵게 버튼·Ctrl+B)
- 링크 기본이 굵게라 보통 = font-weight: 400, 서버 desc_inline_style 이 400 만 허용
- 글자와 같이 고르면 글자에 적용된 굵기를 따름
- project.js 캐시 버전 20261030b, 브라우저·sanitize 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:41:47 +09:00
king 945b81ab4a Merge branch 'fix/project-board-drag' 2026-10-30 15:21:11 +09:00
king c85ba4acc3 fix(프로젝트): 보드에서 끌어 옮긴 연결 업무 카드가 제자리로 돌아가던 문제
원인: 연결 업무(다른 프로젝트 카드)는 이 프로젝트 보드에서도 원 소속
tasks.sort_order 로 정렬됐는데, reorder_tasks 는 tasks.stage_id = 섹션인
업무만 고쳐 연결 카드 자리가 저장되지 않았다. 실시간 동기화로 다시 받으면
연결 카드가 원 소속 순서로 돌아가며 옮긴 카드도 밀려났다.

- 마이그레이션 032: task_project_links.sort_order(연결별 보드 순서)
- reorder_tasks 가 연결 행 순서도 저장, 목록은 COALESCE(연결 순서, 원 소속 순서)
- 032 미적용이면 예전 그대로(link_order_ready)
- 연결 카드를 다른 섹션으로 옮길 때도 놓은 자리 저장
- project.js 캐시 버전 20261030a, 실제 PG 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:21:05 +09:00
king fa50a85730 Merge branch 'feat/perf-ads-kpi-line' 2026-10-30 14:54:01 +09:00
king 12c733bafc feat(실적): 광고비 탭 KPI 카드를 한 줄로, 월 누적 광고비 삭제
- 매출 실적 탭처럼 .perf-kpi-line 한 줄: 광고비 · 매출 대비 광고비 · 연 누적
  (항목은 세로 선으로 나눔, 좁은 화면은 한 항목씩 줄바꿈)
- 월 누적 광고비 KPI 삭제, 안 쓰는 KPI 카드 CSS 삭제
- performance.css 캐시 버전 20261030a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:54:00 +09:00
king 72352a2ed9 Merge branch 'feat/perf-ex-groupbuy-live' 2026-10-30 14:36:55 +09:00
king 38afbca839 feat(실적): 공동구매 칸 저장 즉시 카페24(공구 제외) 칸 반영
- 공동구매 날짜 칸을 저장하면 같은 줄 차이 칸 = 카페24 − 저장 응답(총매출·수수료·차감)
- 차이 칸에 data-diff-minus·data-base(카페24 값) — 일 행만, 합계 줄은 새로고침 때
- performance.js 캐시 버전 20261030a

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:36:53 +09:00
king ede1f8e5e1 Merge branch 'feat/perf-cafe24-ex-groupbuy' 2026-10-30 14:29:53 +09:00
king 45f92f60ca feat(실적): 매출 실적 표에 카페24(공구 제외) 열 추가
- "카페24 공동구매" 열 바로 오른쪽에 카페24 − 카페24 공동구매 계산 열
  (총매출·수수료·차감 매출 각각, 기간·주간 합계 행 포함)
- 표 열만 — 일 합계·KPI·그래프엔 안 더함, 클릭·메모 없음
- 공동구매 쇼핑몰은 이름으로 찾음, 그룹 하위면 같은 그룹으로 접힘

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:29:50 +09:00
king 4ec9f2944a Merge branch 'feat/dispatch-period-set-sheet' 2026-10-30 12:49:57 +09:00
king 439ecb035c feat(배송): 기간별 발송 수량 엑셀에 세트별 요약 시트 추가
- 「세트별 요약」: 세트 코드 × 날짜 피벗, 낱개로 풀기 전 세트 단위 수량(_N 배수 반영)
- 아이템별·세트별 요약 시트 생성 코드를 하나로 합침
- 다운로드 카드 안내 문구·모듈 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:49:48 +09:00
king 5a660e73dd Merge branch 'feat/login-next-users-json' 2026-10-30 10:46:28 +09:00
king 007a16eb9c fix(공통): 로그인 후 보던 화면으로 복귀 + 깨진 users.json 덮어쓰기 방지
- app/store.py login_redirect(): 로그인 전 화면 주소를 /login?next= 로 넘긴다(GET 만 —
  폼 POST 주소로 돌아가면 405). 경비·쿠팡·휴가·말레이시아·배송·카페24·실적 11곳이
  next 없이 /login 으로 보내던 것과 프로젝트·입출고·안내문 발송의 복사본 4벌을 이 함수로.
- UserStore._read: JSONDecodeError 를 빈 목록으로 삼키지 않는다 — 다음 로그인이 전체
  사용자·권한을 그 한 명으로 덮어쓰던 것을 막는다.
- tests/test_login_redirect.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:45:58 +09:00
king c9b4fa36fe Merge branch 'docs/server-arch-diagram' 2026-10-30 03:20:39 +09:00
king 2a3272e514 docs: 서버 아키텍처 다이어그램(HTML) 추가
Proxmox → Gitea VM / Ubuntu VM → Docker(NPM·main-app·cafe24-worker·postgres-db)
연결 관계를 diagram-design 스타일 단일 HTML로 정리.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 03:20:36 +09:00
king e420b7f1af Merge branch 'feat/dispatch-period-bom' 2026-10-28 16:08:19 +09:00
king 7914fc6056 feat(dispatch): 기간별 발송 수량 엑셀 — 세트는 낱개로 풀어 합산
- 세트(MY-)는 itemcode_db BOM 으로 구성 낱개 분해 후 같은 날 같은 코드에 합산
- BOM 없는 세트가 있으면 422 로 해당 세트 목록 안내(조용히 틀린 파일 방지)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:08:18 +09:00
king 667bdd813c Merge branch 'feat/dispatch-period-export' 2026-10-28 15:53:08 +09:00
king 66b5155b9b feat(dispatch): 수퍼 관리자 전용 기간별 발송 수량 엑셀 다운로드
- GET /dispatch/period-export?date_from=&date_to= (서버 측 is_super_admin 검사, 최대 366일)
- 시트 「날짜별」(날짜/아이템코드/상품이름/수량) + 「아이템별 요약」(아이템×날짜 피벗, 합계)
- seller_sku _N 배수 반영, 콤보는 발송된 그대로(분해 안 함), 상품명은 itemcode_db 우선
- 배치 목록 오른쪽에 기간 선택 카드(수퍼 관리자에게만 표시)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:53:05 +09:00
king 883fcd24f6 Merge branch 'feat/perf-colw-label' 2026-10-27 23:32:14 +09:00
king fbed3ef159 fix(performance): 날짜 열은 너비 조절 안 함(늘 자동 너비)
수동 열 너비 모드에서도 날짜 열은 글자 길이 자동 너비 유지, 경계 손잡이 없음,
예전에 저장된 날짜 열 너비는 무시.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:32:14 +09:00
king 2b3b36d646 Merge branch 'feat/perf-colw' 2026-10-27 23:20:25 +09:00
king d9dd03ecc8 feat(performance): 일자별 표 열 너비 자동/수동 옵션
실적 설정 "보기 설정"에 표 열 너비 [자동(글자 길이)]·[수동 조절] 추가(쿠키 perf_colw).
수동이면 매출 실적·광고비 일자별 표 머리글 오른쪽 경계를 끌어 열 너비를 바꾸고,
바꾼 너비는 localStorage(perf_colw_sales/ads)에 유지. 경계 두 번 클릭 = 그 열만 자동,
설정 [조절한 너비 초기화]로 전부 되돌림. 그룹 접기·펴기 애니메이션과 연동.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:20:24 +09:00
king d48a942932 Merge branch 'feat/inout-mail-toolbar' 2026-10-27 13:04:08 +09:00
king 3d2e20427c feat(inout): 발주 메일 본문 서식 막대(크기·굵게·색·정렬·목록·링크 등)
미리보기 위 서식 막대로 고른 글자의 서식을 바꾼다(execCommand, 표·인라인 서식 유지).
서버는 밑줄·취소선 text-decoration-line 을 메일용 text-decoration 으로 바꿔 보낸다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:04:07 +09:00
king d007122782 Merge branch 'feat/inout-mail-edit' 2026-10-27 12:09:55 +09:00
king f4d7e9588f feat(inout): 발주 메일 미리보기에서 본문 바로 고치기
미리보기 창을 눌러 글·표를 고치면 고친 본문 그대로 발송(안 고치면 서버 본문).
서버가 허용 태그·인라인 서식만 남기고 글 버전도 다시 만든다. [원래 본문으로]·닫을 때 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:09:40 +09:00
king 7275f12a74 Merge branch 'feat/outreach-settings-editor' 2026-10-27 09:55:22 +09:00
king 9c166be404 feat(outreach): 설정 화면 세로 2단(메일 | DM) + 메일 본문 서식 편집기, {이름} 빨강 굵게
- 설정 = 왼쪽 메일(제목·(광고)·보내는 이름·본문 편집기·끝 문구·사진), 오른쪽 인스타 DM, 위 저장 막대
- 메일 본문 = Quill 2.0.3 편집기(글자 크기·굵게·기울임·밑줄·취소선·색·배경·정렬·목록·링크·서식 지우기·되돌리기),
  vendor/quill 에 자체 호스팅
- 본문 HTML 저장(fmt=html) — 서버 sanitize_html 로 허용 태그·스타일만, 예전 글은 text_to_html 로 자동 변환
- {이름} 은 두 편집기에서 빨강 굵게(화면에서만, 메일에는 남지 않음), 글자마다 서식이 달라도 이름으로 바꿈
- DM 편집기: 서식 없음, 글자 수, [메일 본문 글 가져오기]
- 테스트: 정리기·예전 글 변환·웹 흐름, 설정 화면 브라우저 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:55:13 +09:00
king 77355b10e4 Merge branch 'feat/outreach-dm-template' 2026-10-27 09:31:28 +09:00
king 6c87a736a6 feat(outreach): 설정에 인스타 DM 문구 칸 — 비우면 메일 본문으로
- store: dm_body(최대 1000자)·dm_text, needs_name 을 메일/DM 구분별로
- 리스트 [DM 보내기] 복사 글·DM 미리보기가 DM 문구 사용
- 설정 화면: DM 문구 칸 + 글자 수, [기본 문구로 되돌리기]에 포함
- 설정은 outreach_settings JSON 이라 DB 변경 없음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 09:31:18 +09:00
king 3a0ec6e840 Merge branch 'feat/perf-auto-refresh'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:37:44 +09:00
king 18d2835304 feat(performance): 자동 업데이트가 끝나면 매출 실적·광고비 화면 새로 고침
- 화면이 20초마다 GET /api/update-status?kind=sales|ads 로 마지막으로 끝난 업데이트를 보고,
  그린 때(update_watch.seen)와 다르고 도는 중이 아니면 reload (jobs.last_finished — 메모리만, DB 안 읽음)
- 보는 사람이 직접 누른 업데이트는 제외(진행 창이 새로 그림), 매출·광고비 따로
- 칸 입력·창·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다리고 "새 데이터 있음" 안내, 탭이 안 보이면 안 물음
- 테스트: last_finished·update-status API, 브라우저(새로 고침·기다림·종류별)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:37:39 +09:00
king fba27772a4 Merge branch 'feat/perf-auto-sync-clock'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:07:42 +09:00
king c9e5a78115 feat(performance): 자동 업데이트 카드 — 시간·간격 칸 글자 너비, 아날로그 시계
- 시간(시·분)·간격 칸이 공용 .erp-input min-width 240px 로 늘어나던 것을 글자 너비만큼으로
- 시간 오른쪽에 12시간 아날로그 시계: 시작·끝 바늘, 그 사이(시계 방향)를 빨갛게, 12시간 넘는 부분은 진한 빨강.
  시간을 바꾸면 바로 다시 그림, 마우스를 올리면 "09:00 ~ 19:00 (10시간)"
- 브라우저 테스트: 실제 erp.css 로 칸 너비 확인, 시계 부채꼴·눈금·바늘·12시간 초과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:07:37 +09:00
king 2bbc2320dc Merge branch 'feat/perf-auto-sync-schedule'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:01:11 +09:00
king 07861dfe8c feat(performance): 자동 업데이트 일정 설정 — 매출·광고비 따로 간격·요일·시작/끝
- 실적 설정 "자동 업데이트" 카드(관리자): 매출 실적·광고비 각각 사용·요일([매일]·[평일])·
  시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30분), PUT /api/auto-sync-schedule
- 마이그레이션 011 perf_settings(key auto_sync, JSONB). 미적용·값 없음 = 기본 일정(매일 9~19시 30분)
- auto_sync: 종류별 일정·Scheduler(1분마다 다시 읽어 바뀐 종류만 다시 계산, 종류마다 따로 스레드)
- 매출·광고비 탭 카운트다운이 각자 일정대로 다음 회차 계산(nextScheduleSlot)
- 테스트: 일정 계산·검증·Scheduler·저장 API·브라우저(설정 카드·카운트다운)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:01:00 +09:00
king 5d30433019 Merge branch 'feat/outreach-module'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:28:27 +09:00
king 8c805fdd9c feat(outreach): 안내문 발송 모듈 — 메일 일괄 발송(본인 Gmail)·인스타 DM 반자동·{이름}
- 새 모듈 app/modules/outreach(권한키 outreach, outreach_db — scripts/sql/outreach_db_init.sql, OUTREACH_DB_URL)
- 리스트 붙여넣기(주소, 이름) → 주소를 보고 메일/DM 판별(store.detect: 이메일·@계정·instagram.com·ig.me·계정명) → 미리보기 → 추가
- 메일 = 고른 줄을 한 UPDATE 로 발송중(두 번 눌러도 한 번) → 백그라운드로 본인 Gmail 한 사람에 한 통(입출고·휴가와 같은 Gmail 연결),
  설정 사진 본문 아래(cid), 보냄/실패·기록. 인스타 = 이름 넣은 문구 복사 + ig.me DM 창 → [보냄] 기록(공식 API 는 첫 DM 불가)
- 설정: 제목·본문 기본 = 미라네주방 공동구매 제안 문구, {이름}·**굵게**, 보내는 이름·끝 문구·(광고) 표시, 사진 10장
- 입출고 Gmail 콜백을 모듈 공용으로(_GMAIL_ORIGINS — vacation·outreach)
- 테스트: 판별·본문·발송(가짜 Gmail)·실제 앱·실제 PG(동시 claim 4번 = 1번)·브라우저

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:28:21 +09:00
king e197d3deb3 Merge branch 'feat/vacation-hire-based-expiry'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:27:56 +09:00
king 4b2defac3a feat(vacation): 연차 12/31 소멸 삭제 — 입사일 기준, 연차마다 쓸 수 있는 기한
- store.leave_grants/leave_period/leave_status: 1년 미만 월 1일 = 입사일부터 1년까지, 근속 n년 연차 = 생긴 날부터 1년까지(근로기준법 제60조)
- 승인된 연차·반차를 날짜별(usage_units = compute_days 규칙)로 나눠 그날 쓸 수 있는 연차 중 먼저 소멸하는 것부터 차감, 생기기 전이면 당겨 씀
- 화면: 지금 연차 기간 · 생기는 연차(오늘까지 +앞으로) · 사용 · 오늘 쓸 수 있는 잔여 · 먼저 소멸(날짜·일수), 해 이동 없음, 달력 위 내 연차도 같은 값
- 직접 입력 = 지금 연차 기간이 시작한 해 줄(override_year), 시스템 전 사용 = 2026 줄(도입일에 쓴 것으로)
- 테스트: 규칙(10/12 입사 사례·먼저 소멸·당겨 씀·시스템 전·입사일 없음), 실제 PG, 실제 앱, 브라우저

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 16:27:50 +09:00
king 197c3c13a3 Merge branch 'feat/vacation-hire-legal-meet-section'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:53:56 +09:00
king 6f58beb2c5 feat(project): 회의록 업무 등록 — 세부 업무 줄에 상위 업무 섹션 표시 · 제목 열을 업무 오른쪽으로
- 서버 parent_stage_name(_mt_select LATERAL 재귀 — 세부의 세부면 섹션 있는 맨 위 업무), 화면은 회색 고칠 수 없는 섹션
- 열 순서 담당자·프로젝트·섹션·업무·제목, 제목 Enter = [적용]으로 포커스, 도움말 갱신
- 테스트: 실제 PG parent_stage_name, goals_meeting_ui [2g4]·[2g5]

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:53:48 +09:00
king d20ce1efac feat(vacation): 입사일(이름 옆 날짜) · 근로기준법 연차 자동 · 2026 시스템 전 사용 연차
- 잔여 연차 표 이름 옆 입사일 날짜 버튼(ErpDatePop.enhance, « » 1년씩) → vacation_employees(마이그레이션 002)
- 법정 연차 = 근로기준법 제60조 입사일 기준(1년 미만 월 1일·최대 11, 근속 n년 min(25, 15+(n-1)//2)), 그해 생기는 날을 모음
  (store.legal_annual_leave, 화면도 같은 계산으로 바로 표시) — 연차 칸을 비우면 법정, 숫자면 직접 입력(total_days NULL 허용)
- 2026(도입 해)만 "시스템 전 사용"(prior_used) 칸 — 잔여 = 총 − 시스템 전 사용 − 승인된 연차·반차(db.balance_summary 한 곳)
- 테스트: 법정 연차 규칙, 실제 PG(입사일·법정·직접·시스템 전·검증), 실제 앱 저장, 브라우저(입사일 버튼·바로 계산·전송)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:53:45 +09:00
king f0391e88fa Merge branch 'feat/vacation-no-settings'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:16:45 +09:00
king a12a862c47 feat(vacation): 설정 화면·공휴일 설정 삭제 · 옵션 수정 = 관리자·승인자·통보자
- [설정] 버튼·설정 화면·공휴일 추가/삭제 삭제(예전 /vacation/settings 는 옵션으로), 쓰지 않는 CSS·db 공휴일 CRUD 정리
- 쉬는 날 = 국경일·대체공휴일 표(KR_HOLIDAYS)만 — vacation_holidays 는 남아 있지만 읽지 않음
- 옵션(승인자·통보자·잔여 연차) 수정 = ERP 관리자(수퍼 포함) + 지금 승인자 + 승인 통보자(_can_edit_options), 예전엔 관리자만
- 테스트: 실제 PG(국경일 표만), 실제 앱(통보자·승인자 수정 가능·그 밖 403, 설정 주소 없음·버튼 없음)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:16:40 +09:00
king 6191118ac7 Merge branch 'feat/vacation-holidays-balances'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:06:20 +09:00
king 36d000eb17 feat(vacation): 달력 공휴일 이름 · 잔여 연차를 옵션으로(참여자 표) · 연차 차감·12/31 소멸
- 쉬는 날 = 국경일·대체공휴일(project KR_HOLIDAYS, 2026~2030) + 휴가 설정 공휴일(덮어쓰기, 빨강 해제 = 근무일) — db.holiday_map 한 곳
  (달력·날짜 팝업·일수 계산), 메인 달력은 날짜 아래 이름 + 그 주 막대 내림
- 잔여 연차 등록을 설정 → 옵션(관리자): 참여자 전원 아이콘·이름 미리 보여 주는 표, 사용·잔여·작년 참고, 한꺼번에 저장(save_balances)
- 사용 연차 = 승인된 연차·오전반차·오후반차만(병가·경조·대체휴무·기타 제외), 해를 넘는 신청은 해마다 나눔, 연도별 12/31 소멸 안내
- 옵션 화면 카드가 화면 높이에 눌려 잘리던 것·입력 칸 최소 너비 수정
- 테스트: 실제 PG(holiday_map·used_days·save_balances), 실제 앱(옵션 표·저장 권한·설정 없음·달력 이름)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:06:15 +09:00
king 6a1c9f4434 Merge branch 'feat/vacation-datepop'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:50:32 +09:00
king 77cf46c859 feat(vacation): 휴가 신청 날짜 칸 — 프로젝트와 같은 아사나식 날짜 팝업
- 공용 erp-datepop.js/css(project.js openDatePopover·enhanceDateInput·.pj-datepop CSS 를 떼어 낸 같은 모양·동작)
- 시작일·종료일 = 숨긴 input + 날짜 버튼 둘(enhanceRange), 어느 쪽을 눌러도 같은 기간 팝업(누른 칸 먼저, 시작 → 종료 → 닫힘),
  반차는 하루짜리, 직접 입력(Enter), Esc·바깥 클릭 닫힘
- 공휴일 = 휴가 설정 공휴일(빨강, 작년~내년) — 팝업 빨강·이름, 예상 일수에서도 제외(서버 compute_days 와 같게)
- 테스트: vacation_datepop.browser.test.js(render_vacation.py), 휴가 신청 화면 공휴일·스크립트 렌더 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:50:25 +09:00
king a6f505bebf Merge branch 'feat/vacation-options-mail'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:35:50 +09:00
king 09f6a2ee6f feat(vacation): 휴가 옵션(승인자·승인 통보자) · 제출·승인·반려 메일(처리한 사람 본인 Gmail)
- /vacation/options(달력 [옵션], 수정 = ERP 관리자): 휴가 승인자(여러 명)·휴가 승인 통보자 — vacation_options(마이그레이션 001)
- 승인·반려 = 관리자 + 옵션 승인자(지정 시 그 사람만), 비우면 예전처럼 vacation_approver 권한자
- 메일(notify.py, 응답 뒤 백그라운드): 제출 = 승인자+통보자, 승인·반려 = 승인자+통보자+신청자
  보내는 사람 = 그 일을 한 사람 본인 Gmail(입출고와 같은 연결·같은 구글 콜백, _gmail_callback_vacation),
  없거나 실패하면 회사 SMTP(이름·Reply-To = 그 사람, app/mail.py reply_to 추가)
- vacation_mail_log → 상세 화면 "메일" 줄, 휴가 화면 셸 오른쪽 넘침(border-box) 수정
- 테스트: test_vacation_options_mail.py(규칙·내용·Gmail→SMTP·실제 앱 권한·콜백), test_vacation_db.py(실제 PG)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:35:44 +09:00
king 2cba5596a9 Merge branch 'fix/perf-sticky-page-scroll'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:17:29 +09:00
king de5a8a3d0a fix(performance): 일자별 표 제목·기간 합계 행 — 페이지 스크롤에 고정(매출·광고비), 스크롤 막대 배경 투명
- 10-26 판은 표 상자 안 세로 스크롤이라 진짜 ERP 셸에서 상자 아래가 화면 밖에 잘리고 휠이 페이지로 안 넘어갔다
- 표 상자 세로 스크롤 없앰 → stickyHead 가 .erp-page 스크롤마다 제목 행·기간 합계 행 칸을 translateY 로 내림(표 끝에서 멈춤),
  내려온 동안 제목 칸이 아래 1px 선을 직접 그림(border-collapse 선 틈으로 뒤 줄이 비침 방지)
- 스크롤 막대 트랙 투명(scrollbar-color, 표 상자·실적 화면)
- perf_sticky.browser.test.js 를 진짜 erp_base.html 셸 렌더(perf_*_shell.html)로 — 휠 스크롤·가로 고정·표 끝 멈춤

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 14:17:25 +09:00
king 906633a884 Merge branch 'feat/perf-sticky-meeting-subtasks'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:32:02 +09:00
king 96f54db0b1 feat(project): 섹션째 다른 프로젝트로 · 회의록 글 칸 하이퍼링크 · 업무 등록 표 하위 업무·줄 클릭 업무 창
- 보드 섹션 머리를 왼쪽 프로젝트 목록에 놓으면 확인 창 → POST /api/stages/{id}/move-project
  (db.move_stage_to_project 한 트랜잭션: 섹션 + 업무 + 세부 업무, 대상 맨 끝, 원·대상 멤버만, 남의 연결은 원 프로젝트에 섹션 없음)
- 목표·회의록 글 칸 서식 도구 🔗 — pj-rich 조각 link(http(s)만, 서버 store.goal_link), 주소 붙여넣기 = 링크, Ctrl+클릭 = 새 탭
- 회의록 업무 등록 표: 등록된 줄 [+] = 바로 아래 세부 업무 초안, 세부 업무 줄은 상위 줄 아래 들여쓰기,
  등록된 줄 어디든 클릭 = 오른쪽 업무 창, ↳ 상위 = 상위 업무 창
- 도움말·CLAUDE.md·PROJECT_MODULE.md 6-26, 정적 파일 버전 20261026a
- 테스트: test_move_stage_to_other_project(실제 PG), 링크 서버 검증, project_ui [섹션 이동], goals_meeting_ui [2g5],
  goal_text_link.browser.test.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:29:14 +09:00
king 3d14ff4a85 feat(performance): 기간 빠른 선택 이번달·올해만(기본 이번달) · 일자별 표 제목·기간 합계 행 스크롤 고정
- 매출 실적·광고비 탭 오늘·이번주 버튼 삭제, 매출 실적 기본 기간 = 이번달
- 일자별 표 상자(.perf-main-wrap)를 화면 높이로 묶어 상자 안 세로 스크롤 — 제목 행 + 맨 위 기간 합계 행 sticky
  (합계 행 top = 제목 행 높이 --perf-head-h, stickyHead 가 ResizeObserver 로 잼), 날짜 열 가로 고정은 그대로
- 테스트: perf_sticky.browser.test.js(실제 브라우저), test_ad_spend 빠른 선택 순서

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:29:09 +09:00
king 7731e4e8de Merge branch 'feat/cupang-outbound-center-colors' 2026-10-23 16:31:15 +09:00
king 248782fffb feat(cupang): 출고리스트 작성 팝업 — 입고센터별 카드 배경색
센터를 고르면 카드 배경·왼쪽 띠·제목 색이 센터마다 달라진다(팝업에 나온 순서대로 8색, 같은 센터는 같은 색, 미선택은 회색).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:31:10 +09:00
king c590e0fabe Merge branch 'feat/cupang-outbound-height' 2026-10-23 16:27:42 +09:00
king bed658576d feat(cupang): 출고리스트 작성 팝업 높이 850px 고정 — 버튼 줄은 맨 아래
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:27:38 +09:00
king 6fffa88f68 Merge branch 'feat/cupang-outbound-multi-center' 2026-10-23 16:20:26 +09:00
king 7e459c1926 feat(cupang): 출고리스트 작성 — 입고센터별 입력·기본 택배·완료 진행 막대(%)
- 팝업에 입고센터 카드: [+ 입고센터 추가]·[센터 삭제], 센터마다 입고센터·출고방식·제품·출고를 따로 입력
  (작성일·출고일·센터입고일·작업자는 공통), 출고방식 기본값 택배
- POST /cupang/api/outbound-sheet: centers 목록을 받아 센터 순서대로 출고일 시트 아래에 덧붙임
  (엑셀 내려받기·올리기 1번씩, 순번 이어짐, 파렛트 센터만 배경색). centers 없으면 예전처럼 센터 1곳
- ?stream=1 이면 단계별 진행률을 NDJSON 으로 흘려보냄(내려받기 → 센터별 추가 → 올리기 → 완료/오류),
  팝업은 막대 그래프와 %로 표시하고 단계 사이에도 조금씩 채움, 실패하면 빨간 막대 + 사유
- 테스트: pytest(센터별 입력 검사·여러 센터 한 번에 쓰기·진행 단계·스트림·충돌), Playwright(카드·진행 막대·완료·실패·모바일)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:20:21 +09:00
king 904cf10e5c Merge branch 'fix/cupang-outbound-xlsx-only' 2026-10-23 15:31:29 +09:00
king 1926128fb0 fix(cupang): 출고리스트 작성 팝업은 항상 드라이브 엑셀 파일에만 기록
- 서버 CUPANG_SHEET_ID 가 구글 시트 문서이거나 드라이브 인증이 없으면 자동 판별이 구글 시트로 써서
  팝업 내용이 계속 구글 시트에 들어갔다
- router._outbound_target: CUPANG_OUTBOUND_XLSX_ID(기본 1J74op7lBZOgE27p4R28I3RWsv0EtXdii)만 보고 항상 drive_xlsx.
  인증이 없거나 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시)
- 입고센터 후보도 같은 엑셀 파일에서 읽음, 로그에 기록한 파일 id 남김
- [분배 확정]·출고 삭제 동기화(CUPANG_SHEET_ID)는 그대로

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:31:25 +09:00
king cfb11955d4 Merge branch 'fix/cupang-outbound-drive-xlsx' 2026-10-23 15:12:16 +09:00
king 2f31604c4e fix(cupang): 밀크런 출고리스트를 구글 드라이브 엑셀(.xlsx) 파일에 기록
- 출고리스트 문서(1J74op7lBZOgE27p4R28I3RWsv0EtXdii)는 구글 시트가 아니라 드라이브에 올린 .xlsx 라
  Sheets API 로는 쓸 수 없었다 → app/integrations/drive_xlsx.py 추가: 내려받아 openpyxl 로 고친 뒤
  같은 파일 id 에 다시 올림(GoogleSheetsWriter 와 같은 메서드, lock 블록 = 내려받기·올리기 1번씩)
- 올리기 직전 파일 version 이 바뀌었으면 덮어쓰지 않고 처음부터 다시(최대 3번)
- router._sheet_target: 드라이브에서 형식을 보고 xlsx/구글 시트 writer 선택, CUPANG_SHEET_ID 기본값 = 위 파일
  (출고리스트 작성 팝업과 분배 확정·출고 삭제 동기화 모두 적용)
- 팝업 문구 "구글 시트" → "출고리스트 엑셀", cupang-outbound.js 캐시 버전 올림
- 테스트: 가짜 Drive 에 진짜 xlsx 를 두고 덧붙이기·양식 생성·충돌 재시도·시트 삭제·범위 읽기·writer 선택

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:12:11 +09:00
king e63734c984 feat(cupang): 밀크런 출고리스트 작성 팝업 — 구글 시트 출고일 시트 아래에 덧붙임
- 첫 화면 "+ 신규 등록" 옆 엑셀색 버튼 → 작성일·출고일·센터입고일(프로젝트 날짜 팝업),
  입고센터(시트 F열 + 등록 센터, 직접 입력), 출고방식(파렛트/택배), 코드표 검색 제품·수량, 출고, 작업자(기본 핫프렌즈)
- POST /cupang/api/outbound-sheet: 출고일 시트 YYYYMMDD(요일) 맨 아래에 기존 양식으로 추가
  (순번 이어짐·파렛트 배경색), 시트가 없으면 5행 양식째 생성. cupang_db 에는 저장하지 않음
- GET /cupang/api/outbound-sheet/centers: 입고센터 후보(10분 캐시)
- export.build_block 분리(기존 build_table 결과 동일), google_sheets 에 sheet_titles·read_ranges·append_block 추가
- 테스트: pytest(양식·입력 검사·덧붙일 위치·Sheets 요청·실제 앱), Playwright 화면 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:57:43 +09:00
king 9883971beb feat(auth): authorize external modules from ERP permissions 2026-10-22 16:42:10 +09:00
king da42675a15 Merge branch 'feat/perf-memo-all-shops' 2026-10-22 12:57:49 +09:00
king cebe5719a5 feat(performance): 셀 메모를 모든 쇼핑몰 날짜 칸에서 — API 쇼핑몰 칸도 우클릭 메모
메모 대상을 수동 입력 칸(td.is-manual-cell)에서 쇼핑몰 날짜 칸 전부(td[data-memo-code])로 넓힘.
왼쪽 클릭은 그대로(입력 칸 = 금액 입력, API 칸 = 주문 내역). 그룹 열·주간합계·합계 줄은 아님.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:57:16 +09:00
king b80887ba1b Merge branch 'fix/perf-no-cell-tips-project-image-fit' 2026-10-22 12:49:41 +09:00
king 808361b62c fix: 실적 표 칸 풍선 도움말 제거 · 댓글 사진 창 기본 맞춤(창에 꽉 차게)
- [실적] 매출 실적·광고비 표 몸통 칸(입력 칸·날짜 칸·광고비 줄)의 title 풍선 도움말 제거(저장 뒤에도 안 붙임), 열 머리글은 그대로
- [프로젝트] 댓글 사진 이미지 창: 처음 = 맞춤, 창 크기 = 사진 비율이라 가장자리 검은 공간 없이 꽉 참,
  막대는 사진 위에 뜸, 창 크기를 바꿔도 맞춤 상태면 다시 맞춤(확대·끌기 뒤엔 그대로)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:49:40 +09:00
king 88c0c961cc Merge branch 'feat/perf-ads-autofit-etc-memo' 2026-10-22 12:40:23 +09:00
king b8564e8f3e feat(performance): 날짜 칸 메모·광고비 표 열 너비 자동/날짜 열 고정·기타광고비 열
- 매출 실적·광고비 금액 입력 칸 우클릭 → 메모 삽입·수정·삭제(창), 메모 있는 칸 빨간 삼각형·마우스 올리면 메모 상자
  (마이그레이션 010 perf_cell_memos, PUT /api/cell-memos/{kind}/{code}/{date})
- 광고비 표도 열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정(perf-autofit)
- 기타광고비 열(etc, 애터미아자몰 오른쪽) — ROAS 없음
- 테스트: test_cell_memos.py, perf_memo_ads.browser.test.js, 기존 채널 목록 기대값

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:40:22 +09:00
king 317cfd2fdd Merge branch 'fix/project-image-bar-nowrap' 2026-10-22 12:18:37 +09:00
king ec8b9787e6 fix(project): 이미지 창 아래 막대 단추 글자가 여러 줄로 나오던 문제
막대가 left:50% 라 폭이 창 절반으로 잡혀 작은 창에서 줄바꿈됐다 — 막대 폭 = 내용 길이(max-content)·한 줄,
이미지 창 최소 폭 480 → 560px. 브라우저 테스트에 480·560px 창 확인 추가.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:18:36 +09:00
king 443dfc5a8a Merge branch 'feat/project-comment-image-viewer' 2026-10-22 12:13:31 +09:00
king 161dc87c6a feat(project): 댓글 사진을 누르면 이미지 창(100%·끌어 이동·휠 확대·다운로드·원본 보기)
- 댓글 목록·댓글 대화창의 사진 클릭 = 내려받기 대신 이미지 창(처음 원본 100%)
- 이미지 창에 [다운로드] 단추, "1:1" 단추 이름을 [원본 보기]로
- Ctrl·Shift·가운데 클릭은 예전처럼 링크, 도움말·브라우저 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:13:30 +09:00
king 4baf098491 Merge branch 'feat/perf-table-autofit-groups' 2026-10-22 11:44:39 +09:00
king 08d0b2c013 feat(performance): 매출 실적 표 열 너비 자동·날짜 열 고정·그룹 구분·접기 애니메이션
- 열 너비 = 내용 길이(표가 100% 로 늘지 않음, 모든 기간 같음), 날짜 열 고정 너비 → 자동
- 가로 스크롤해도 날짜 열 고정(sticky)
- 그룹 열(진한 보라·묶음 선)과 하위 열(옅은 보라·위 띠) 구분, 마지막 하위 열 오른쪽 선
- 접기 단추 22px ⊟/⊞, 펼치고 접을 때 열 너비 애니메이션
- perf_manual.test.js 를 10/21 변경(앞날 입력·계산식 글자 그대로 전송)에 맞게 고침

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:44:37 +09:00
king ac9159bdbd Merge branch 'feat/perf-custom-shops-groups' 2026-10-22 10:57:05 +09:00
king e3a8649b41 feat(performance): 직접 추가 쇼핑몰(수동 입력)·쇼핑몰 그룹·설정 드래그 순서
- 마이그레이션 009: perf_marketplaces.is_custom·is_group·parent_code
- 설정: [+ 쇼핑몰 추가(수동 입력)]·[+ 그룹 추가], 이름 변경·삭제, 직접 추가 쇼핑몰 그룹 select
- custom_ 코드는 registry.get_adapter 가 수동 입력 전용 어댑터(CustomManualAdapter)로
- 매출 실적 표: 그룹 열 = 보이는 하위 쇼핑몰 합계(일 합계엔 안 더함), ▾/▸ 하위 열 접기(localStorage)
- 설정 표 ⠿ 드래그 → PUT /api/marketplace-order → sort_order, 화면 순서는 ordered_marketplaces 한 곳
- 테스트: test_custom_groups.py, perf_groups.browser.test.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:57:03 +09:00
king 5ef9a55d91 Merge branch 'fix/meta-period-zero-spend' 2026-10-21 16:34:02 +09:00
king e3e3b42c28 fix(performance): 메타 광고비가 0 으로 들어오던 문제 — 기간 조회 응답의 0 인 날은 하루씩 다시 조회
메타가 기간(10/01~10/21)으로 물으면 지출·노출·클릭을 0 으로 주고(링크 클릭·구매는 정상),
하루만 물으면 정상 값을 준다(운영 진단 스크립트로 확인). 지출·노출 0 인데 링크 클릭·구매가 있는 날만
그날 하루를 다시 물어 바꾼다. 집행 없는 계정·진짜 0 인 날은 추가 호출 없음.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:34:01 +09:00
king d7db21a36b Merge branch 'chore/meta-insights-raw' 2026-10-21 16:31:56 +09:00
king aea3b5e83a chore(performance): 메타 진단 스크립트 — 기간 모드(앱과 같은 요청·fetch_days 결과)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:31:55 +09:00
king 6fe6ca92d4 Merge branch 'chore/meta-insights-raw' 2026-10-21 16:28:55 +09:00
king 7fc17b9032 chore(performance): 메타 insights 원본 응답 확인 스크립트(진단, 읽기 전용)
지출·노출·클릭만 0 으로 들어오는 원인 확인용 — 저장된 인증정보로 하루치를 조회해 원본 JSON(토큰 가림)을 출력.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:28:06 +09:00
king 985dbee74e Merge branch 'feat/inout-totals-units' 2026-10-21 16:01:28 +09:00
king af71d4513a feat(inout): 합계 줄 원·kg 단위(무게 정수 반올림), 발주서 품목 표 PP 사용량·은 함유량 전체 사용량
- 발주 메일 표·발주서 화면 품목 표 합계: 금액 뒤 원, 무게 뒤 kg(소수 첫째 자리 반올림)
- 발주서 품목 표 머리글 PP 사용량·은(Ag) 함유량, 발주 수량 전체 사용량 kg(개당 값은 작은 글씨)
- 줄 사용량 계산을 store.line_usage 한 곳으로(메일·화면 공용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:01:27 +09:00
king f0cead5f06 Merge branch 'feat/inout-detail-table-style' 2026-10-21 15:49:52 +09:00
king f341de7c2b feat(inout): 발주서 품목 표 제목·합계 줄 서식, 은(Ag) 원료 합계 kg
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:49:51 +09:00
king 750dc96712 Merge branch 'feat/inout-qty-step-pallet-visual' 2026-10-21 15:38:51 +09:00
king 8652064415 feat(inout): 발주 수량 공배수 ◀ ▶·파렛트 그림·품목 표 제목 행 서식
- 품목 표 제목 행 가운데·굵게·110%
- 수량 칸 오른쪽 ◀ ▶ 로 통·뚜껑 입수 공배수만큼 줄이기·늘리기
- 합계 줄에 꽉 찬 파렛트 그림과 잔량 파렛트(실린 박스만 색칠, %, 몇 박스 더)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:38:50 +09:00
king 48c0c96f1f Merge branch 'feat/inout-boxes-pallet-group-tab' 2026-10-21 15:13:48 +09:00
king cc68d5be67 feat(inout): 박스 입수·파렛트 계산·상품 그룹 탭·달력 다시 그리기 줄임
- 옵션 상품 그룹을 별도 탭으로, 상품 정보 제목 행 가운데·굵게·110%
- 상품 정보에 통 수량(박스)·뚜껑 수량(박스)(마이그레이션 007, 뚜껑 없으면 빈칸)
- 새 발주서: 줄마다 통·뚜껑 박스 수와 공배수 힌트, 합계 박스 → 파렛트(30박스) 계산
  (화면 계산만, 발주 메일은 그대로)
- 메뉴를 옮겨도 달력은 sessionStorage 에서 바로 복원, 서버 값이 바뀔 때만 다시 그림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:13:47 +09:00
king 16515e9095 Merge branch 'feat/inout-cal-bigger' 2026-10-21 14:31:22 +09:00
king 2c4f42d383 feat(inout): 달력을 화면 너비에 맞춰 키움(300~440px)
입출고 화면만 ERP 공용 최대 폭을 풀어 넓은 화면 오른쪽 여백을 쓰고,
달력 글자·칸은 달력 너비 기준(cqw)으로 같은 비율로 커진다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:31:21 +09:00
king 6d1e4f32a4 Merge branch 'feat/inout-cal-holiday-name' 2026-10-21 14:08:14 +09:00
king a396b94a9f feat(inout): 달력 공휴일 이름을 날짜 숫자 아래에 표시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:08:14 +09:00
king cba4b3b441 Merge branch 'feat/project-creator-paste-inout-calendar-groups' 2026-10-21 14:03:35 +09:00
king 0f4f8cabf0 feat(inout): 오른쪽 발주·입고 달력·상품 그룹·색상·담당자 아이콘
- 모든 화면 2열, 오른쪽 300x320 달력(프로젝트 달력 모양) — 날짜별 발주·입고, 누르면 목록
- 옵션 → 상품 정보: 그룹(은 함유량·색상 한 번만), 상품별 그룹·색상(마이그레이션 006)
- 발주 메일 품목 표에서 색상 있는 품목 줄 배경을 그 색으로(발주 당시 색상 사본)
- 옵션 → 담당자 = 아이콘 + 이름, 아래 이메일
- 006 확인을 연결 열기 전에 해 동시 발주에서 연결 풀이 바닥나지 않게

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:03:33 +09:00
king 981ad386bf feat(project): 업무 창 작성자 표시·댓글 이미지 붙여넣기
- 업무 창 맨 위 삭제 버튼 오른쪽에 작성자 아이콘 + 이름(yyyy.mm.dd(요일) hh:mm:ss)
- 업무 창 댓글 칸 Ctrl+V 이미지 붙여넣기 — 썸네일 미리보기, 등록 시 /comments/files 한 요청
- 도움말 갱신, 브라우저 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:03:32 +09:00
king 866dc14f08 Merge branch 'fix/perf-formula-net-display' 2026-10-21 13:15:58 +09:00
king 34dca7cb76 fix(performance): 계산식 입력 직후 차감 매출 숫자가 안 보이던 문제
칸 저장 뒤 총매출만 바꾸고 수수료·차감 매출(기본 보기)은 새로고침 때까지
예전 값(–)으로 흐리게 남겼다. 저장 응답에 그날 수수료·차감 매출을 함께
돌려주고 화면이 세 숫자를 바로 바꾼다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:15:57 +09:00
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
224 changed files with 24768 additions and 1469 deletions
+24 -6
View File
@@ -26,10 +26,13 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# DB/역할/스키마/센터 seed 생성: scripts/sql/cupang_db_init.sql 참고.
# CUPANG_DB_URL=postgresql://cupang_app:replace-me@postgres-db:5432/cupang_db
# 쿠팡 밀크런 출고리스트를 기록할 Google 스프레드시트 (분배 확정 시 출고일 시트 생성)
# - 대상 문서는 반드시 "Google 스프레드시트" 형식(업로드한 .xlsx 는 파일>Google 스프레드시트로 저장)
# - 서비스 계정 이메일(client_email)에 해당 문서를 편집자로 공유해야 한다
# 쿠팡 밀크런 출고리스트 문서 (분배 확정·출고리스트 작성 팝업이 출고일 시트에 기록)
# - 구글 드라이브에 올린 .xlsx 파일 id(기본값 = 아래 id). 구글 스프레드시트 문서 id 여도 된다(형식 자동 판별)
# - .xlsx 는 Drive 권한이 필요하다: 서비스 계정(GOOGLE_SHEETS_CREDENTIALS) 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN
# - 서비스 계정이면 이메일(client_email)에 해당 파일을 편집자로 공유해야 한다
# CUPANG_SHEET_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
# "밀크런 출고리스트 작성" 팝업 전용 — 드라이브 .xlsx 파일 id(기본값 = 아래 id, 엑셀만·구글 시트로 대신 쓰지 않음)
# CUPANG_OUTBOUND_XLSX_ID=1J74op7lBZOgE27p4R28I3RWsv0EtXdii
#
# [방식 A] 사용자 OAuth 리프레시 토큰 — 조직 정책으로 서비스 계정 키를 못 만들 때
# 토큰 발급: python scripts/google_sheets_authorize.py --client-id .. --client-secret ..
@@ -49,6 +52,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 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 폴백 없음).
@@ -149,6 +156,16 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 초기화: 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
# ─── 안내문 발송 모듈 (outreach_db) — app/modules/outreach ───
# 리스트(이메일·인스타 주소 + 이름)에 안내문 메일 일괄 발송(보내는 사람 본인 Gmail — 입출고 Gmail 연결 재사용)·인스타 DM 반자동.
# 초기화: scripts/sql/outreach_db_init.sql (docs/DEPLOYMENT.md "안내문 발송 DB 생성"). 미설정 시 "설정 필요" 안내만.
# OUTREACH_DB_URL=postgresql://outreach_app:replace-me@postgres-db:5432/outreach_db
# ─── 라이브 커머스 모듈 (live_db) — app/modules/live ───
# 말레이시아 라이브 방송의 호스트 정보·방송 스케줄·판매금액·결과 이미지.
# 초기화: scripts/sql/live_db_init.sql (docs/DEPLOYMENT.md "라이브 커머스 DB 생성"). 미설정 시 "설정 필요" 안내만.
# LIVE_DB_URL=postgresql://live_app:replace-me@postgres-db:5432/live_db
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
# 미설정 시 검색 비활성 → 수동 등록만 가능.
@@ -174,10 +191,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 # 끄기
# 매출·광고비 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 오늘 포함 최근 10일.
# 일정(간격·요일·시작/끝)은 실적 설정 "자동 업데이트" 카드에서 매출·광고비 따로 정한다(performance_db 011). 저장 전 기본 = 매일 9~19시 30분마다.
# PERFORMANCE_AUTO_SYNC=false # 끄기(설정 화면 일정과 상관없이)
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 일정 저장 전 기본 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
+6
View File
@@ -46,6 +46,8 @@
| `[경비]` `[개인경비]` | `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.*` |
| `[안내문 발송]` | `outreach/` | `outreach_db` | `outreach` | (모듈 CLAUDE.md) | `outreach.*` |
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live` | (모듈 CLAUDE.md) | `live.*` |
| `[공통]` `[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` | — |
@@ -59,9 +61,13 @@
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
- `app/mail.py`: 프로젝트 알림 메일.
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`).
---
+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(
+345
View File
@@ -0,0 +1,345 @@
"""Google 드라이브에 올려 둔 엑셀(.xlsx) 파일을 시트처럼 고쳐 쓰기(쿠팡 밀크런 출고리스트, 2026-10-23).
구글 시트 문서가 아니라 드라이브의 .xlsx 파일이면 Sheets API 로는 쓸 수 없다. 그래서
파일을 내려받아(openpyxl) 고친 뒤 같은 파일 id 에 내용을 다시 올린다(링크·공유·이름 그대로).
- 인증은 google_drive 와 같다(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함).
- `GoogleSheetsWriter` 와 같은 메서드(sheet_titles·read_ranges·append_block·write_table·delete_sheet·lock)를
같은 인자로 제공한다 → cupang 라우터는 어느 쪽인지 몰라도 된다(`file_kind` 로 골라 씀).
- `with writer.lock:` 안의 호출은 내려받은 사본 하나를 같이 쓰고, 블록이 끝날 때 바뀐 게 있으면 한 번만 올린다.
잠금 밖에서 부른 메서드는 호출마다 내려받고(바뀌면) 올린다.
- 올리기 직전에 파일 version 을 다시 보고, 그 사이 누가 고쳤으면 `XlsxChangedError` — 덮어쓰지 않는다
(호출부가 처음부터 다시 시도).
- 비밀값은 로그·화면에 출력하지 않는다.
"""
from __future__ import annotations
import re
import threading
from io import BytesIO
from typing import Any
from app.integrations.google_drive import GoogleDriveError, GoogleDriveFiles, _friendly_drive
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
SHEETS_MIME = "application/vnd.google-apps.spreadsheet"
_RANGE_RE = re.compile(r"^([A-Z]+)(\d*)(?::([A-Z]+)(\d*))?$")
# 같은 파일을 두 요청이 동시에 내려받아 고치면 나중 것이 앞의 것을 지우므로 한 번에 하나씩.
_LOCK = threading.RLock()
_KIND_CACHE: dict[str, str] = {}
class XlsxChangedError(RuntimeError):
"""내려받은 뒤 올리기 전에 다른 사람이 파일을 고쳤다."""
def _col_num(letters: str) -> int:
n = 0
for ch in letters:
n = n * 26 + (ord(ch) - 64)
return n
def _parse_range(a1: str) -> tuple[str, int, int, int | None, int | None]:
""""'시트'!F6:F" → (시트, 첫 행, 첫 열, 끝 행|None, 끝 열|None). 끝이 비면 시트 끝까지."""
sheet, _, ref = a1.rpartition("!")
if sheet.startswith("'") and sheet.endswith("'"):
sheet = sheet[1:-1].replace("''", "'")
m = _RANGE_RE.match(ref.upper())
if not sheet or not m:
raise ValueError(f"지원하지 않는 범위: {a1}")
c1, r1, c2, r2 = m.groups()
if c2 is None: # 셀 하나
c2, r2 = c1, r1
return sheet, int(r1 or 1), _col_num(c1), (int(r2) if r2 else None), _col_num(c2)
def _text(value: Any) -> str:
"""Sheets API 의 FORMATTED_VALUE 처럼 문자열로(정수인 실수는 소수점 없이)."""
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value)
def _put(cell: Any, value: Any) -> None:
"""Sheets 의 USER_ENTERED 처럼 앞의 작은따옴표는 "글자 그대로" 표시로 보고 떼어 낸다."""
if isinstance(value, str) and value.startswith("'"):
cell.value = value[1:]
cell.data_type = "s" # '=' 로 시작해도 수식이 되지 않게
else:
cell.value = value
class DriveXlsxWriter(GoogleDriveFiles):
"""드라이브 .xlsx 파일 하나를 GoogleSheetsWriter 처럼 다룬다(spreadsheet_id = 드라이브 파일 id)."""
def __init__(self) -> None:
super().__init__()
self._depth = 0
self._book: dict[str, Any] | None = None # {"id", "wb", "version", "dirty"}
# ── 내려받기 / 올리기 ───────────────────────────
def file_kind(self, file_id: str) -> str:
""""xlsx" | "sheets" | 그 밖의 mimeType. 실패는 GoogleDriveError(사유)."""
if file_id in _KIND_CACHE:
return _KIND_CACHE[file_id]
meta = self._meta(file_id, "mimeType")
mime = str(meta.get("mimeType") or "")
kind = "xlsx" if mime == XLSX_MIME else "sheets" if mime == SHEETS_MIME else mime
_KIND_CACHE[file_id] = kind
return kind
def _meta(self, file_id: str, fields: str) -> dict[str, Any]:
self._check()
try:
return self._service().files().get(fileId=file_id, fields=fields, supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise self._error(exc) from None
@staticmethod
def _error(exc: Exception) -> GoogleDriveError:
text = _friendly_drive(exc).replace("업무 파일 폴더", "출고리스트 엑셀 파일")
return GoogleDriveError(text)
def _open(self, file_id: str) -> dict[str, Any]:
from openpyxl import load_workbook
version = str(self._meta(file_id, "version").get("version") or "")
try:
data = self._service().files().get_media(fileId=file_id, supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise self._error(exc) from None
return {"id": file_id, "wb": load_workbook(BytesIO(data)), "version": version, "dirty": False}
def _save(self, book: dict[str, Any]) -> None:
from googleapiclient.http import MediaIoBaseUpload
now = str(self._meta(book["id"], "version").get("version") or "")
if book["version"] and now != book["version"]:
raise XlsxChangedError("출고리스트 엑셀 파일이 그 사이 바뀌었습니다.")
out = BytesIO()
book["wb"].save(out)
out.seek(0)
try:
self._service().files().update(
fileId=book["id"], media_body=MediaIoBaseUpload(out, mimetype=XLSX_MIME, resumable=False),
fields="id", supportsAllDrives=True,
).execute()
except Exception as exc: # noqa: BLE001
raise self._error(exc) from None
class _Session:
def __init__(self, writer: "DriveXlsxWriter") -> None:
self.w = writer
def __enter__(self) -> "DriveXlsxWriter":
_LOCK.acquire()
self.w._depth += 1
return self.w
def __exit__(self, exc_type: Any, *_: Any) -> None:
w = self.w
try:
w._depth -= 1
if w._depth == 0:
book, w._book = w._book, None
if exc_type is None and book is not None and book["dirty"]:
w._save(book)
finally:
_LOCK.release()
@property
def lock(self) -> "DriveXlsxWriter._Session":
"""이 블록 안의 호출은 내려받은 사본 하나를 같이 쓰고, 끝날 때 바뀐 게 있으면 한 번 올린다."""
return DriveXlsxWriter._Session(self)
def _wb(self, file_id: str) -> Any:
if self._book is None or self._book["id"] != file_id:
if self._book is not None and self._book["dirty"]:
self._save(self._book)
self._book = self._open(file_id)
return self._book["wb"]
def _touch(self) -> None:
if self._book is not None:
self._book["dirty"] = True
@staticmethod
def _url(file_id: str) -> str:
return f"https://docs.google.com/spreadsheets/d/{file_id}/edit"
# ── GoogleSheetsWriter 와 같은 메서드 ────────────
def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
with self.lock:
return list(self._wb(spreadsheet_id).sheetnames)
def read_ranges(self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50) -> list[list[list[Any]]]:
"""범위마다 값의 2차원 목록(문자열) — Sheets API 처럼 뒤쪽 빈 칸·빈 행은 잘라 낸다."""
del chunk
with self.lock:
wb = self._wb(spreadsheet_id)
out: list[list[list[Any]]] = []
for a1 in ranges:
title, r1, c1, r2, c2 = _parse_range(a1)
if title not in wb.sheetnames:
out.append([])
continue
ws = wb[title]
rows = [
[_text(v) for v in row]
for row in ws.iter_rows(min_row=r1, max_row=r2 or ws.max_row, min_col=c1,
max_col=c2 or ws.max_column, values_only=True)
]
for row in rows:
while row and row[-1] == "":
row.pop()
while rows and not rows[-1]:
rows.pop()
out.append(rows)
return out
def append_block(
self,
*,
spreadsheet_id: str,
title: str,
cells: dict[tuple[int, int], Any],
merges: list[tuple[int, int, int, int]],
first_row: int,
last_row: int,
first_col: int,
last_col: int,
left_cols: tuple[int, ...] = (9,),
highlight: str = "",
) -> dict[str, Any]:
"""이미 있는 시트의 first_row~last_row 에 표 한 덩어리(위쪽 내용은 그대로). 서식은 GoogleSheetsWriter 와 같다."""
from openpyxl.styles import PatternFill
with self.lock:
wb = self._wb(spreadsheet_id)
if title not in wb.sheetnames:
raise LookupError(f"시트 '{title}' 이(가) 없습니다.")
ws = wb[title]
for (r, c), value in cells.items():
_put(ws.cell(row=r, column=c), value)
for (r1, c1, r2, c2) in merges:
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
fill = PatternFill("solid", fgColor=highlight) if highlight else PatternFill(fill_type=None)
_style_rows(ws, first_row, last_row, first_col, last_col, left_cols=left_cols, fill=fill)
self._touch()
return {
"created": False, "title": title, "first_row": first_row, "last_row": last_row,
"url": self._url(spreadsheet_id),
}
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
"""시트 1장 삭제. 없으면 missing, 문서에 그 하나뿐이면 내용만 비운다(cleared)."""
with self.lock:
wb = self._wb(spreadsheet_id)
if title not in wb.sheetnames:
return {"ok": True, "action": "missing", "title": title}
if len(wb.sheetnames) <= 1:
_replace_sheet(wb, title)
action = "cleared"
else:
wb.remove(wb[title])
wb.active = min(wb.index(wb.active) if wb.active is not None else 0, len(wb.sheetnames) - 1)
action = "deleted"
self._touch()
return {"ok": True, "action": action, "title": title}
def write_table(
self,
*,
spreadsheet_id: str,
title: str,
cells: dict[tuple[int, int], Any],
merges: list[tuple[int, int, int, int]],
header_row: int,
first_data_row: int,
last_row: int,
first_col: int,
last_col: int,
title_row: int,
widths: dict[int, int],
header_bg: str = "",
row_highlights: list[tuple[int, int, str]] | None = None,
) -> dict[str, Any]:
"""시트를 만들고(있으면 새로 갈아 끼우고) 표를 통째로 기록한다. 좌표 1-based, 색은 "RRGGBB"."""
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
with self.lock:
wb = self._wb(spreadsheet_id)
created = title not in wb.sheetnames
ws = _replace_sheet(wb, title)
for (r, c), value in cells.items():
_put(ws.cell(row=r, column=c), value)
for (r1, c1, r2, c2) in merges:
ws.merge_cells(start_row=r1, start_column=c1, end_row=r2, end_column=c2)
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
head = ws.cell(row=title_row, column=first_col)
head.font = Font(size=16, bold=True)
head.alignment = center
ws.row_dimensions[title_row].height = 28
header_fill = PatternFill("solid", fgColor=header_bg) if header_bg else PatternFill(fill_type=None)
_style_rows(ws, header_row, header_row, first_col, last_col, left_cols=(), fill=header_fill)
for col in range(first_col, last_col + 1):
ws.cell(row=header_row, column=col).font = Font(bold=True)
if last_row >= first_data_row:
_style_rows(ws, first_data_row, last_row, first_col, last_col, left_cols=(9,), fill=None)
for (r1, r2, color) in (row_highlights or []):
fill = PatternFill("solid", fgColor=color)
for row in range(r1, r2 + 1):
for col in range(first_col, last_col + 1):
ws.cell(row=row, column=col).fill = fill
for col, px in widths.items():
ws.column_dimensions[get_column_letter(col)].width = round(px / 7.0, 2)
self._touch()
return {"created": created, "title": title, "url": self._url(spreadsheet_id)}
def _replace_sheet(wb: Any, title: str) -> Any:
"""같은 이름의 빈 시트로 갈아 끼운다(탭 위치 유지). 없으면 맨 뒤에 새로."""
if title in wb.sheetnames:
index = wb.sheetnames.index(title)
wb.remove(wb[title])
return wb.create_sheet(title, index)
return wb.create_sheet(title)
def _style_rows(
ws: Any, r1: int, r2: int, c1: int, c2: int, *, left_cols: tuple[int, ...], fill: Any
) -> None:
"""가운데 정렬·줄바꿈·얇은 검은 테두리, left_cols 만 왼쪽 정렬. fill 이 None 이면 배경은 그대로."""
from openpyxl.styles import Alignment, Border, Side
thin = Side(style="thin", color="000000")
box = Border(left=thin, right=thin, top=thin, bottom=thin)
center = Alignment(horizontal="center", vertical="center", wrap_text=True)
left = Alignment(horizontal="left", vertical="center", wrap_text=True)
for row in range(r1, r2 + 1):
for col in range(c1, c2 + 1):
cell = ws.cell(row=row, column=col)
cell.border = box
cell.alignment = left if col in left_cols else center
if fill is not None:
cell.fill = fill
_WRITER: DriveXlsxWriter | None = None
_WRITER_LOCK = threading.Lock()
def get_writer() -> DriveXlsxWriter:
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인)."""
global _WRITER
with _WRITER_LOCK:
if _WRITER is None or not _WRITER.enabled:
_WRITER = DriveXlsxWriter()
return _WRITER
+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
+170 -11
View File
@@ -42,6 +42,37 @@ def _hex_color(value: str) -> dict[str, float]:
}
def a1_sheet(title: str) -> str:
"""A1 표기용 시트 이름 — 작은따옴표로 감싸고 안의 ' 는 '' 로."""
return "'" + title.replace("'", "''") + "'"
def col_letter(col: int) -> str:
"""1-based 열 번호 → 열 문자(A, B, …, AA)."""
letters = ""
while col > 0:
col, rem = divmod(col - 1, 26)
letters = chr(65 + rem) + letters
return letters
def _repeat_cell(
sheet_id: int, r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str
) -> dict[str, Any]:
"""1-based 양끝 포함 범위에 같은 서식을 입히는 요청."""
return {
"repeatCell": {
"range": {
"sheetId": sheet_id,
"startRowIndex": r1 - 1, "endRowIndex": r2,
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
},
"cell": {"userEnteredFormat": fmt},
"fields": fields,
}
}
# 웹 핸들러가 sync def(스레드풀)라 여러 요청이 동시에 이 writer 를 쓸 수 있다.
# googleapiclient 의 HTTP 클라이언트(httplib2)는 스레드 안전하지 않고, 같은 날짜
# 시트를 동시에 지우고/쓰면 내용이 섞이므로 시트 작업은 한 번에 하나씩만 한다.
@@ -169,6 +200,144 @@ class GoogleSheetsWriter:
).execute()
return int(res["replies"][0]["addSheet"]["properties"]["sheetId"])
@property
def lock(self) -> Any:
"""읽고 → 쓰기를 한 덩어리로 묶을 때 쓰는 잠금(같은 시트에 동시에 덧붙이지 않게).
RLock 이라 잡은 채로 이 writer 의 다른 메서드를 불러도 된다."""
return _LOCK
@_serialized
def sheet_titles(self, *, spreadsheet_id: str) -> list[str]:
"""문서의 시트 이름 목록(탭 순서)."""
if not self.enabled:
raise RuntimeError(self.reason or "Google Sheets 미설정")
meta = self._service.spreadsheets().get(
spreadsheetId=spreadsheet_id, fields="sheets.properties.title"
).execute()
return [str(sh.get("properties", {}).get("title") or "") for sh in meta.get("sheets", [])]
@_serialized
def read_ranges(
self, *, spreadsheet_id: str, ranges: list[str], chunk: int = 50
) -> list[list[list[Any]]]:
"""A1 범위 여러 개의 값(범위마다 2차원 목록). 요청 하나가 너무 길지 않게 나눠 읽는다."""
if not self.enabled:
raise RuntimeError(self.reason or "Google Sheets 미설정")
out: list[list[list[Any]]] = []
for i in range(0, len(ranges), chunk):
part = ranges[i:i + chunk]
res = self._service.spreadsheets().values().batchGet(
spreadsheetId=spreadsheet_id, ranges=part
).execute()
got = res.get("valueRanges", [])
out.extend(vr.get("values", []) for vr in got)
out.extend([] for _ in range(len(part) - len(got)))
return out
@_serialized
def append_block(
self,
*,
spreadsheet_id: str,
title: str,
cells: dict[tuple[int, int], Any],
merges: list[tuple[int, int, int, int]],
first_row: int,
last_row: int,
first_col: int,
last_col: int,
left_cols: tuple[int, ...] = (9,),
highlight: str = "",
) -> dict[str, Any]:
"""이미 있는 시트의 first_row~last_row 에 표 한 덩어리를 쓴다(위쪽 내용은 그대로).
서식은 write_table 의 데이터 행과 같다 — 가운데 정렬·줄바꿈·테두리, left_cols 만 왼쪽 정렬,
highlight("RRGGBB")가 있으면 그 덩어리 배경색. 좌표는 1-based."""
if not self.enabled:
raise RuntimeError(self.reason or "Google Sheets 미설정")
meta = self._service.spreadsheets().get(
spreadsheetId=spreadsheet_id,
fields="sheets.properties(sheetId,title,gridProperties.rowCount)",
).execute()
props = next(
(sh.get("properties", {}) for sh in meta.get("sheets", [])
if sh.get("properties", {}).get("title") == title),
None,
)
if props is None:
raise LookupError(f"시트를 찾을 수 없습니다: {title}")
sheet_id = int(props.get("sheetId"))
row_count = int(props.get("gridProperties", {}).get("rowCount") or 0)
requests: list[dict[str, Any]] = []
if row_count < last_row:
# 격자보다 아래에는 값을 쓸 수 없으므로 행을 먼저 늘린다
requests.append({"appendDimension": {
"sheetId": sheet_id, "dimension": "ROWS", "length": last_row - row_count,
}})
for (r1, c1, r2, c2) in merges:
requests.append({
"mergeCells": {
"mergeType": "MERGE_ALL",
"range": {
"sheetId": sheet_id,
"startRowIndex": r1 - 1, "endRowIndex": r2,
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
},
}
})
requests.append(_repeat_cell(
sheet_id, first_row, first_col, last_row, last_col,
{"horizontalAlignment": "CENTER", "verticalAlignment": "MIDDLE", "wrapStrategy": "WRAP"},
"userEnteredFormat(horizontalAlignment,verticalAlignment,wrapStrategy)",
))
for col in left_cols:
requests.append(_repeat_cell(
sheet_id, first_row, col, last_row, col,
{"horizontalAlignment": "LEFT"}, "userEnteredFormat(horizontalAlignment)",
))
if highlight:
requests.append(_repeat_cell(
sheet_id, first_row, first_col, last_row, last_col,
{"backgroundColor": _hex_color(highlight)}, "userEnteredFormat(backgroundColor)",
))
border = {"style": "SOLID", "color": {"red": 0, "green": 0, "blue": 0}}
requests.append({
"updateBorders": {
"range": {
"sheetId": sheet_id,
"startRowIndex": first_row - 1, "endRowIndex": last_row,
"startColumnIndex": first_col - 1, "endColumnIndex": last_col,
},
"top": border, "bottom": border, "left": border, "right": border,
"innerHorizontal": border, "innerVertical": border,
}
})
self._service.spreadsheets().batchUpdate(
spreadsheetId=spreadsheet_id, body={"requests": requests}
).execute()
matrix = [
[cells.get((r, c), "") for c in range(first_col, last_col + 1)]
for r in range(first_row, last_row + 1)
]
self._service.spreadsheets().values().update(
spreadsheetId=spreadsheet_id,
range=f"{a1_sheet(title)}!{col_letter(first_col)}{first_row}",
valueInputOption="USER_ENTERED",
body={"values": matrix},
).execute()
return {
"created": False,
"title": title,
"first_row": first_row,
"last_row": last_row,
"url": f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit#gid={sheet_id}",
}
@_serialized
def delete_sheet(self, *, spreadsheet_id: str, title: str) -> dict[str, Any]:
"""이름이 정확히 일치하는 시트 1장을 삭제한다.
@@ -263,17 +432,7 @@ class GoogleSheetsWriter:
})
def _fmt(r1: int, c1: int, r2: int, c2: int, fmt: dict[str, Any], fields: str) -> dict[str, Any]:
return {
"repeatCell": {
"range": {
"sheetId": sheet_id,
"startRowIndex": r1 - 1, "endRowIndex": r2,
"startColumnIndex": c1 - 1, "endColumnIndex": c2,
},
"cell": {"userEnteredFormat": fmt},
"fields": fields,
}
}
return _repeat_cell(sheet_id, r1, c1, r2, c2, fmt, fields)
requests.append(_fmt(
title_row, first_col, title_row, last_col,
+5
View File
@@ -44,9 +44,12 @@ def send_email(
body: str,
html: str | None = None,
from_name: str = "DBX ERP",
reply_to: str = "",
) -> bool:
"""단순 텍스트(+선택 HTML) 메일 1건 발송.
reply_to — 받는 사람이 [답장]하면 갈 주소(예: 휴가 메일 = 처리한 사람, 2026-10-27). 보내는 주소는 늘 SMTP_FROM.
반환: 성공 True / 비활성·실패 False. 예외를 밖으로 던지지 않는다.
"""
host = _env("SMTP_HOST")
@@ -71,6 +74,8 @@ def send_email(
msg["Subject"] = subject
msg["From"] = formataddr((from_name, sender))
msg["To"] = ", ".join(recipients)
if reply_to and "@" in reply_to:
msg["Reply-To"] = formataddr((from_name, reply_to.strip()))
msg.set_content(body)
if html:
msg.add_alternative(html, subtype="html")
+72 -1
View File
@@ -2,7 +2,7 @@ import inspect
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any
from typing import Any, Literal
from authlib.integrations.starlette_client import OAuth, OAuthError
from dotenv import load_dotenv
@@ -26,10 +26,14 @@ 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.live import build_live_store
from .modules.live import router as live_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.outreach import build_outreach_store
from .modules.outreach import router as outreach_router
from .modules.performance import build_performance_store
from .modules.performance import router as performance_router
from .modules.project import build_project_store
@@ -62,6 +66,8 @@ MODULE_LABELS: dict[str, str] = {
"performance": "실적",
"asset": "자산관리",
"inout": "입출고 관리",
"outreach": "안내문 발송",
"live": "라이브 커머스",
"expense_approver": "개인경비",
"vacation_approver": "휴가",
}
@@ -157,6 +163,8 @@ _MODULE_TEMPLATE_DIRS = [
BASE_DIR / "modules" / "asset" / "templates",
BASE_DIR / "modules" / "notice" / "templates",
BASE_DIR / "modules" / "inout" / "templates",
BASE_DIR / "modules" / "outreach" / "templates",
BASE_DIR / "modules" / "live" / "templates",
]
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
templates.env.loader = ChoiceLoader(
@@ -226,6 +234,11 @@ app.state.notice_store = build_notice_store(app.state.project_store)
# 제품은 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()
# 안내문 발송(메일 일괄·인스타 DM 반자동): OUTREACH_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
# 메일은 보내는 사람 본인 Gmail — 입출고 Gmail 연결(inout_store.inout_gmail_tokens)을 같이 쓴다.
app.state.outreach_store = build_outreach_store(dsn=env("OUTREACH_DB_URL") or None)
# 라이브 커머스(말레이시아 방송 호스트·스케줄): LIVE_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
app.state.live_store = build_live_store(dsn=env("LIVE_DB_URL") or None)
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
app.include_router(expense_router)
@@ -239,6 +252,8 @@ app.include_router(performance_router)
app.include_router(asset_router)
app.include_router(notice_router)
app.include_router(inout_router)
app.include_router(outreach_router)
app.include_router(live_router)
def public_url_for(request: Request, route_name: str) -> str:
@@ -441,6 +456,27 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
"status": "ready",
"category": "운영",
},
{
"key": "outreach",
"title": "안내문 발송",
"subtitle": "Outreach",
"description": "이메일·인스타그램 리스트에 이름을 넣은 안내문을 메일로 일괄 발송하고 인스타 DM 을 보냅니다.",
"url": "/outreach/",
"health_url": "/outreach/health",
"status": "ready",
"category": "운영",
},
{
"key": "live",
"title": "라이브 커머스",
"card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게)
"subtitle": "Malaysia",
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
"url": "/live/",
"health_url": "/live/health",
"status": "ready",
"category": "운영",
},
]
items.append({
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
@@ -457,6 +493,8 @@ 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"/>',
"outreach": '<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>',
"live": '<rect x="2" y="6" width="14" height="12" rx="2"/><path d="m16 11 6-4v10l-6-4"/>',
"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"/>',
@@ -672,6 +710,39 @@ async def healthz() -> dict[str, str]:
return {"status": "ok"}
@app.get("/api/auth/check")
async def external_module_auth(
request: Request, module: Literal["corm", "order"]
) -> JSONResponse:
"""외부 서비스 접근을 ERP의 현재 사용자/권한으로 판단한다.
세션에 권한을 복제하지 않는다. 삭제·권한 해제는 다음 요청부터 반영된다.
호출 서비스는 브라우저의 세션 쿠키만 전달하며 이메일을 지정할 수 없다.
"""
headers = {"Cache-Control": "no-store", "Vary": "Cookie"}
user = get_current_user_record(request)
if user is None:
return JSONResponse(
{"detail": "로그인이 필요합니다."}, status_code=401, headers=headers
)
if not has_module(user, module):
return JSONResponse(
{"detail": "모듈 접근 권한이 없습니다."}, status_code=403, headers=headers
)
return JSONResponse(
{
"module": module,
"user": {
"email": user["email"],
"name": user.get("name", ""),
"role": user.get("role", "user"),
"is_super_admin": bool(user.get("is_super_admin")),
},
},
headers=headers,
)
# ── 관리자 페이지 ──────────────────────────────────────────────
@app.get("/admin", response_class=HTMLResponse)
async def admin_page(request: Request) -> HTMLResponse:
+7
View File
@@ -9,9 +9,13 @@
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널).
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
- HTML 편집기 `<img>` 안에서 커서 바로 뒤가 `.jpg`/`.gif`/`.png` 일 때 Ctrl+↑/↓ 로 파일명 번호 변경(없음 → `_2` → `_3` …, 내리면 `_2` 다음은 원래 이름, `_2`~`_99` 만 번호로 인식).
- 정보 패널(`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 전용).
## 규칙
@@ -19,6 +23,7 @@
- 카페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`)가 처리 — 웹 프로세스에서 대기하지 않는다.
## 읽기 지연 ("마지막 쓰기가 권위")
@@ -26,6 +31,8 @@
- **카페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).
+2 -2
View File
@@ -96,11 +96,11 @@ def guard(request: Request):
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
"""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, MODULE_KEY):
return render_template(
request,
+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": [...]}}
@@ -122,7 +122,7 @@
<input type="hidden" name="list_query" value="{{ list_query }}" />
<div class="cf24-editor-bar">
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del]</span>
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del] · 이미지 번호[Ctrl+↑↓]</span>
<span class="cf24-editor-bar-right">
<input class="cf24-memo" type="text" name="memo" maxlength="200"
placeholder="변경 메모 (버전 이력에 남습니다)" />
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
<link rel="stylesheet" href="/static/cafe24.css?v=20261103c" />
{% endblock %}
{% block content %}
@@ -122,10 +122,13 @@
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
</div>
</div>
{# 소스의 <img> 위에 마우스를 올리면 화면 오른쪽에 뜨는 미리보기 — setupCodeEditor 가 켜고 끈다. #}
<div class="cf24-img-preview" id="cf24-img-preview" hidden><div class="cf24-img-preview-name"></div><img alt="이미지를 불러올 수 없습니다" /></div>
{% 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");
@@ -164,14 +167,42 @@
last = TOKEN_RE.lastIndex;
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
out += '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
paintAttrs(m[5]) +
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
var tag = '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
paintAttrs(m[5]) +
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
out += /^img$/i.test(m[4]) ? '<span class="cf24-t-img">' + tag + "</span>" : tag;
}
return out + esc(src.slice(last));
}
// 상대 경로는 쇼핑몰 루트 기준이다: ../img/a.jpg → https://쇼핑몰/img/a.jpg
function imgPreviewUrl(tag) {
var m = tag.match(/\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
var src = m && (m[1] || m[2] || m[3]);
var shop = document.getElementById("cf24-url");
if (!src || !shop) return "";
try { return new URL(src, new URL("/", shop.value)).href; }
catch (err) { return ""; }
}
function imgFileName(url) {
var name = new URL(url).pathname.split("/").pop();
// URL 이 한글 파일명을 %XX 로 바꿔 놓으므로 되돌린다.
try { return decodeURIComponent(name); }
catch (err) { return name; }
}
function showImgPreview(url) {
var box = document.getElementById("cf24-img-preview");
var img = box.lastElementChild;
if (url && img.getAttribute("src") !== url) {
img.src = url;
box.firstElementChild.textContent = imgFileName(url);
}
box.hidden = !url;
}
function setupCodeEditor() {
var ta = document.getElementById("cf24-html-pc");
var hl = document.getElementById("cf24-hl-pc");
@@ -337,6 +368,47 @@
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
}
/* Ctrl+↑/↓ — <img> 안에서 커서 바로 뒤가 .jpg/.gif/.png 이면 파일명 번호를 바꾼다.
a.jpg → a_2.jpg → a_3.jpg …, 내릴 때는 _2 다음이 원래 이름. 커서는 확장자 앞에 그대로 둔다.
_2~_99 만 번호로 본다(product_2024.jpg 의 2024 는 번호가 아니다).
조건이 안 맞으면 false — 브라우저 기본 동작을 막지 않는다. */
function stepImgSuffix(up) {
var at = ta.selectionStart, value = ta.value;
if (at !== ta.selectionEnd || !/^\.(jpg|gif|png)/i.test(value.slice(at, at + 4))) return false;
var head = value.slice(value.lastIndexOf("<", at - 1), at);
if (!/^<img\s[^>]*$/i.test(head)) return false;
var m = head.match(/_([2-9]|[1-9]\d)$/);
var n = m ? Number(m[1]) : 1;
if (up ? n >= 99 : !m) return true; // 더 갈 곳이 없다
var next = up ? n + 1 : n - 1;
var text = next < 2 ? "" : "_" + next;
var from = at - (m ? m[0].length : 0);
applyEdit(from, at, text, from + text.length, from + text.length);
return true;
}
/* 이미지 미리보기 — 맨 위 textarea 를 판정에서 잠깐 빼고 색칠 층의 <img> 를 찾는다.
글자 폭을 계산하지 않아 한글·탭·여러 줄 태그에서도 위치가 어긋나지 않는다.
shortcut: HL_LIMIT 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
var hoverTag = null;
function setHoverTag(tag) {
if (tag === hoverTag) return;
if (hoverTag) hoverTag.classList.remove("cf24-t-img-on");
if (tag) tag.classList.add("cf24-t-img-on");
hoverTag = tag;
showImgPreview(tag ? imgPreviewUrl(tag.textContent) : "");
}
ta.addEventListener("mousemove", function (e) {
ta.style.pointerEvents = "none";
var el = document.elementFromPoint(e.clientX, e.clientY);
ta.style.pointerEvents = "";
setHoverTag(el && el.closest(".cf24-t-img"));
});
ta.addEventListener("mouseleave", function () { setHoverTag(null); });
ta.addEventListener("scroll", sync);
ta.addEventListener("input", function () { dirty = true; refresh(); });
ta.addEventListener("keydown", function (e) {
@@ -356,6 +428,10 @@
else moveLines(isDown);
return;
}
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (isUp || isDown) && stepImgSuffix(isUp)) {
e.preventDefault();
return;
}
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
(e.key === "Delete" || e.code === "Delete")) {
+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)
+66 -1
View File
@@ -746,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}
@@ -1127,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
# ════════════════════════════════════════════════════════════
# 기본 정보 · 옵션 · 품목 입력 검증
# ════════════════════════════════════════════════════════════
+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, ""
+32 -3
View File
@@ -15,10 +15,16 @@
- 양식 생성은 `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).
- 출고리스트 문서는 **구글 드라이브에 올린 .xlsx 파일**(`CUPANG_SHEET_ID`, 기본 `router.DEFAULT_SHEET_ID`
= `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`). `router._sheet_target` 이 드라이브에서 형식을 보고 writer 를 고른다:
- .xlsx → `app/integrations/drive_xlsx.py` — 내려받아 openpyxl 로 고친 뒤 같은 파일 id 에 다시 올림
(인증은 google_drive 와 같음: 서비스 계정 또는 `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN`/`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`, Drive 권한).
`with writer.lock:` 블록 = 내려받기 1번·올리기 1번. 올리기 직전 version 이 바뀌었으면(누가 고침) `_in_sheet` 가 처음부터 다시(3번).
- 구글 시트 문서 → 예전처럼 `google_sheets.py`(Sheets API). 드라이브 인증이 없을 때도 이쪽.
- 엑셀은 openpyxl 로 다시 저장하므로 파일 안 그림·차트는 사라진다(출고리스트에는 없음).
- 인증이 없으면 조용히 skip. 확정과 동시에 출고일 시트를 생성/덮어쓰기.
- 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제
(문서에 시트가 하나뿐이면 내용만 비움).
@@ -45,3 +51,26 @@
- 구글 시트 양식 xlsx·csv 업로드(`sales_import.py`) — 같은 발주번호+SKU+출고일+센터+수량은 덮어씀.
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
## 밀크런 출고리스트 작성 (팝업 → 드라이브 엑셀 파일, 2026-10-23)
- 첫 화면 "+ 신규 등록" 옆 엑셀색(#217346) 버튼 → 팝업(`index.html` + `static/cupang-outbound.js`).
팝업 높이 850px 고정(화면이 낮으면 화면 - 32px), 넘치면 팝업 안 스크롤, [취소]·[완료] 줄은 맨 아래(`.cpg-ol-box`).
상자 계산 없이 입고센터 여러 곳을 한 번에 **출고리스트 엑셀 파일에만** 적는다 — cupang_db 출고 묶음은 만들지 않는다(달력에 안 보임).
- 대상 파일은 `router._outbound_target` — `CUPANG_OUTBOUND_XLSX_ID`(기본 `DEFAULT_OUTBOUND_XLSX_ID` = `1J74op7lBZOgE27p4R28I3RWsv0EtXdii`),
항상 `drive_xlsx`. `CUPANG_SHEET_ID`(분배 확정 동기화)와 따로라 그게 구글 시트 문서여도 팝업은 엑셀에만 쓴다.
드라이브 인증이 없거나 파일이 .xlsx 가 아니면 구글 시트로 대신 쓰지 않고 503(사유 표시).
- 공통 입력: 작성일(기본 오늘)·출고일·센터입고일(출고일 고르면 +1일 자동)·작업자(기본 `export.WORKER`) — 날짜 칸은 프로젝트 날짜 팝업
(`PJLib.enhanceDateInput`, project.js 를 `PJ_LIB_ONLY` 로 로드).
- **입고센터 카드**(`#cpg-ol-center-tpl`, [+ 입고센터 추가]·[센터 삭제], 최대 20곳): 센터마다 입고센터(시트 F열 + 등록 센터, 직접 입력 가능),
출고방식(**기본 택배**/파렛트), 제품(코드표 `GET /cupang/api/products/all` 검색 → 코드·이름 자동, 수량 수기), 출고(수기).
카드 배경색은 센터마다 다르다(JS `recolor` → `data-tone` 0~7, 팝업에 나온 순서대로 배정·같은 센터는 같은 색·미선택은 회색, 색은 cupang.css).
- `POST /cupang/api/outbound-sheet` 본문 `{document_date, ship_date, center_arrival_date, worker, centers: [{center, ship_method, outbound, lines}]}`
(`centers` 없으면 본문 자체가 센터 1곳 — `_clean_outbound_entries`). 센터 순서대로 시트 `YYYYMMDD(요일)`(출고일) 맨 아래에
`export.build_block` 으로 덧붙임(순번 B열 이어짐, 파렛트 센터만 배경색). 시트가 없거나 5행 머리글이 없으면 첫 센터는 양식째 새로 쓴다(`write_table`).
전체가 `writer.lock` 한 덩어리 = 엑셀 내려받기 1번·올리기 1번(`_run_outbound_write`). 입고센터 후보는 `GET /cupang/api/outbound-sheet/centers`(10분 캐시).
- **진행 막대**: 팝업은 `?stream=1` 로 보내고 서버가 NDJSON 한 줄씩 `{progress, until, step}`(5 내려받기 → 40~80 센터별 추가 → 80 올리기)
… 마지막 `{done: true, ...결과}` 또는 `{error}`. 쓰기는 별도 스레드(잠금은 잡은 스레드에서 풀어야 함)가 하고 큐로 넘긴다.
화면은 단계 사이에도 다음 단계(until) 바로 앞까지 조금씩 채우고 %를 같이 표시, 실패면 빨강. 입력 오류(400)·설정 없음(503)은 스트림 전 보통 JSON.
- 주의: 같은 출고일에 [분배 확정]·출고 삭제가 일어나면 기존 동기화가 그 날짜 시트를 DB 기준으로 **통째로 다시 써서**
팝업으로 적은 줄이 사라진다.
+55 -30
View File
@@ -94,37 +94,15 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
row = FIRST_DATA_ROW
seq = 0
for sh in shipments:
lines = sh.get("lines") or []
if not lines:
block = build_block(sh, start_row=row, start_seq=seq)
if block is None:
continue
start = row
for ln in lines:
seq += 1
cells[(row, 2)] = seq
cells[(row, 8)] = ln.get("product_code") or ""
cells[(row, 9)] = ln.get("product_name_snapshot") or ""
cells[(row, 10)] = int(ln.get("quantity") or 0)
row += 1
end = row - 1
method = sh.get("ship_method") or ""
if method == PALLET_METHOD:
pallet_ranges.append((start, end))
block = {
# 날짜는 요일까지 표기 — 2026-09-03(목)
3: with_dow(str(sh.get("document_date") or "")),
4: with_dow(str(sh.get("ship_date") or "")),
5: with_dow(str(sh.get("center_arrival_date") or "")),
6: sh.get("center_name_snapshot") or "",
7: method,
11: sh.get("outbound_summary") or "",
12: WORKER,
}
for col in MERGE_COLS:
cells[(start, col)] = block[col]
if end > start:
merges.append((start, col, end, col))
cells.update(block["cells"])
merges.extend(block["merges"])
if block["is_pallet"]:
pallet_ranges.append((block["first_row"], block["last_row"]))
row = block["last_row"] + 1
seq = block["last_seq"]
return {
"title": title,
@@ -135,6 +113,53 @@ def build_table(ship_date: str, shipments: list[dict[str, Any]]) -> dict[str, An
}
def build_block(sh: dict[str, Any], *, start_row: int, start_seq: int) -> dict[str, Any] | None:
"""출고 묶음(센터) 1건 → start_row 부터 품목 1줄 = 1행. 품목이 없으면 None.
build_table(시트 전체)과 출고리스트 직접 작성(기존 시트 아래에 덧붙임)이 같이 쓴다.
순번(B열)은 start_seq 다음 번호부터 이어진다.
"""
lines = sh.get("lines") or []
if not lines:
return None
cells: dict[tuple[int, int], Any] = {}
merges: list[tuple[int, int, int, int]] = []
row, seq = start_row, start_seq
for ln in lines:
seq += 1
cells[(row, 2)] = seq
cells[(row, 8)] = ln.get("product_code") or ""
cells[(row, 9)] = ln.get("product_name_snapshot") or ""
cells[(row, 10)] = int(ln.get("quantity") or 0)
row += 1
end = row - 1
method = sh.get("ship_method") or ""
block = {
# 날짜는 요일까지 표기 — 2026-09-03(목)
3: with_dow(str(sh.get("document_date") or "")),
4: with_dow(str(sh.get("ship_date") or "")),
5: with_dow(str(sh.get("center_arrival_date") or "")),
6: sh.get("center_name_snapshot") or "",
7: method,
11: sh.get("outbound_summary") or "",
12: sh.get("worker") or WORKER,
}
for col in MERGE_COLS:
cells[(start_row, col)] = block[col]
if end > start_row:
merges.append((start_row, col, end, col))
return {
"cells": cells,
"merges": merges,
"first_row": start_row,
"last_row": end,
"last_seq": seq,
"is_pallet": method == PALLET_METHOD,
}
def build_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
"""xlsx 워크북(openpyxl). 시트명 = YYYYMMDD(요일)."""
from openpyxl import Workbook
+395 -33
View File
@@ -22,6 +22,7 @@ from app.timezone import today_kst
from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from .export import WORKER as OUTBOUND_WORKER
from .holidays import holiday_name, is_holiday
from .store import SHIP_METHODS, parse_weight_g
@@ -74,11 +75,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, "cupang"):
return render_template(
request,
@@ -222,6 +223,7 @@ def index(request: Request) -> HTMLResponse:
"months": months,
"selected_date": sel,
"sel_shipments": sel_shipments,
"outbound_worker": OUTBOUND_WORKER,
},
)
@@ -243,21 +245,57 @@ def _shipments_for_date(store: Any, ship_date: str) -> list[dict[str, Any]]:
return out
# 출고리스트 문서 — 구글 드라이브에 올려 둔 엑셀(.xlsx) 파일(2026-10-23). 구글 시트 문서여도 된다.
DEFAULT_SHEET_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
def _sheet_target(store: Any) -> tuple[Any, str, dict[str, Any] | None]:
"""(writer, spreadsheet_id, skip 사유) — 설정이 없으면 skip 정보를 돌려준다."""
"""(writer, 문서 id, skip 사유) — 쓸 수 없으면 skip 정보를 돌려준다.
문서 형식은 드라이브에서 보고 고른다 — .xlsx 파일이면 drive_xlsx(내려받아 고친 뒤 다시 올림),
구글 시트 문서면 google_sheets. 두 writer 는 같은 메서드를 갖는다."""
import os # noqa: WPS433
from app.integrations.google_sheets import get_writer # noqa: WPS433
from app.integrations import drive_xlsx, google_sheets # noqa: WPS433
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip()
if not spreadsheet_id:
return None, "", {"ok": False, "skipped": True, "reason": "CUPANG_SHEET_ID 미설정"}
writer = get_writer()
spreadsheet_id = (os.getenv("CUPANG_SHEET_ID") or "").strip() or DEFAULT_SHEET_ID
drive = drive_xlsx.get_writer()
if not drive.enabled:
# 드라이브 인증이 없으면 예전처럼 Sheets API 로(구글 시트 문서일 때만 된다)
writer = google_sheets.get_writer()
if not writer.enabled:
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
return writer, spreadsheet_id, None
try:
kind = drive.file_kind(spreadsheet_id)
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
if kind == "xlsx":
return drive, spreadsheet_id, None
if kind != "sheets":
return None, "", {"ok": False, "skipped": True, "reason": f"엑셀·구글 시트 파일이 아닙니다({kind})"}
writer = google_sheets.get_writer()
if not writer.enabled:
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
return writer, spreadsheet_id, None
def _in_sheet(writer: Any, fn: Any) -> Any:
"""`with writer.lock:` 안에서 fn() — 읽기~쓰기를 한 덩어리로.
엑셀 파일(drive_xlsx)은 내려받은 뒤 올리기 전에 누가 파일을 고쳤으면 처음부터 다시(최대 3번)."""
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
for attempt in range(3):
try:
with writer.lock:
return fn()
except XlsxChangedError:
if attempt == 2:
raise
return None
def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any]:
"""출고 삭제 후 구글 시트를 현재 상태에 맞춘다.
@@ -275,7 +313,8 @@ def _sync_google_sheet_after_delete(store: Any, ship_date: str) -> dict[str, Any
return _push_to_google_sheet(store, ship_date)
try:
res = writer.delete_sheet(spreadsheet_id=spreadsheet_id, title=sheet_title(ship_date))
res = _in_sheet(writer, lambda: writer.delete_sheet(spreadsheet_id=spreadsheet_id,
title=sheet_title(ship_date)))
except Exception as exc: # noqa: BLE001 - 사유만 남긴다
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
return {"ok": True, "skipped": False, **res}
@@ -291,17 +330,12 @@ def _log_sheet(action: str, ship_date: str, res: dict[str, Any]) -> None:
def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
"""확정한 출고일을 Google 스프레드시트에 시트 1장으로 기록.
"""확정한 출고일을 출고리스트 문서(드라이브 엑셀 또는 구글 시트)에 시트 1장으로 기록.
- 대상 스프레드시트: 환경변수 `CUPANG_SHEET_ID`
- 인증: 서비스 계정(app/integrations/google_sheets.py). 미설정이면 조용히 skip.
- 대상 문서: 환경변수 `CUPANG_SHEET_ID`(기본 DEFAULT_SHEET_ID), 형식은 `_sheet_target` 이 고른다.
- 인증: 서비스 계정 또는 OAuth(app/integrations/drive_xlsx.py·google_sheets.py). 미설정이면 조용히 skip.
- 실패해도 출고 묶음 저장은 이미 끝났으므로 예외를 밖으로 던지지 않는다.
"""
from .export import ( # noqa: WPS433
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
)
writer, spreadsheet_id, skip = _sheet_target(store)
if skip:
return skip
@@ -310,28 +344,356 @@ def _push_to_google_sheet(store: Any, ship_date: str) -> dict[str, Any]:
if not shipments:
return {"ok": False, "skipped": True, "reason": "해당 출고일의 출고 묶음 없음"}
table = build_table(ship_date, shipments)
try:
res = writer.write_table(
spreadsheet_id=spreadsheet_id,
title=sheet_title(ship_date),
cells=table["cells"],
merges=table["merges"],
header_row=HEADER_ROW,
first_data_row=FIRST_DATA_ROW,
last_row=table["last_row"],
first_col=COL_FIRST,
last_col=COL_LAST,
title_row=TITLE_ROW,
widths=WIDTHS_PX,
header_bg=HEADER_BG,
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
)
res = _in_sheet(writer, lambda: _write_full_sheet(writer, spreadsheet_id, ship_date, shipments))
except Exception as exc: # noqa: BLE001 - 시트 기록 실패는 경고로만 알린다
return {"ok": False, "skipped": False, "reason": f"{type(exc).__name__}: {exc}"}
return {"ok": True, "skipped": False, **res}
def _write_full_sheet(
writer: Any, spreadsheet_id: str, ship_date: str, shipments: list[dict[str, Any]]
) -> dict[str, Any]:
"""출고일 시트를 양식(1~5행)부터 통째로 다시 쓴다. 실패는 예외로 알린다."""
from .export import ( # noqa: WPS433
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_BG, HEADER_ROW, PALLET_BG,
TITLE_ROW, WIDTHS_PX, build_table, sheet_title,
)
table = build_table(ship_date, shipments)
res = writer.write_table(
spreadsheet_id=spreadsheet_id,
title=sheet_title(ship_date),
cells=table["cells"],
merges=table["merges"],
header_row=HEADER_ROW,
first_data_row=FIRST_DATA_ROW,
last_row=table["last_row"],
first_col=COL_FIRST,
last_col=COL_LAST,
title_row=TITLE_ROW,
widths=WIDTHS_PX,
header_bg=HEADER_BG,
row_highlights=[(r1, r2, PALLET_BG) for (r1, r2) in table["pallet_ranges"]],
)
return {**res, "first_row": FIRST_DATA_ROW, "last_row": table["last_row"]}
# ════════════════════════════════════════════════════════════
# 밀크런 출고리스트 직접 작성 — 상자 계산 없이 팝업에서 입력한 센터 1곳을
# 출고리스트 문서(드라이브 엑셀 파일)의 출고일 시트(YYYYMMDD(요일)) 맨 아래에 덧붙인다. cupang_db 에는 저장하지 않는다.
# ════════════════════════════════════════════════════════════
OUTBOUND_SHEET_METHODS: tuple[str, ...] = ("파렛트", "택배")
_SHEET_CENTERS_TTL_SECONDS = 600
_sheet_centers_cache: dict[str, Any] = {"at": 0.0, "sheet": "", "names": []}
# 팝업이 쓰는 문서 — 항상 드라이브 엑셀(.xlsx) 파일. CUPANG_SHEET_ID(분배 확정 동기화)와 따로 둔다:
# 서버의 CUPANG_SHEET_ID 가 구글 시트 문서를 가리켜도 팝업은 엑셀 파일에만 쓴다(구글 시트로 대신 쓰지 않음).
DEFAULT_OUTBOUND_XLSX_ID = "1J74op7lBZOgE27p4R28I3RWsv0EtXdii"
def _outbound_target() -> tuple[Any, str, dict[str, Any] | None]:
"""(drive_xlsx writer, 엑셀 파일 id, skip 사유). 드라이브 인증이 없거나 .xlsx 가 아니면 skip."""
import os # noqa: WPS433
from app.integrations import drive_xlsx # noqa: WPS433
file_id = (os.getenv("CUPANG_OUTBOUND_XLSX_ID") or "").strip() or DEFAULT_OUTBOUND_XLSX_ID
writer = drive_xlsx.get_writer()
if not writer.enabled:
return None, "", {"ok": False, "skipped": True, "reason": writer.reason}
try:
kind = writer.file_kind(file_id)
except Exception as exc: # noqa: BLE001 - 사유만(비밀값 없음)
return None, "", {"ok": False, "skipped": True, "reason": str(exc) or type(exc).__name__}
if kind != "xlsx":
return None, "", {"ok": False, "skipped": True, "reason": f"출고리스트 파일이 엑셀(.xlsx)이 아닙니다({kind})"}
return writer, file_id, None
def _sheet_text(value: Any, *, label: str, max_len: int, required: bool = True) -> str:
text = str(value or "").strip()
if required and not text:
raise HTTPException(status_code=400, detail=f"{label}을(를) 입력해 주세요.")
if len(text) > max_len:
raise HTTPException(status_code=400, detail=f"{label}은(는) {max_len}자까지 입력할 수 있습니다.")
# USER_ENTERED 로 쓰므로 '=' 로 시작하면 수식이 된다 — 글자 그대로 남긴다.
return "'" + text if text.startswith("=") else text
def _sheet_date(value: Any, *, label: str) -> str:
try:
return _date.fromisoformat(str(value or "").strip()).isoformat()
except ValueError:
raise HTTPException(status_code=400, detail=f"{label}을(를) 선택해 주세요.") from None
def _clean_outbound_entry(payload: dict[str, Any]) -> dict[str, Any]:
"""팝업 입력 → export.build_block 이 읽는 출고 묶음 모양."""
method = str(payload.get("ship_method") or "").strip()
if method not in OUTBOUND_SHEET_METHODS:
raise HTTPException(status_code=400, detail="출고방식은 파렛트 또는 택배 중에서 골라 주세요.")
raw_lines = payload.get("lines")
if not isinstance(raw_lines, list) or not raw_lines:
raise HTTPException(status_code=400, detail="제품을 1개 이상 추가해 주세요.")
if len(raw_lines) > 100:
raise HTTPException(status_code=400, detail="제품은 한 번에 100줄까지 입력할 수 있습니다.")
lines = []
for i, ln in enumerate(raw_lines, start=1):
if not isinstance(ln, dict):
raise HTTPException(status_code=400, detail=f"{i}번째 제품 정보를 확인해 주세요.")
try:
qty = int(str(ln.get("quantity") or "").replace(",", "").strip())
except ValueError:
qty = 0
if not 1 <= qty <= 1_000_000:
raise HTTPException(status_code=400, detail=f"{i}번째 제품의 수량을 확인해 주세요.")
lines.append({
"product_code": _sheet_text(ln.get("code"), label=f"{i}번째 제품코드", max_len=60),
"product_name_snapshot": _sheet_text(ln.get("name"), label=f"{i}번째 제품명", max_len=200),
"quantity": qty,
})
return {
"document_date": _sheet_date(payload.get("document_date"), label="작성일"),
"ship_date": _sheet_date(payload.get("ship_date"), label="출고일"),
"center_arrival_date": _sheet_date(payload.get("center_arrival_date"), label="센터입고일"),
"center_name_snapshot": _sheet_text(payload.get("center"), label="입고센터", max_len=60),
"ship_method": method,
"outbound_summary": _sheet_text(payload.get("outbound"), label="출고", max_len=100, required=False),
"worker": _sheet_text(payload.get("worker") or OUTBOUND_WORKER, label="작업자", max_len=30),
"lines": lines,
}
def _sheet_centers(writer: Any, spreadsheet_id: str) -> list[str]:
"""출고리스트 문서의 모든 시트 F열(입고센터, 6행부터)에 적힌 센터 이름. 10분 캐시."""
import time # noqa: WPS433
from app.integrations.google_sheets import a1_sheet # noqa: WPS433
from .export import FIRST_DATA_ROW # noqa: WPS433
cache = _sheet_centers_cache
if cache["sheet"] == spreadsheet_id and time.monotonic() - cache["at"] < _SHEET_CENTERS_TTL_SECONDS:
return list(cache["names"])
with writer.lock: # 엑셀 파일이면 한 번만 내려받는다
titles = writer.sheet_titles(spreadsheet_id=spreadsheet_id)
columns = writer.read_ranges(
spreadsheet_id=spreadsheet_id,
ranges=[f"{a1_sheet(t)}!F{FIRST_DATA_ROW}:F" for t in titles],
)
names = sorted({
str(row[0]).strip() for rows in columns for row in rows if row and str(row[0]).strip()
})
cache.update(at=time.monotonic(), sheet=spreadsheet_id, names=names)
return list(names)
def _append_outbound_entry(writer: Any, spreadsheet_id: str, entry: dict[str, Any]) -> dict[str, Any]:
"""출고일 시트 맨 아래에 덧붙인다. 시트가 없거나 양식(5행 머리글)이 없으면 양식째 만든다."""
from app.integrations.google_sheets import a1_sheet, col_letter # noqa: WPS433
from .export import ( # noqa: WPS433
COL_FIRST, COL_LAST, FIRST_DATA_ROW, HEADER_ROW, PALLET_BG, build_block, sheet_title,
)
title = sheet_title(entry["ship_date"])
rows: list[list[Any]] = []
if title in writer.sheet_titles(spreadsheet_id=spreadsheet_id):
rows = writer.read_ranges(
spreadsheet_id=spreadsheet_id,
ranges=[f"{a1_sheet(title)}!A1:{col_letter(COL_LAST)}"],
)[0]
last_row = max(
(i for i, row in enumerate(rows, start=1) if any(str(v).strip() for v in row)), default=0
)
if last_row < HEADER_ROW:
return _write_full_sheet(writer, spreadsheet_id, entry["ship_date"], [entry])
# 순번(B열)은 시트에 이미 있는 가장 큰 번호 다음부터
last_seq = 0
for row in rows[FIRST_DATA_ROW - 1:]:
text = str(row[1]).strip() if len(row) > 1 else ""
if text.isdigit():
last_seq = max(last_seq, int(text))
block = build_block(entry, start_row=last_row + 1, start_seq=last_seq)
return writer.append_block(
spreadsheet_id=spreadsheet_id,
title=title,
cells=block["cells"],
merges=block["merges"],
first_row=block["first_row"],
last_row=block["last_row"],
first_col=COL_FIRST,
last_col=COL_LAST,
highlight=PALLET_BG if block["is_pallet"] else "",
)
@router.get("/api/outbound-sheet/centers")
def outbound_sheet_centers(
request: Request, _: dict[str, Any] = Depends(_require_user)
) -> JSONResponse:
"""입고센터 후보 — 출고리스트 문서에 적힌 센터 + 설정에 등록된 센터."""
store = _store(request)
names = {c["name"] for c in store.list_centers()} if store else set()
reason = ""
writer, spreadsheet_id, skip = _outbound_target()
if skip:
reason = str(skip.get("reason") or "")
else:
try:
names.update(_sheet_centers(writer, spreadsheet_id))
except Exception as exc: # noqa: BLE001 - 목록은 등록 센터만으로도 쓸 수 있다
reason = f"출고리스트 파일을 읽지 못했습니다({str(exc) or type(exc).__name__})"
return JSONResponse({"centers": sorted(names), "reason": reason})
_OUTBOUND_MAX_CENTERS = 20
def _clean_outbound_entries(payload: dict[str, Any]) -> list[dict[str, Any]]:
"""팝업 입력 → 입고센터마다 출고 묶음 1건.
공통(작성일·출고일·센터입고일·작업자) + `centers: [{center, ship_method, outbound, lines}]`.
`centers` 가 없으면 payload 자체를 센터 1곳으로 본다."""
raw = payload.get("centers")
if raw is None:
return [_clean_outbound_entry(payload)]
if not isinstance(raw, list) or not raw:
raise HTTPException(status_code=400, detail="입고센터를 1곳 이상 추가해 주세요.")
if len(raw) > _OUTBOUND_MAX_CENTERS:
raise HTTPException(status_code=400, detail=f"입고센터는 한 번에 {_OUTBOUND_MAX_CENTERS}곳까지 입력할 수 있습니다.")
common = {k: payload.get(k) for k in ("document_date", "ship_date", "center_arrival_date", "worker")}
entries = []
for i, c in enumerate(raw, start=1):
if not isinstance(c, dict):
raise HTTPException(status_code=400, detail=f"{i}번째 입고센터 정보를 확인해 주세요.")
try:
entries.append(_clean_outbound_entry({**c, **common}))
except HTTPException as exc:
prefix = f"{i}번째 입고센터: " if len(raw) > 1 else ""
raise HTTPException(status_code=exc.status_code, detail=prefix + str(exc.detail)) from None
return entries
def _run_outbound_write(
writer: Any, file_id: str, entries: list[dict[str, Any]], report: Any
) -> dict[str, Any]:
"""센터들을 차례로 출고일 시트 아래에 덧붙인다(엑셀은 내려받기·올리기 1번씩).
report(진행률, 다음 단계 진행률, 단계 이름) 로 진행 상황을 알린다. 실패는 HTTPException(502)."""
from app.integrations.drive_xlsx import XlsxChangedError # noqa: WPS433
from app.integrations.google_drive import GoogleDriveError # noqa: WPS433
ship_date = entries[0]["ship_date"]
n = len(entries)
def run() -> list[dict[str, Any]]:
report(5, 40, "출고리스트 엑셀 내려받는 중")
writer.sheet_titles(spreadsheet_id=file_id) # 이 덩어리에서 한 번 내려받는다
done = []
for i, entry in enumerate(entries):
report(40 + 40 * i // n, 40 + 40 * (i + 1) // n,
f"{entry['center_name_snapshot']} 추가 중 ({i + 1}/{n})")
done.append(_append_outbound_entry(writer, file_id, entry))
report(80, 100, "출고리스트 엑셀 올리는 중")
return done
try:
# 시트 끝 위치를 읽고 쓰는 사이에 다른 요청이 끼어들지 않게 한 덩어리로
results = _in_sheet(writer, run)
except Exception as exc: # noqa: BLE001 - 사유만 남긴다(비밀값 미출력)
_log_sheet("manual-append", ship_date, {"ok": False, "reason": type(exc).__name__})
if isinstance(exc, XlsxChangedError):
why = "다른 사람이 파일을 고치는 중입니다"
elif isinstance(exc, GoogleDriveError):
why = str(exc)
else:
why = type(exc).__name__
raise HTTPException(
status_code=502, detail=f"출고리스트 파일에 기록하지 못했습니다({why}). 잠시 후 다시 시도해 주세요."
) from exc
first, last = results[0], results[-1]
_log_sheet("manual-append", ship_date,
{"ok": True, "action": f"xlsx {file_id} centers {n} rows {first.get('first_row')}-{last.get('last_row')}"})
if _sheet_centers_cache["sheet"] == file_id:
_sheet_centers_cache["names"] = sorted(
{*_sheet_centers_cache["names"], *(e["center_name_snapshot"] for e in entries)})
return {
"ok": True,
"title": last.get("title"),
"url": last.get("url"),
"first_row": first.get("first_row"),
"last_row": last.get("last_row"),
"line_count": sum(len(e["lines"]) for e in entries),
"centers": [
{"center": e["center_name_snapshot"], "first_row": r.get("first_row"), "last_row": r.get("last_row"),
"line_count": len(e["lines"])}
for e, r in zip(entries, results)
],
}
@router.post("/api/outbound-sheet")
def outbound_sheet_write(
request: Request,
payload: dict[str, Any] = Body(...),
stream: bool = False,
_: dict[str, Any] = Depends(_require_user),
) -> Any:
"""출고리스트 엑셀에 센터들을 덧붙인다.
`?stream=1` 이면 한 줄에 JSON 하나씩(NDJSON) 진행 상황을 흘려보낸다 —
`{"progress", "until", "step"}` … 마지막에 `{"done": true, ...결과}` 또는 `{"error": 사유}`.
입력 오류(400)·설정 없음(503)은 흘려보내기 전에 보통 JSON 오류로 돌려준다."""
entries = _clean_outbound_entries(payload)
writer, file_id, skip = _outbound_target()
if skip:
_log_sheet("manual-append", entries[0]["ship_date"], skip)
raise HTTPException(
status_code=503, detail=f"출고리스트 엑셀 파일에 쓸 수 없습니다: {skip.get('reason') or '설정 확인 필요'}"
)
if not stream:
return JSONResponse(_run_outbound_write(writer, file_id, entries, lambda *_a: None))
import queue # noqa: WPS433
import threading # noqa: WPS433
from fastapi.responses import StreamingResponse # noqa: WPS433
events: Any = queue.Queue()
def work() -> None:
# 잠금(writer.lock)은 잡은 스레드에서 풀어야 하므로 쓰기 전체를 스레드 하나에서
try:
res = _run_outbound_write(
writer, file_id, entries,
lambda p, until, step: events.put({"progress": p, "until": until, "step": step}),
)
events.put({"progress": 100, "until": 100, "step": "완료", "done": True, **res})
except HTTPException as exc:
events.put({"error": str(exc.detail)})
except Exception as exc: # noqa: BLE001
events.put({"error": f"출고리스트 파일에 기록하지 못했습니다({type(exc).__name__})."})
finally:
events.put(None)
threading.Thread(target=work, name="cupang-outbound-write", daemon=True).start()
def lines() -> Any:
while True:
item = events.get()
if item is None:
return
yield json.dumps(item, ensure_ascii=False) + "\n"
return StreamingResponse(lines(), media_type="application/x-ndjson",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
@router.get("/export.xlsx")
def export_shipments_xlsx(request: Request, date: str = "") -> Any:
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
+80 -1
View File
@@ -1,6 +1,12 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
{% block head_extra %}
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %}
{% block content %}
<section class="cpg">
@@ -9,6 +15,7 @@
<div class="cpg-actions-grid">
<div class="cpg-actions-main">
<a class="erp-btn erp-btn-primary" href="/cupang/box-calc">+ 신규 등록</a>
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-open">밀크런 출고리스트 작성</button>
<span class="cpg-settings-btns">
<a class="erp-btn erp-btn-outline cpg-sales-link" href="/cupang/sales">쿠팡 로켓 매출</a>
<a class="erp-btn erp-btn-outline" href="/cupang/products">제품명 설정</a>
@@ -168,10 +175,82 @@
<input type="hidden" name="next" id="cpg-del-next" />
</form>
<!-- 밀크런 출고리스트 작성 팝업 — 완료하면 출고리스트 엑셀(구글 드라이브 .xlsx) 출고일 시트 아래에 덧붙인다 -->
<div class="cpg-modal" id="cpg-ol-dlg" hidden>
<div class="cpg-modal-back" data-ol-close></div>
<div class="cpg-modal-box cpg-ol-box" role="dialog" aria-modal="true" aria-labelledby="cpg-ol-title">
<h3 id="cpg-ol-title">밀크런 출고리스트 작성</h3>
<div class="cpg-ol-grid cpg-ol-grid-4">
<div class="erp-field"><span>작성일</span><input type="date" id="cpg-ol-doc-date" /></div>
<div class="erp-field"><span>출고일</span><input type="date" id="cpg-ol-ship-date" /></div>
<div class="erp-field"><span>센터입고일</span><input type="date" id="cpg-ol-arrival-date" /></div>
<label class="erp-field"><span>작업자</span>
<input class="erp-input" type="text" id="cpg-ol-worker" maxlength="30" value="{{ outbound_worker }}" /></label>
</div>
<!-- 입고센터 카드 — 센터마다 출고방식·제품·출고를 따로 입력(cupang-outbound.js 가 템플릿으로 만든다) -->
<div class="cpg-ol-centers" id="cpg-ol-centers"></div>
<button type="button" class="erp-btn erp-btn-outline cpg-ol-add-center" id="cpg-ol-add-center">+ 입고센터 추가</button>
<template id="cpg-ol-center-tpl">
<section class="cpg-ol-center">
<header class="cpg-ol-center-head">
<strong class="cpg-ol-center-no">입고센터 1</strong>
<button type="button" class="cpg-icon-btn is-danger cpg-ol-center-del">센터 삭제</button>
</header>
<div class="cpg-ol-grid">
<label class="erp-field"><span>입고센터</span>
<select class="erp-select cpg-ol-center-sel"><option value="">불러오는 중…</option></select></label>
<label class="erp-field"><span>출고방식</span>
<select class="erp-select cpg-ol-method">
<option value="택배">택배</option>
<option value="파렛트">파렛트</option>
</select></label>
<label class="erp-field"><span>출고</span>
<input class="erp-input cpg-ol-outbound" type="text" maxlength="100" placeholder="예) 2파렛트, 15박스" /></label>
<label class="erp-field cpg-ol-center-custom" hidden><span>새 입고센터</span>
<input class="erp-input cpg-ol-center-new" type="text" maxlength="60" placeholder="센터 이름" /></label>
</div>
<div class="erp-field"><span>제품 (코드표에서 검색해 추가)</span>
<div class="cpg-ol-search">
<input class="erp-input cpg-ol-search-input" type="search" autocomplete="off"
placeholder="제품코드 또는 제품명으로 검색" />
<ul class="cpg-ol-results" hidden></ul>
</div>
</div>
<table class="cpg-ol-lines" hidden>
<thead><tr><th>제품코드</th><th>제품명</th><th>수량</th><th></th></tr></thead>
<tbody></tbody>
</table>
<p class="erp-muted cpg-ol-empty">위 검색창에서 제품을 골라 추가하세요.</p>
</section>
</template>
<p class="erp-muted cpg-ol-target" id="cpg-ol-target"></p>
<div class="cpg-ol-progress" id="cpg-ol-progress" hidden>
<div class="cpg-ol-progress-top">
<span id="cpg-ol-progress-step">준비 중</span>
<b id="cpg-ol-progress-pct">0%</b>
</div>
<div class="cpg-ol-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"
aria-label="기록 진행률" id="cpg-ol-progress-track">
<div class="cpg-ol-progress-bar" id="cpg-ol-progress-bar"></div>
</div>
</div>
<p class="cpg-ol-error" id="cpg-ol-error" hidden></p>
<div class="cpg-ol-actions">
<button type="button" class="erp-btn erp-btn-outline" data-ol-close>취소</button>
<button type="button" class="erp-btn cpg-btn-excel" id="cpg-ol-submit">완료</button>
</div>
</div>
</div>
</section>
{% endblock %}
{% block scripts %}
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
<script>
(function () {
var dlg = document.getElementById("cpg-del-dlg");
+1
View File
@@ -10,4 +10,5 @@
- 작업 상태 토글(`dispatch_logs` 기록).
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 세트는 BOM 으로 낱개 분해) + 아이템×날짜 요약 시트 + 세트×날짜 요약 시트(낱개로 풀기 전 세트 수량).
- 엑셀은 openpyxl 파싱/생성.
+35
View File
@@ -309,6 +309,41 @@ class DispatchStore:
for r in rows
]
def shipped_by_date_range(
self, *, date_from: str, date_to: str
) -> list[dict[str, Any]]:
"""기간(양끝 포함) 날짜·SKU별 합산 수량 — 기간별 발송 수량 엑셀용.
반환: [{"dispatch_date": "YYYY-MM-DD", "seller_sku", "product_name", "qty"}].
_N 배수 반영은 호출부(export)에서 한다.
"""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT b.dispatch_date, i.seller_sku,
MAX(i.product_name) AS product_name,
SUM(i.quantity)::int AS qty
FROM dispatch_items i
JOIN dispatch_parcels p ON p.id = i.parcel_id
JOIN dispatch_batches b ON b.id = p.batch_id
WHERE b.dispatch_date BETWEEN %s AND %s
GROUP BY b.dispatch_date, i.seller_sku
ORDER BY b.dispatch_date ASC, i.seller_sku ASC
""",
(date_from, date_to),
).fetchall()
return [
{
"dispatch_date": r["dispatch_date"].isoformat()
if isinstance(r["dispatch_date"], date)
else str(r["dispatch_date"] or ""),
"seller_sku": r["seller_sku"] or "",
"product_name": r["product_name"] or "",
"qty": int(r["qty"] or 0),
}
for r in rows
]
# ════════════════════════════════════════════════════════════
# 말레이시아 재고 차감 1회성 가드
# ════════════════════════════════════════════════════════════
+152
View File
@@ -246,6 +246,158 @@ def stock_filename(dispatch_date: str) -> str:
return f"{stamp}_sabangnet_outbound.xlsx"
# ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
def missing_set_boms(
rows: list[dict[str, Any]], set_bom: dict[str, list[dict[str, Any]]]
) -> list[str]:
"""세트(MY-)인데 BOM 이 없어 낱개로 풀 수 없는 코드 목록(정렬)."""
return sorted({
b for b in (split_sku(r.get("seller_sku", ""))[0].strip().upper() for r in rows)
if b.startswith(_SET_PREFIX) and b not in set_bom
})
def aggregate_shipped(
rows: list[dict[str, Any]],
name_map: dict[str, str] | None = None,
set_bom: dict[str, list[dict[str, Any]]] | None = None,
) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]:
"""날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}).
seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다
(예: MT-0320_3 × 2 → MT-0320 6개). 세트(set_bom 에 있는 코드)는 구성 낱개로
풀어 (수량 × 구성수량) 을 낱개 코드에 더한다.
"""
name_map = name_map or {}
set_bom = set_bom or {}
dates: set[str] = set()
names: dict[str, str] = {}
qty: dict[tuple[str, str], int] = {}
def _add(d: str, code: str, n: int, fallback: str) -> None:
key = (d, code)
qty[key] = qty.get(key, 0) + n
if not names.get(code):
names[code] = resolve_product_name(code, name_map, fallback=fallback)
for r in rows:
base, mult = split_sku(r.get("seller_sku", ""))
code = base.strip().upper()
if not code:
continue
pieces = int(r.get("qty", 0) or 0) * mult
if pieces <= 0:
continue
d = r.get("dispatch_date", "") or ""
dates.add(d)
comps = set_bom.get(code)
if comps: # 세트 → 낱개 분해
for c in comps:
cc = str(c.get("component_code", "")).strip().upper()
n = pieces * int(c.get("component_qty", 0) or 0)
if cc and n > 0:
_add(d, cc, n, "")
else:
_add(d, code, pieces, r.get("product_name", "") or "")
return sorted(dates), names, qty
def build_period_xlsx(
*,
rows: list[dict[str, Any]],
date_from: str,
date_to: str,
name_map: dict[str, str] | None = None,
set_bom: dict[str, list[dict[str, Any]]] | None = None,
) -> bytes:
"""기간별 발송 수량 xlsx(세트는 낱개로 풀어 합산). 시트 3개.
- 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계)
- 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행)
- 「세트별 요약」: 세트 코드 / 상품이름 / 날짜1..N / 합계 — 낱개로 풀기 전 세트 단위 수량
"""
from openpyxl import Workbook # noqa: WPS433
from openpyxl.styles import Alignment, Font, PatternFill
from openpyxl.utils import get_column_letter
set_bom = set_bom or {}
dates, names, qty = aggregate_shipped(rows, name_map, set_bom)
codes = sorted(names)
# 세트 행만 BOM 없이 다시 합산하면 세트 단위 수량이 된다(_N 배수 반영은 같다).
set_rows = [r for r in rows if split_sku(r.get("seller_sku", ""))[0].strip().upper() in set_bom]
_sd, set_names, set_qty = aggregate_shipped(set_rows, name_map)
head_fill = PatternFill("solid", fgColor="E2E8F0")
head_font = Font(bold=True)
bold = Font(bold=True)
def _style_head(ws: Any) -> None:
for cell in ws[1]:
cell.fill = head_fill
cell.font = head_font
cell.alignment = Alignment(horizontal="center", vertical="center")
ws.freeze_panes = "A2"
wb = Workbook()
# 시트 1 — 날짜별 목록
ws = wb.active
ws.title = "날짜별"
headers = ["발송 날짜", "아이템 코드", "상품이름", "수량"]
ws.append(headers)
total = 0
for d in dates:
for code in codes:
n = qty.get((d, code))
if not n:
continue
ws.append([d, code, names.get(code, ""), n])
total += n
ws.append(["합계", "", "", total])
for cell in ws[ws.max_row]:
cell.font = bold
_style_head(ws)
_autosize(ws, headers)
# 시트 2·3 — 코드(행) × 날짜(열) 요약. 날짜 열은 두 시트 모두 전체 발송 날짜로 맞춘다.
def _pivot(title: str, code_label: str, p_names: dict[str, str],
p_qty: dict[tuple[str, str], int]) -> None:
p_codes = sorted(p_names)
ws2 = wb.create_sheet(title)
headers2 = [code_label, "상품이름", *dates, "합계"]
ws2.append(headers2)
for code in p_codes:
per_day = [p_qty.get((d, code), 0) for d in dates]
ws2.append([code, p_names.get(code, ""), *[n or None for n in per_day], sum(per_day)])
day_totals = [sum(p_qty.get((d, c), 0) for c in p_codes) for d in dates]
ws2.append(["합계", "", *day_totals, sum(day_totals)])
for cell in ws2[ws2.max_row]:
cell.font = bold
_style_head(ws2)
ws2.freeze_panes = "C2"
_autosize(ws2, headers2)
for i in range(3, len(headers2) + 1): # 날짜 열은 좁게 고정
ws2.column_dimensions[get_column_letter(i)].width = 12
_pivot("아이템별 요약", "아이템 코드", names, qty)
_pivot("세트별 요약", "세트 코드", set_names, set_qty)
wb.properties.title = f"말레이시아 발송 수량 {date_from} ~ {date_to}"
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
def period_filename(date_from: str, date_to: str) -> str:
"""기간별 발송 수량 파일명: 2026.10.01-2026.10.28_shipped_qty.xlsx."""
def _stamp(v: str) -> str:
d = _parse_date(v)
return d.strftime("%Y.%m.%d") if d else (v or "").strip()
return f"{_stamp(date_from)}-{_stamp(date_to)}_shipped_qty.xlsx"
def _cell(value: Any) -> Any:
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
if isinstance(value, int):
+68 -2
View File
@@ -131,11 +131,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
def _guard(request: Request):
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, "dispatch"):
return render_template(
request,
@@ -477,6 +477,72 @@ def stock_export(
)
_PERIOD_MAX_DAYS = 366
@router.get("/period-export")
def period_export(
request: Request,
date_from: str,
date_to: str,
user: dict[str, Any] = Depends(_require_user),
) -> Response:
"""기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용.
seller_sku 의 _N 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개로 풀어 합산.
"""
if not bool(user.get("is_super_admin")):
raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.")
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="dispatch_db 미설정")
d_from = export._parse_date(date_from)
d_to = export._parse_date(date_to)
if d_from is None or d_to is None:
raise HTTPException(status_code=400, detail="시작일·종료일을 YYYY-MM-DD 로 입력하세요.")
if d_from > d_to:
d_from, d_to = d_to, d_from
if (d_to - d_from).days + 1 > _PERIOD_MAX_DAYS:
raise HTTPException(status_code=400, detail=f"기간은 최대 {_PERIOD_MAX_DAYS}일까지 가능합니다.")
f, t = d_from.isoformat(), d_to.isoformat()
rows = st.shipped_by_date_range(date_from=f, date_to=t)
if not rows:
raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.")
# 세트 BOM 이 없으면 낱개로 못 푼 채 파일이 만들어진다 — 조용히 틀리지 말고 알린다.
set_bom, _sab = _itemcode_bom_and_sabangnet(request)
missing_sets = export.missing_set_boms(rows, set_bom)
if missing_sets:
reader = getattr(request.app.state, "malaysia_itemcode", None)
hint = getattr(reader, "last_error", "") or getattr(reader, "reason", "")
detail = (
"세트 BOM 을 찾지 못해 낱개로 풀 수 없습니다: "
+ ", ".join(missing_sets)
+ ". itemcode_db 의 set_components 에 해당 세트 BOM 이 등록돼 있는지 확인하세요."
)
if hint:
detail += f" (itemcode 리더 오류: {hint})"
raise HTTPException(status_code=422, detail=detail)
xlsx_bytes = export.build_period_xlsx(
rows=rows, date_from=f, date_to=t,
name_map=_itemcode_name_map(request), set_bom=set_bom,
)
fname = export.period_filename(f, t)
headers = {
"Content-Disposition": (
f"attachment; filename=\"shipped_{f}_{t}.xlsx\"; "
f"filename*=UTF-8''{quote(fname)}"
)
}
return Response(
content=xlsx_bytes,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers=headers,
)
@router.post("/stock-deduct")
def stock_deduct(
request: Request,
@@ -114,7 +114,8 @@
</div>
</div>
<div class="erp-card dsp-calwrap">
<div class="dsp-calwrap" style="display:flex;flex-direction:column;gap:16px;">
<div class="erp-card" style="margin:0;">
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
@@ -143,6 +144,24 @@
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
</div>
</div>
{% if is_super %}
<div class="erp-card" style="margin:0;">
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="기간별 발송 수량" data-en="Shipped Qty by Period">기간별 발송 수량</h3></div>
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
data-ko="기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)"
data-en="Download shipped quantities per date and item for the period. Sets are split into singles; set counts are on a separate sheet. (Super admin only)">기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)</p>
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
<input type="date" id="dsp-pe-from" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
<span class="erp-muted">~</span>
<input type="date" id="dsp-pe-to" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
</div>
<button type="button" id="dsp-pe-dl" class="erp-btn erp-btn-primary" style="margin-top:10px;width:100%;"
data-ko="📊 기간별 발송 수량 엑셀 다운로드" data-en="📊 Download Shipped Qty Excel">📊 기간별 발송 수량 엑셀 다운로드</button>
<div id="dsp-pe-note" class="erp-muted" style="font-size:12px;margin-top:6px;"></div>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
@@ -264,6 +283,53 @@
render();
})();
// ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
(function () {
var btn = document.getElementById('dsp-pe-dl');
if (!btn) return;
var fromEl = document.getElementById('dsp-pe-from');
var toEl = document.getElementById('dsp-pe-to');
var note = document.getElementById('dsp-pe-note');
function pad(n) { return (n < 10 ? '0' : '') + n; }
function iso(d) { return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); }
function en() { return (window.dspLang && window.dspLang() === 'en'); }
// 기본: 이번 달 1일 ~ 오늘
var now = new Date();
fromEl.value = iso(new Date(now.getFullYear(), now.getMonth(), 1));
toEl.value = iso(now);
btn.onclick = function () {
var f = fromEl.value, t = toEl.value;
if (!f || !t) { alert(en() ? 'Pick both dates.' : '시작일과 종료일을 고르세요.'); return; }
btn.disabled = true;
note.textContent = en() ? 'Preparing…' : '만드는 중…';
var url = '/dispatch/period-export?date_from=' + encodeURIComponent(f) + '&date_to=' + encodeURIComponent(t);
fetch(url)
.then(function (r) {
if (!r.ok) {
return r.json().catch(function () { return {}; }).then(function (j) {
throw new Error((j && j.detail) || ('HTTP ' + r.status));
});
}
var cd = r.headers.get('Content-Disposition') || '';
var m = cd.match(/filename\*=UTF-8''([^;]+)/);
var name = m ? decodeURIComponent(m[1]) : ('shipped_' + f + '_' + t + '.xlsx');
return r.blob().then(function (b) {
var a = document.createElement('a');
a.href = URL.createObjectURL(b);
a.download = name;
document.body.appendChild(a); a.click(); a.remove();
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
note.textContent = '';
});
})
.catch(function (e) {
note.textContent = (e && e.message) || (en() ? 'Failed' : '실패');
})
.then(function () { btn.disabled = false; });
};
})();
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
(function () {
var wrap = document.getElementById('dsp-search');
@@ -0,0 +1,91 @@
"""기간별 발송 수량 엑셀(export.aggregate_shipped / build_period_xlsx) 테스트.
DB 없이 집계·엑셀 생성만 검증한다.
python -m app.modules.dispatch.tests.test_period_export
또는 pytest 로 실행 가능.
"""
from __future__ import annotations
import io
from app.modules.dispatch import export
_ROWS = [
{"dispatch_date": "2026-10-02", "seller_sku": "MT-0320", "product_name": "A", "qty": 2},
{"dispatch_date": "2026-10-01", "seller_sku": "MT-0320_3", "product_name": "A", "qty": 1},
{"dispatch_date": "2026-10-01", "seller_sku": "mt-0320", "product_name": "A", "qty": 1},
{"dispatch_date": "2026-10-01", "seller_sku": "MY-0001", "product_name": "Set", "qty": 4},
{"dispatch_date": "2026-10-02", "seller_sku": "", "product_name": "", "qty": 9},
]
def test_aggregate_multiplier_and_merge():
"""_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외(BOM 없으면 세트 그대로)."""
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0320": "상품A"})
assert dates == ["2026-10-01", "2026-10-02"], dates
assert qty[("2026-10-01", "MT-0320")] == 4 # 1×3 + 1
assert qty[("2026-10-02", "MT-0320")] == 2
assert qty[("2026-10-01", "MY-0001")] == 4
assert names["MT-0320"] == "상품A" # itemcode 이름 우선
assert names["MY-0001"] == "Set" # 없으면 파싱된 이름
_BOM = {"MY-0001": [
{"component_code": "MT-0320", "component_qty": 1},
{"component_code": "mt-0550", "component_qty": 2},
]}
def test_aggregate_explodes_sets():
"""세트는 BOM 으로 낱개 분해해 같은 날 같은 낱개 코드에 합산."""
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0550": "상품B"}, _BOM)
assert ("2026-10-01", "MY-0001") not in qty
assert qty[("2026-10-01", "MT-0320")] == 8 # 1×3 + 1 + 세트 4×1
assert qty[("2026-10-01", "MT-0550")] == 8 # 세트 4×2
assert names["MT-0550"] == "상품B"
assert export.missing_set_boms(_ROWS, _BOM) == []
assert export.missing_set_boms(_ROWS, {}) == ["MY-0001"]
def test_build_period_xlsx_sheets():
from openpyxl import load_workbook
data = export.build_period_xlsx(
rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={}, set_bom=_BOM
)
wb = load_workbook(io.BytesIO(data))
assert wb.sheetnames == ["날짜별", "아이템별 요약", "세트별 요약"]
ws = wb["날짜별"]
rows = list(ws.iter_rows(values_only=True))
assert rows[0] == ("발송 날짜", "아이템 코드", "상품이름", "수량")
assert rows[1] == ("2026-10-01", "MT-0320", "A", 8)
assert rows[2] == ("2026-10-01", "MT-0550", None, 8)
assert rows[3] == ("2026-10-02", "MT-0320", "A", 2)
assert rows[-1][0] == "합계" and rows[-1][3] == 18
ws2 = wb["아이템별 요약"]
rows2 = list(ws2.iter_rows(values_only=True))
assert rows2[0] == ("아이템 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
assert rows2[1] == ("MT-0320", "A", 8, 2, 10)
assert rows2[2] == ("MT-0550", None, 8, None, 8)
assert rows2[3] == ("합계", None, 16, 2, 18)
# 세트는 낱개로 풀기 전 세트 단위 수량, 날짜 열은 전체 발송 날짜와 같다.
rows3 = list(wb["세트별 요약"].iter_rows(values_only=True))
assert rows3[0] == ("세트 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
assert rows3[1] == ("MY-0001", "Set", 4, None, 4)
assert rows3[2] == ("합계", None, 4, 0, 4)
def test_period_filename():
assert export.period_filename("2026-10-01", "2026-10-28") == "2026.10.01-2026.10.28_shipped_qty.xlsx"
if __name__ == "__main__":
test_aggregate_multiplier_and_merge()
test_aggregate_explodes_sets()
test_build_period_xlsx_sheets()
test_period_filename()
print("OK")
+10 -10
View File
@@ -265,11 +265,11 @@ def expense_index(request: Request) -> HTMLResponse:
get_current_user_record,
render_template,
)
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, "expense"):
return render_template(
request,
@@ -325,11 +325,11 @@ def pending_page(request: Request) -> HTMLResponse:
get_current_user_record,
render_template,
)
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not (is_admin(user) or has_module(user, "expense_approver")):
return render_template(
request,
@@ -362,11 +362,11 @@ def reports_page(request: Request) -> HTMLResponse:
get_current_user_record,
render_template,
)
from app.store import is_admin # noqa: WPS433
from app.store import is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
store = _store(request)
_require_db_store(store)
year_str = request.query_params.get("year") or str(now_kst().year)
@@ -436,11 +436,11 @@ def approved_page(request: Request) -> HTMLResponse:
get_current_user_record,
render_template,
)
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not (is_admin(user) or has_module(user, "expense_approver")):
return render_template(
request,
@@ -667,11 +667,11 @@ def settings_page(request: Request) -> HTMLResponse:
get_current_user_record,
render_template,
)
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not (is_admin(user) or has_module(user, "expense_approver")):
return render_template(
request,
+58
View File
@@ -10,6 +10,8 @@
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
- 미입고 현황(제품별 합계·발주별·지연).
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(2026-11-04) — `inout_settings` 키 `list_status:{이메일}`(마이그레이션 없음, 005 미적용이면 기억만 안 함). 주소에 `status` 가 있으면 저장, 없으면 저장값, 그것도 없으면 진행 중.
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
- 잔량 종결·취소(취소는 입고 없을 때만).
@@ -28,7 +30,18 @@
- 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 보냄.
- **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`).
**휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며,
콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인.
- 보낸 기록·재발송 확인.
- **본문 고치기**(2026-10-27): 발주 메일 미리보기 iframe 이 `designMode`(sandbox `allow-same-origin`, 스크립트 없음) — 고치면 [원래 본문으로]·닫을 때 확인,
보낼 때만 `html` 을 함께 POST → `store.clean_mail_html`(허용 태그·표·인라인 서식만, url()·이벤트·스크립트 제거) + 글 버전 `mail_html_to_text`. 안 고치면 서버 본문 그대로. 입고 요청 메일은 고치기 없음(cid 사진).
**서식 막대**(`initMail` 안 `RTE_BAR`, 안내문 발송 편집기와 같은 구성: 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기) = iframe `execCommand`(styleWithCSS → span style).
Quill 은 표를 못 담아 안 씀. 크기는 fontSize 7 → px span 으로 바꿔 끼움. 선택은 본문 문서의 현재 선택 우선(막대 mousedown 때 기억은 대비용). 서버는 `text-decoration-line` → `text-decoration`.
- **입고 담당 발주 알림 자동 발송**(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 필요).
- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로.
박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음.
## 입고 요청 메일 (005, 2026-10-19)
@@ -47,6 +60,8 @@
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
## 상품 정보 (004, 옵션 세 번째 탭)
@@ -55,8 +70,51 @@
- 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동).
- 한 번 불러오면 발주서 제품은 이 목록에서. 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`).
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
- 발주서 화면 품목 표(`.io-items-table`, 2026-10-21): 제목 행 검정·굵게·가운데, 합계 줄 검정·굵게·제목 크기, "합계" = 1~3열 가운데.
열 **PP 사용량**·**은(Ag) 함유량** = 발주 수량 전체 사용량 kg(`store.line_usage` — 메일 표와 같은 값), 아래 작은 글씨 = 개당 g·%.
- **합계 줄(발주서 화면·발주 메일 표 같음)**: 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg). 줄 값·메일 요약 표는 예전 자릿수 그대로.
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
## 상품 그룹·색상 (006, 2026-10-21)
- 옵션 **상품 그룹** 탭(2026-10-21 상품 정보 탭에서 분리) = 그룹 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다.
계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값.
- 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`).
- 발주 품목에 그때 색상 사본(`inout_order_lines.color`, 006 전 품목 NULL = 지금 상품 색상). **발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 그 색**(tr + 칸마다).
- 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다).
- 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일.
## 박스 입수·파렛트 (007, 2026-10-21)
- 옵션 → 상품 정보 **통 수량(박스)**·**뚜껑 수량(박스)** = 통·뚜껑이 한 박스에 몇 개(`inout_products.body_per_box`·`lid_per_box`, 1 이상 정수, 뚜껑 없으면 빈칸,
`store.validate_box_values`). 상품 정보 표 제목 행 = 가운데·굵게·13.2px(예전 12px × 110%).
- **새 발주서** 줄마다 "통·뚜껑 박스" 칸(`inout.js boxCell`) = 통 ⌈수량 ÷ 통 입수⌉박스 · 뚜껑 ⌈수량 ÷ 뚜껑 입수⌉박스, 힌트 = 통·뚜껑 입수의 **최소공배수**(둘 다 꽉 차는 수량 단위,
뚜껑 없으면 통 입수)와 지금 수량에 가까운 그 배수(누르면 수량 칸에), 배수면 "✓ 꽉 찹니다". 합계 줄 = 통·뚜껑·전체 박스 → **파렛트 ⌈전체 박스 ÷ 30⌉**(`store.PALLET_BOXES`) + 마지막 파렛트 박스 수.
- 수량 칸 오른쪽 **◀ ▶** = 공배수(`unitOf`)만큼 줄이기·늘리기 — 배수가 아니면 가까운 아래/위 배수로, 0 이면 빈칸. 제품을 안 골랐거나 입수가 없으면 못 누름.
- 합계 줄 파렛트 그림(`palletSvg`·`palletVis`, 6열 × 5행 박스 + 받침대) = 꽉 찬 파렛트(최대 10개 + "+N") · 잔량 파렛트(실린 박스만 색칠, 몇 %·몇 박스 더 실으면 한 파렛트), 딱 맞으면 "✓ 모든 파렛트가 꽉 찹니다".
- 품목 표 제목 행 = 가운데·굵게·`--text-caption` × 110%.
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
## 봉투·백 (008, 2026-11-04)
- 이름에 **"미라클 봉투"·"미라클백"** 이 들어간 상품(`store.is_bag`, 저장 안 함 — 이름으로 판단) = 옵션 → 상품 정보에서 일반 상품과 **표를 나눔**(봉투·백 표가 위). 칸: **박스당 수량**(`body_per_box` 재사용)·**1파렛트당 박스 수량**(`inout_products.boxes_per_pallet`). 뚜껑 없음(저장하면 `lid_per_box` 는 NULL).
**단가·무게·은 칸 없음**(2026-11-04 사용자 지정) — 전에 넣은 값은 줄의 숨은 칸으로 저장 때 그대로 보내 지우지 않음. 그룹·색상 칸은 있음. 새 발주서 "단가 없는 N종"·발주서 화면과 발주 메일의 "단가 미입력 N종"(`store.order_totals`) 안내에서 봉투·백은 뺌.
- 새 발주서 합계 줄에 봉투·백 박스·파렛트를 **통·뚜껑과 따로** 표시: 파렛트 = ⌈Σ(박스 ÷ 그 상품 1파렛트 박스)⌉. 파렛트 그림도 통처럼(`palletVis(all, cap, mixed)`, 그림 칸은 60칸까지) — 1파렛트 박스 수가 다른 상품이 섞이면 가장 큰 값으로 환산해 잔량은 %만. 입수·1파렛트 값은 `store.box_info`(`_form_page`·`/api/items`).
- 008 확인 `db.bags_ready`(boxes_ready 와 같은 방식). 미적용이면 모두 일반 상품으로 동작.
## 오른쪽 달력 (2026-10-21)
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
달력 크기 = 화면에 따라 300~440px(`clamp(300px, 23vw, 440px)`, 높이 ×320/300) — 입출고 화면만 ERP 공용 최대 폭 1550px 를 풀어 넓은 화면 여백을 씀(2026-10-21 "여백이 많다, 더 키워 달라").
글자·칸은 달력 너비 기준 `cqw`(300px 일 때 1cqw = 3px)라 같은 비율로 커진다 — 새 크기 값도 px 대신 cqw 로.
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
- 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`).
- **메뉴를 옮겨도 달력은 다시 그리지 않음**(2026-10-21) — 마지막 달력(달·API 응답 글·칸 HTML)을 sessionStorage `io_cal_v1` 에 두고 `_calendar.html` 인라인 스크립트가 그리기 전에 붙임,
`inout.js` 는 서버 값을 다시 받아 **글이 달라졌을 때만** 다시 그린다(보던 달도 유지). `CAL_KEY` 는 `initCalendar` 안에 — 바깥 const 면 위에서 먼저 부를 때 TDZ 로 복원이 조용히 꺼진다.
## 시각 / 날짜
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
+228 -11
View File
@@ -8,10 +8,11 @@
from __future__ import annotations
import time
from datetime import date, datetime
from typing import Any
from psycopg.errors import UndefinedColumn, UndefinedTable
from psycopg.errors import UndefinedColumn, UndefinedTable, UniqueViolation
from psycopg.rows import dict_row
from psycopg.types.datetime import TimestamptzLoader
from psycopg_pool import ConnectionPool
@@ -23,6 +24,15 @@ from . import store
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
# 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*).
# p.* 다음에 같은 이름(silver_pct·color)을 다시 고르면 dict_row 는 뒤의 값(그룹 적용 값)을 쓴다. p.* 라 007 박스 입수 등 새 열도 따라온다.
_PRODUCT_SELECT_006 = (
"SELECT p.*, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
"CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, "
"CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color "
"FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id"
)
class OverReceipt(Exception):
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
@@ -134,10 +144,21 @@ class InoutDBStore:
# ════════════════════════════════════════════════════════════
# 발주서
# ════════════════════════════════════════════════════════════
def _ready_flags(self) -> tuple[bool, bool]:
"""(004 상품 정보, 006 그룹·색상) — 발주 저장 트랜잭션을 열기 전에 확인해 _insert_line 에 넘긴다."""
return self.products_ready(), self.groups_ready()
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():
specs: dict[str, dict[str, Any]], ready: tuple[bool, bool]) -> None:
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을(006 이면 색상도) 그때 값으로 함께 남긴다."""
products_ok, groups_ok = ready
if groups_ok: # 006 — 색상 사본도(그룹 상품은 그룹 색상)
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, color) "
"VALUES (%s,%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"), sp.get("color") or "none"))
elif products_ok:
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)",
@@ -150,6 +171,7 @@ class InoutDBStore:
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}."""
ready = self._ready_flags()
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'))")
@@ -166,13 +188,14 @@ class InoutDBStore:
(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 {})
self._insert_line(conn, oid, i, ln, names, specs or {}, ready)
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)."""
ready = self._ready_flags()
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
@@ -194,7 +217,7 @@ class InoutDBStore:
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 {})
self._insert_line(conn, order_id, i, ln, names, specs or {}, ready)
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))
@@ -273,6 +296,11 @@ class InoutDBStore:
by_receipt: dict[int, list[dict[str, Any]]] = {}
for r in rlines:
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
if any("color" in ln and ln["color"] is None for ln in lines): # 006 전 품목 = 지금 상품 색상
cur = self.catalog_lookup([ln["item_code"] for ln in lines if ln["color"] is None])
for ln in lines:
if ln.get("color") is None and ln["item_code"] in cur:
ln["color"] = cur[ln["item_code"]].get("color")
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,
@@ -404,6 +432,19 @@ class InoutDBStore:
if not row:
raise ValueError("사진을 찾을 수 없습니다.")
def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
"""저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서입니다.")
row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
"WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
if not row:
raise ValueError("사진을 찾을 수 없습니다.")
data = store.rotate_image(bytes(row["data"]), degrees)
conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
"""사진 내용(+ 발주서 id) — 보여 주기용."""
try:
@@ -482,6 +523,22 @@ class InoutDBStore:
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
# 발주 목록 상태 거르기 — 사람마다 기억(2026-11-04). 같은 설정 표에 사람별 키(마이그레이션 없음), 005 미적용이면 기억만 안 한다.
def get_list_status(self, email: str) -> str:
try:
with self._pool.connection() as conn:
row = conn.execute("SELECT value FROM inout_settings WHERE key = %s",
("list_status:" + _norm_email(email),)).fetchone()
except UndefinedTable:
return ""
return row["value"] if row else ""
def save_list_status(self, email: str, status: str) -> None:
try:
self.save_settings({"list_status:" + _norm_email(email): status}, by=email)
except ValueError:
pass
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
try:
@@ -531,9 +588,13 @@ class InoutDBStore:
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
def list_products(self) -> list[dict[str, Any]]:
"""상품 정보 — 006 이면 그룹 이름·그룹 적용 값(silver_pct·color)·상품 자기 값(own_*)까지."""
if not self.products_ready():
return []
grouped = self.groups_ready()
with self._pool.connection() as conn:
if grouped:
return conn.execute(_PRODUCT_SELECT_006 + " ORDER BY p.item_code").fetchall()
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
def list_excluded(self) -> list[dict[str, Any]]:
@@ -571,9 +632,36 @@ class InoutDBStore:
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 를 거친 값). 한 트랜잭션."""
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션.
006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
self._need_products()
grouped = self.groups_ready() and any("group_id" in r for r in rows)
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
bagged = self.bags_ready() and any("boxes_per_pallet" in r for r in rows)
with self._pool.connection() as conn, conn.transaction():
if bagged: # 008 — 봉투·백 1파렛트당 박스 수량
for r in rows:
if "boxes_per_pallet" in r:
conn.execute("UPDATE inout_products SET boxes_per_pallet=%s WHERE item_code=%s", (r["boxes_per_pallet"], r["code"]))
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
for r in rows:
if "body_per_box" in r:
conn.execute("UPDATE inout_products SET body_per_box=%s, lid_per_box=%s WHERE item_code=%s",
(r.get("body_per_box"), r.get("lid_per_box"), r["code"]))
if grouped:
known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()}
for r in rows:
gid = r.get("group_id")
if gid is not None and int(gid) not in known:
raise ValueError(f"{r['code']}: 없는 그룹입니다(다른 사람이 지웠을 수 있음 — 옵션을 다시 여세요).")
hit = conn.execute(
"UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, group_id=%s, color=%s, "
"updated_by=%s, updated_at=now() WHERE item_code=%s RETURNING item_code",
(r["unit_price"], r["weight_g"], r["silver_pct"], gid, r.get("color") or "none",
_norm_email(by), r["code"])).fetchone()
if not hit:
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
return len(rows)
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",
@@ -614,20 +702,149 @@ class InoutDBStore:
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
if not esc:
return []
args = {"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}
grouped = self.groups_ready()
with self._pool.connection() as conn:
if grouped: # 그룹 상품은 그룹의 은 함유량·색상
return conn.execute(
_PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s "
"ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall()
return conn.execute(
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
"SELECT * 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()
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
if not codes or not self.products_ready():
return {}
grouped = self.groups_ready()
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()
if grouped: # 발주 품목 사본 = 그룹 적용 값
rows = conn.execute(_PRODUCT_SELECT_006 + " WHERE p.item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
else:
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}
# ════════════════════════════════════════════════════════════
# 상품 그룹(006) — 은 함유량·색상을 그룹에 한 번만. 그룹을 지우면 그 상품들은 그룹 없음(자기 값)으로.
# ════════════════════════════════════════════════════════════
def groups_ready(self) -> bool:
"""006 이 적용됐나(그룹 표·상품 group_id·발주 품목 color). 적용됐으면 계속, 아직이면 1분 동안 기억한다 —
부를 때마다 연결을 하나 더 잡지 않게(발주 저장 트랜잭션이 연결을 쥔 채 부르면 동시 발주에서 풀이 바닥난다).
그래서 연결을 열기 전에 먼저 부른다."""
if getattr(self, "_groups_ok", False):
return True
if time.monotonic() - getattr(self, "_groups_checked", -1e9) < 60:
return False
if not self.products_ready():
return False
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT to_regclass('public.inout_product_groups') IS NOT NULL "
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' AND column_name = 'group_id') "
"AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_order_lines' AND column_name = 'color') AS ok"
).fetchone()["ok"])
self._groups_ok = ok
self._groups_checked = time.monotonic()
return ok
def boxes_ready(self) -> bool:
"""007 이 적용됐나(상품 body_per_box·lid_per_box). groups_ready 와 같이 — 적용됐으면 계속, 아직이면 1분 기억, 연결 열기 전에 부른다."""
if getattr(self, "_boxes_ok", False):
return True
if time.monotonic() - getattr(self, "_boxes_checked", -1e9) < 60:
return False
if not self.products_ready():
return False
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
"AND column_name = 'lid_per_box') AS ok").fetchone()["ok"])
self._boxes_ok = ok
self._boxes_checked = time.monotonic()
return ok
def bags_ready(self) -> bool:
"""008 이 적용됐나(상품 boxes_per_pallet). boxes_ready 와 같은 방식."""
if getattr(self, "_bags_ok", False):
return True
if time.monotonic() - getattr(self, "_bags_checked", -1e9) < 60:
return False
if not self.products_ready():
return False
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
"AND column_name = 'boxes_per_pallet') AS ok").fetchone()["ok"])
self._bags_ok = ok
self._bags_checked = time.monotonic()
return ok
def _need_groups(self) -> None:
if not self.groups_ready():
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
def list_groups(self) -> list[dict[str, Any]]:
if not self.groups_ready():
return []
with self._pool.connection() as conn:
return conn.execute(
"SELECT g.*, (SELECT count(*) FROM inout_products p WHERE p.group_id = g.id)::int AS product_count "
"FROM inout_product_groups g ORDER BY g.sort_order, g.name").fetchall()
def save_group(self, *, group_id: int | None, name: str, silver_pct: Any, color: str, sort_order: int, by: str) -> int:
"""그룹 만들기·고치기(store.validate_group 를 거친 값). 같은 이름은 거절. 반환 = 그룹 id."""
self._need_groups()
try:
with self._pool.connection() as conn, conn.transaction():
if group_id:
row = conn.execute(
"UPDATE inout_product_groups SET name=%s, silver_pct=%s, color=%s, sort_order=%s, updated_by=%s, "
"updated_at=now() WHERE id=%s RETURNING id",
(name, silver_pct, color, sort_order, _norm_email(by), group_id)).fetchone()
if not row:
raise ValueError("그룹을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
else:
row = conn.execute(
"INSERT INTO inout_product_groups (name, silver_pct, color, sort_order, updated_by) "
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
(name, silver_pct, color, sort_order, _norm_email(by))).fetchone()
except UniqueViolation:
raise ValueError(f"같은 이름의 그룹이 있습니다: {name}") from None
return int(row["id"])
def delete_group(self, group_id: int) -> str:
"""그룹 지우기 — 그 그룹 상품은 그룹 없음(상품 자기 은 함유량·색상)으로. 지난 발주서는 그대로. 반환 = 이름."""
self._need_groups()
with self._pool.connection() as conn, conn.transaction():
row = conn.execute("DELETE FROM inout_product_groups WHERE id=%s RETURNING name", (group_id,)).fetchone()
if not row:
raise ValueError("그룹을 찾을 수 없습니다.")
return str(row["name"])
# ════════════════════════════════════════════════════════════
# 달력(2026-10-21) — 화면 오른쪽 달력에 날짜별 발주(발주일)·입고(입고일). 취소된 발주는 뺀다.
# ════════════════════════════════════════════════════════════
def calendar(self, start: date, end: date) -> dict[str, list[dict[str, Any]]]:
with self._pool.connection() as conn:
orders = conn.execute(
"SELECT o.id, o.order_no, o.order_date, f.name AS factory_name, "
"(SELECT COALESCE(sum(qty), 0) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS qty, "
"(SELECT count(*) FROM inout_order_lines l WHERE l.order_id = o.id)::int AS kinds, "
"(SELECT l.item_name FROM inout_order_lines l WHERE l.order_id = o.id ORDER BY l.line_no LIMIT 1) AS first_item "
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
"WHERE o.cancelled_at IS NULL AND o.order_date BETWEEN %s AND %s ORDER BY o.order_date, o.id",
(start, end)).fetchall()
receipts = conn.execute(
"SELECT r.id, r.order_id, r.receipt_date, o.order_no, f.name AS factory_name, "
"COALESCE(sum(rl.qty), 0)::int AS qty "
"FROM inout_receipts r JOIN inout_orders o ON o.id = r.order_id JOIN inout_factories f ON f.id = o.factory_id "
"LEFT JOIN inout_receipt_lines rl ON rl.receipt_id = r.id "
"WHERE o.cancelled_at IS NULL AND r.receipt_date BETWEEN %s AND %s "
"GROUP BY r.id, o.order_no, f.name ORDER BY r.receipt_date, r.id",
(start, end)).fetchall()
return {"orders": orders, "receipts": receipts}
# ════════════════════════════════════════════════════════════
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
# ════════════════════════════════════════════════════════════
+242 -16
View File
@@ -11,10 +11,11 @@
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete|rotate · GET /inout/photos/{pid} 입고증 사진
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
POST /inout/settings/order-mail 옵션 → 공장(발주 메일 참조 기본값 — 처음엔 king@dbxcorp.co.kr)
GET /inout/orders/{id}/receipts/{rid}/sabangnet.xlsx 사방넷 입고 파일(상품코드=사방넷 코드·가용수량=입고 수량·불용수량=상품 이름)
GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만)
GET /inout/api/items?q= 코드표 단품 검색(JSON)
@@ -67,13 +68,11 @@ def _user(request: Request) -> dict[str, Any]:
def _page_user(request: Request) -> Any:
"""화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다."""
from urllib.parse import quote # noqa: WPS433
from app.main import get_current_user_record # noqa: WPS433
from app.store import login_redirect # noqa: WPS433
if get_current_user_record(request) is None:
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
return login_redirect(request)
return _user(request)
@@ -172,13 +171,17 @@ def _opt_date(v: Any) -> date | None:
# 발주 목록 · 미입고 현황
# ────────────────────────────────────────────────────────────
@router.get("/", response_class=HTMLResponse)
def index(request: Request, status: str = "active", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
def index(request: Request, status: str = "", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
date_to: str = Query("", alias="to")) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
status = status if status in store.STATUS_FILTERS else "active"
saved = st.get_list_status(user.get("email", ""))
if status not in store.STATUS_FILTERS: # 주소에 상태가 없으면 이 사람이 마지막으로 고른 보기
status = saved if saved in store.STATUS_FILTERS else "active"
elif status != saved:
st.save_list_status(user.get("email", ""), status)
orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from),
date_to=_opt_date(date_to))
return _render(request, "inout/index.html", user, {
@@ -258,10 +261,13 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
# 단가 — 이미 있던 품목은 발주 당시 값(사본), 새 품목은 지금 상품 정보 값(004). 금액은 화면이 수량 × 단가로 계산.
snap = {x["item_code"]: x.get("unit_price") for x in (order["lines"] if order else [])}
catalog = st.catalog_lookup([ln["code"] for ln in lines if ln["code"] and ln["code"] not in snap])
boxes = st.catalog_lookup([ln["code"] for ln in lines if ln["code"]]) if st.boxes_ready() else {}
for ln in lines:
price = snap[ln["code"]] if ln["code"] in snap else (catalog.get(ln["code"]) or {}).get("unit_price")
ln["price"] = float(price) if price is not None else None
ln["price_label"] = store.fmt_num(price) if price is not None else ""
bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음)
ln.update(store.box_info(bx))
reader = _items(request)
catalog_n = st.catalog_count()
return _render(request, "inout/order_form.html", user, {
@@ -269,6 +275,7 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
"factories": [f for f in st.list_factories(include_inactive=True)
if f["is_active"] or (order and f["id"] == order["factory_id"])],
"items_enabled": bool(reader is not None and reader.enabled) or catalog_n > 0, "from_catalog": catalog_n > 0,
"boxes_ready": st.boxes_ready(), "pallet_boxes": store.PALLET_BOXES,
}, status_code=status_code)
@@ -347,7 +354,7 @@ def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, An
# 입고 담당(발주 담당 아님)은 품목을 이름·발주 수량(+ 이번 입고 칸)만 — 2026-10-16 사용자 요청
"items_limited": perms["can_receive"] and not perms["can_order"],
"show_prices": perms["can_order"], "totals": store.order_totals(order["lines"]),
"fmt_num": store.fmt_num, "line_amount": store.line_amount, "silver_g": store.silver_g,
"fmt_num": store.fmt_num, "line_amount": store.line_amount, "silver_g": store.silver_g, "line_usage": store.line_usage,
"max_photos": store.MAX_PHOTOS,
"receipt_form": receipt_form or {"receipt_date": today_kst().isoformat(), "memo": "", "qty": {}},
"can_receive_now": order["status"] in (store.ST_OPEN, store.ST_PARTIAL, store.ST_DONE, store.ST_OVER),
@@ -483,7 +490,7 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
_PHOTO_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
"Cache-Control": "private, max-age=86400",
"Cache-Control": "private, no-cache",
}
@@ -527,6 +534,21 @@ def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
@router.post("/orders/{order_id}/photos/{photo_id}/rotate")
def receipt_photo_rotate(request: Request, order_id: int, photo_id: int, degrees: int = Query(...)) -> Any:
"""크게 보기 창의 회전 버튼 — 창을 닫지 않게 JSON 으로 답한다(화면이 사진을 다시 받아 그림)."""
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "receive")
try:
st.rotate_receipt_photo(order_id, photo_id, degrees)
except (ValueError, LookupError) as exc:
return JSONResponse({"error": str(exc)}, status_code=400)
return JSONResponse({"ok": True})
@router.get("/photos/{photo_id}")
def photo_view(request: Request, photo_id: int) -> Response:
_user(request)
@@ -534,12 +556,18 @@ def photo_view(request: Request, photo_id: int) -> Response:
row = st.get_photo(photo_id) if st is not None else None
if row is None:
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
from hashlib import md5 # noqa: WPS433
from urllib.parse import quote # noqa: WPS433
data = bytes(row["data"])
# 돌린 사진이 하루 동안 예전 모습으로 남지 않게 — 브라우저가 매번 내용이 같은지 묻는다(no-cache + ETag)
etag = '"' + md5(data, usedforsecurity=False).hexdigest() + '"'
if request.headers.get("if-none-match") == etag:
return Response(status_code=304, headers={"ETag": etag, "Cache-Control": _PHOTO_HEADERS["Cache-Control"]})
name = quote(str(row["filename"] or f"photo-{photo_id}"))
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
return Response(content=bytes(row["data"]), media_type=row["content_type"],
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
return Response(content=data, media_type=row["content_type"],
headers={**_PHOTO_HEADERS, "ETag": etag, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
# ────────────────────────────────────────────────────────────
@@ -572,6 +600,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa
except gmail.GmailError as exc:
return _redirect(_safe_next(next), str(exc))
request.session["_inout_gmail_next"] = _safe_next(next)
request.session.pop("_gmail_origin", None) # 휴가·안내문 발송에서 시작한 연결 표시가 남아 있으면 지움
return await client.authorize_redirect(
request, public_url_for(request, "inout_gmail_callback"),
access_type="offline", prompt="consent", include_granted_scopes="true",
@@ -580,6 +609,8 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa
@router.get("/gmail/callback", name="inout_gmail_callback")
async def gmail_callback(request: Request) -> Any:
if request.session.get("_gmail_origin") in _GMAIL_ORIGINS:
return await _gmail_callback_vacation(request)
got = _ctx(request)
if not isinstance(got, tuple):
return got
@@ -603,6 +634,54 @@ async def gmail_callback(request: Request) -> Any:
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.")
# 다른 모듈에서 시작한 [Gmail 연결] — 세션 _gmail_origin = 모듈 키 → (돌아갈 기본 주소, 권한 없을 때 문구, 연결 뒤 문구)
_GMAIL_ORIGINS: dict[str, tuple[str, str, str]] = {
"vacation": ("/vacation/options", "휴가 관리 모듈 권한이 없습니다.", "Gmail 을 연결했습니다 — 이제 휴가 메일이 내 Gmail 로 나갑니다."),
"outreach": ("/outreach/", "안내문 발송 모듈 권한이 없습니다.", "Gmail 을 연결했습니다 — 이제 안내문 메일을 내 Gmail 로 보낼 수 있습니다."),
}
async def _gmail_callback_vacation(request: Request) -> Any:
"""휴가 옵션·안내문 발송의 [Gmail 연결](2026-10-27) — 같은 구글 리디렉션 주소를 함께 쓰므로 여기로 돌아온다(구글 클라우드 설정 추가 없음).
입출고 담당 권한 대신 그 모듈 권한(_GMAIL_ORIGINS)을 보고, 토큰은 입출고와 같은 inout_gmail_tokens 에(한 사람 = 연결 하나, 모듈이 같이 씀).
돌아갈 주소 = 세션 _gmail_next(그 모듈 경로 아래만, 예전 휴가 _vacation_gmail_next 도 읽음)."""
from urllib.parse import quote # noqa: WPS433
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433
from . import gmail # noqa: WPS433
origin = str(request.session.pop("_gmail_origin", "") or "")
home, denied, done = _GMAIL_ORIGINS[origin]
nxt = str(request.session.pop("_gmail_next", "") or request.session.pop("_vacation_gmail_next", "") or "")
request.session.pop("_vacation_gmail_next", None)
if not nxt.startswith(f"/{origin}/") or "//" in nxt or "\\" in nxt:
nxt = home
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login?next=" + quote(nxt, safe=""), status_code=303)
# 휴가 협의자는 휴가 권한이 없어도 연결한다 — 휴가 연결 시작 때 그 신청의 협의자인지 확인해 세션에 남긴 값(2026-11-02)
if not request.session.pop("_gmail_consultant", False) and not has_module(user, origin):
raise HTTPException(status_code=403, detail=denied)
st = _store(request)
if st is None:
return _redirect(nxt, "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다.")
email = user.get("email", "")
try:
token = await gmail.oauth_client().authorize_access_token(request)
refresh, scopes = gmail.check_grant(token, expected_email=email)
st.save_gmail_token(email, refresh_token_enc=gmail.encrypt_token(email, refresh), scopes=scopes)
except OAuthError as exc:
msg = "Gmail 연결을 취소했습니다." if exc.error == "access_denied" else f"Gmail 연결 실패({exc.error})"
return _redirect(nxt, msg)
except (gmail.GmailError, ValueError) as exc:
return _redirect(nxt, str(exc))
return _redirect(nxt, done)
@router.post("/gmail/disconnect")
def gmail_disconnect(request: Request) -> JSONResponse:
user = _user(request)
@@ -630,6 +709,10 @@ def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], d
order = _order_or_404(st, order_id)
if order["cancelled_at"]:
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
if store.is_simple_mail_factory(order["factory_name"]) and st.boxes_ready(): # 박스 칸 — 발주 품목에 없어 지금 상품 정보 값
found = st.catalog_lookup([x["item_code"] for x in order["lines"]])
for x in order["lines"]:
x.update(store.box_info(found.get(x["item_code"]) or {}))
return st, user, order
@@ -646,6 +729,8 @@ def mail_preview(request: Request, order_id: int) -> JSONResponse:
"connect_url": f"/inout/gmail/connect?{urlencode({'next': f'/inout/orders/{order_id}?mail=1'})}",
"callback_url": _callback_url(request), # 구글 클라우드 승인된 리디렉션 URI 에 등록해야 하는 주소(안내용)
"from": user.get("email", ""), "to": order.get("factory_email") or "", "factory": order["factory_name"],
"cc": st.get_settings()[store.SETTING_ORDER_MAIL_CC], # 참조 기본(옵션 → 공장, 처음엔 king@dbxcorp.co.kr)
"notice_to": _receive_emails(st), # 발송하면 이 입고 담당들에게 발주 알림이 따로 감
"subject": mail["subject"], "html": mail["html"],
"sent": [{"at": store.fmt_datetime(m["sent_at"]), "by": m["sent_by"], "to": m["to_addrs"]} for m in order["mails"]],
})
@@ -661,6 +746,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
try:
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
cc = store.parse_emails(payload.get("cc"), label="참조")
# 미리보기 창에서 본문을 고쳤으면 그 HTML(2026-10-27) — 안 고쳤으면 보내지 않고 서버가 만든 본문 그대로
edited = store.clean_mail_html(payload["html"]) if payload.get("html") else None
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
if order["mails"] and not payload.get("resend"):
@@ -671,6 +758,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
status_code=409)
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
if edited is not None:
mail = {**mail, "html": edited, "text": store.mail_html_to_text(edited)}
try:
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
@@ -684,7 +773,34 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
return JSONResponse({"ok": False, "message": str(exc)}, status_code=502)
st.add_order_mail(order_id, sent_by=email, to=to, cc=cc, subject=mail["subject"], gmail_id=gid)
st.mark_gmail(email)
return JSONResponse({"ok": True, "message": f"메일을 보냈습니다 → {', '.join(to)}"})
note = _send_order_notice(st, user, order, refresh, subject=mail["subject"])
return JSONResponse({"ok": True, "message": f"메일을 보냈습니다 → {', '.join(to)}" + (f" · {note}" if note else ""),
"notice": note})
def _receive_emails(st: Any) -> list[str]:
"""발주 알림 받는 사람 = 옵션 → 담당자의 입고 담당(지정된 사람만, ERP 관리자는 자동으로 넣지 않음)."""
return list(st.list_roles().get(store.ROLE_RECEIVE) or [])
def _send_order_notice(st: Any, user: dict[str, Any], order: dict[str, Any], refresh: str, *, subject: str) -> str:
"""발주 메일을 보낸 뒤 입고 담당들에게 따로 자동 발송(2026-10-19) — 같은 Gmail·같은 제목, 내용은 발주번호·발주일·품목(코드·이름·수량).
공장 메일은 이미 나갔으므로 여기 실패는 막지 않고 안내 문구만 돌려준다."""
from . import gmail # noqa: WPS433
to = _receive_emails(st)
if not to:
return "입고 담당이 옵션에 없어 발주 알림 메일은 보내지 않았습니다"
email = user.get("email", "")
m = store.order_notice_mail(order, subject=subject, sender_name=str(user.get("name") or ""), sender_email=email)
try:
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=[],
subject=m["subject"], text=m["text"], html=m["html"])
gmail.send(refresh, raw)
except (gmail.GmailError, gmail.GmailNotConnected) as exc:
_log.warning("inout order notice mail failed: %s (%s)", order.get("order_no"), exc)
return f"입고 담당 알림 메일은 보내지 못했습니다({exc})"
return f"입고 담당 {len(to)}명에게 발주 알림 메일도 보냈습니다"
# ────────────────────────────────────────────────────────────
@@ -811,7 +927,8 @@ def _candidates() -> list[dict[str, str]]:
out = []
for u in user_store.list_all():
if has_module(u, "inout"):
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or "")})
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or ""),
"picture": str(u.get("picture") or "")}) # 옵션 → 담당자 = 아이콘 + 이름(2026-10-21)
return sorted(out, key=lambda x: x["email"])
@@ -822,13 +939,17 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다
for e in emails:
if e not in known:
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"})
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)", "picture": ""})
known.add(e)
reader = _items(request)
products = st.list_products()
bags_ready = st.bags_ready()
for pr in products:
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
pr["is_bag"] = bags_ready and store.is_bag(pr.get("item_name"))
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
"boxes_ready": st.boxes_ready(),
"fmt_num": store.fmt_num,
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
"settings": st.get_settings(), "settings_ready": st.settings_ready(),
@@ -900,6 +1021,23 @@ async def settings_logistics_save(request: Request) -> Any:
return _options_done(request, "물류센터 이메일을 저장했습니다.")
@router.post("/settings/order-mail")
async def settings_order_mail_save(request: Request) -> Any:
"""옵션 → 공장 — 발주 메일 참조 기본값(2026-10-19, 저장은 005 의 inout_settings)."""
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
form = await request.form()
try:
st.save_settings({store.SETTING_ORDER_MAIL_CC: store.clean_emails(form.get("order_mail_cc"), label="발주 메일 참조")},
by=user.get("email", ""))
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, "발주 메일 참조를 저장했습니다.")
@router.post("/settings/factories/{factory_id}/delete")
def settings_factory_delete(request: Request, factory_id: int) -> Any:
got = _ctx(request)
@@ -966,7 +1104,18 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
for r in (payload.get("rows") or [])[:5000]:
code = str((r or {}).get("code") or "").strip().upper()
try:
rows.append({"code": code, **store.validate_product_values(r)})
row = {"code": code, **store.validate_product_values(r)}
if "boxes_per_pallet" in (r or {}): # 008 — 봉투·백(박스당 수량·1파렛트당 박스 수량)
row.update(store.validate_bag_values(r))
elif "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
row.update(store.validate_box_values(r))
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
gid = str(r.get("group_id") or "").strip()
if gid and not gid.isdigit():
raise ValueError("그룹이 올바르지 않습니다.")
row["group_id"] = int(gid) if gid else None
row["color"] = store.norm_color(r.get("color"))
rows.append(row)
except ValueError as exc:
errors.append(f"{code}: {exc}")
if errors:
@@ -980,6 +1129,38 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
return _options_done(request, f"상품 정보 {n}개를 저장했습니다.")
@router.post("/settings/groups")
async def settings_group_save(request: Request) -> Any:
"""상품 그룹 만들기·고치기(006) — 이름·은 함유량·색상·순서. 그룹 상품 모두에 은 함유량·색상이 적용된다."""
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
form = await request.form()
try:
vals = store.validate_group(dict(form))
gid = _opt_int(form.get("id"))
st.save_group(group_id=gid, by=user.get("email", ""), **vals)
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, f"그룹 '{vals['name']}' 을(를) {'저장' if gid else '추가'}했습니다.")
@router.post("/settings/groups/{group_id}/delete")
def settings_group_delete(request: Request, group_id: int) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
try:
name = st.delete_group(group_id)
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, f"그룹 '{name}' 을(를) 지웠습니다 — 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.")
@router.post("/settings/products/{code}/exclude")
def settings_product_exclude(request: Request, code: str) -> Any:
got = _ctx(request)
@@ -1023,7 +1204,9 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
"unit_price": store.fmt_num(r["unit_price"]) if r["unit_price"] is not None else "",
"price": float(r["unit_price"]) if r["unit_price"] is not None else None,
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else ""} for r in rows]})
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
"color": r.get("color") or "none",
**store.box_info(r)} for r in rows]})
reader = _items(request)
if reader is None or not reader.enabled:
return JSONResponse({"items": [], "enabled": False,
@@ -1031,6 +1214,49 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
return JSONResponse({"items": reader.search(q, limit=30), "enabled": True})
@router.get("/api/calendar")
def api_calendar(request: Request, month: str = "") -> JSONResponse:
"""오른쪽 달력(2026-10-21) — month=YYYY-MM(없으면 이번 달) 앞뒤 주까지(6주 칸)의 날짜별 발주·입고.
days = {"YYYY-MM-DD": {"orders": [...], "receipts": [...]}}, holidays = {"YYYY-MM-DD": 이름}."""
from datetime import timedelta # noqa: WPS433
_user(request)
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="입출고 관리 DB 가 설정되지 않았습니다.")
today = today_kst()
try:
y, m = (int(x) for x in month.split("-", 1)) if month else (today.year, today.month)
first = date(y, m, 1)
except ValueError:
raise HTTPException(status_code=400, detail="month 는 YYYY-MM 입니다.") from None
start = first - timedelta(days=(first.weekday() + 1) % 7) # 일요일 시작
end = start + timedelta(days=41)
data = st.calendar(start, end)
days: dict[str, dict[str, list[dict[str, Any]]]] = {}
for o in data["orders"]:
days.setdefault(o["order_date"].isoformat(), {"orders": [], "receipts": []})["orders"].append({
"id": int(o["id"]), "order_no": o["order_no"], "factory": o["factory_name"], "qty": int(o["qty"]),
"item": (o["first_item"] or "") + (f" 외 {int(o['kinds']) - 1}종" if int(o["kinds"]) > 1 else "")})
for r in data["receipts"]:
days.setdefault(r["receipt_date"].isoformat(), {"orders": [], "receipts": []})["receipts"].append({
"id": int(r["id"]), "order_id": int(r["order_id"]), "order_no": r["order_no"], "factory": r["factory_name"],
"qty": int(r["qty"])})
holidays: dict[str, str] = {}
try:
from app.modules.project.store import holiday_name # noqa: WPS433 — 프로젝트 달력과 같은 공휴일 표
d = start
while d <= end:
name = holiday_name(d.isoformat())
if name:
holidays[d.isoformat()] = name
d += timedelta(days=1)
except Exception: # noqa: BLE001 — 공휴일 표가 없어도 달력은 보인다
holidays = {}
return JSONResponse({"month": f"{first:%Y-%m}", "start": start.isoformat(), "end": end.isoformat(),
"today": today.isoformat(), "days": days, "holidays": holidays})
@router.get("/health")
def health(request: Request) -> dict[str, str]:
return {"status": "ok" if _store(request) is not None else "not_configured"}
+402 -44
View File
@@ -9,6 +9,7 @@
from __future__ import annotations
import html as _html
import html.parser as _html_parser
import re
from datetime import date, datetime
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
@@ -247,6 +248,28 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False)
return out
# 간단 발주 메일(2026-11-04) — 이 공장들엔 품목 표를 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 요약에서도 금액·무게·은을 뺀다.
SIMPLE_MAIL_FACTORIES = ("대성화학", "인천공장")
def is_simple_mail_factory(name: Any) -> bool:
"""이름 일부·띄어쓰기가 달라도 맞게 — 놓치면 단가가 공장에 나간다."""
compact = "".join(str(name or "").split())
return any(word in compact for word in SIMPLE_MAIL_FACTORIES)
def line_boxes(x: dict[str, Any]) -> dict[str, Any]:
"""간단 발주 메일 칸 — 박스당 수량·박스 수(올림). 뚜껑이 있으면 통·뚜껑 따로, 입수가 없으면 '-'(total None)."""
body, lid, qty = x.get("body_per_box"), x.get("lid_per_box"), int(x["qty"])
if not body:
return {"per": "-", "count": "-", "total": None}
boxes = -(-qty // body)
if not lid:
return {"per": f"{body:,}개", "count": f"{boxes:,}박스", "total": boxes}
lids = -(-qty // lid)
return {"per": f"통 {body:,}개 · 뚜껑 {lid:,}개", "count": f"통 {boxes:,} · 뚜껑 {lids:,}박스", "total": boxes + lids}
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)
@@ -262,25 +285,26 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
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}"))
simple = is_simple_mail_factory(order.get("factory_name"))
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 not simple:
if money["amount"] is not None:
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
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
price, pct = to_dec(x.get("unit_price")), to_dec(x.get("silver_pct"))
amt = line_amount(int(x["qty"]), price)
use = line_usage(x)
total_kg, ag_kg = use["total_kg"], use["ag_kg"]
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 "-",
@@ -289,12 +313,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
# 글 본문(HTML 을 못 보는 메일 프로그램용)
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
text += [f"- {k}: {v}" for k, v in facts]
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · 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']}"
b = line_boxes(x)
if simple:
detail = f" · 박스당 {b['per']} · {b['count']}" if b["total"] is not None else ""
else:
detail = (f" · 단가 {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']}")
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개{detail}"
+ (f" ({x['memo']})" if x.get("memo") else ""))
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
# HTML 본문 — 값은 모두 escape
@@ -302,43 +331,65 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
td = "padding:6px 10px;border:1px solid #d9dce1;"
r = "text-align:right;white-space:nowrap;"
# 요약 표 = 항목·값 두 쌍씩 한 줄(4열, 2026-10-19 — 예전 2열 × 8행). 요청 사항(길 수 있음)은 맨 아래 한 줄 전체.
fth = f"{td}background:#f6f7f9;text-align:left;white-space:nowrap"
# 칸 높이는 글자 한 줄에 맞게 — 받은 메일(메일 프로그램)에서 칸이 크게 늘어나 보여 줄 높이·글자 크기·위아래 여백을 칸마다 못 박는다.
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="{td}">{e(str(v))}</td>' for k, v in pairs[i:i + 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="{td}"></td>'
cols += f'<th style="{fth}"></th><td style="{ftd}"></td>'
fact_rows += f"<tr>{cols}</tr>"
if order.get("memo"):
fact_rows += f'<tr><th style="{fth}">요청 사항</th><td colspan="3" style="{td}">{e(str(order["memo"]))}</td></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)
# 색상 있는 품목(006) = 줄 전체 배경 그 색 — 메일 프로그램이 tr 배경을 무시하기도 해서 칸마다도 칠한다
hexc = color_hex(x.get("color"))
ctd = f"{td}background:{hexc};" if hexc else td
tr_style = f' style="background:{hexc}"' if hexc else ""
b = line_boxes(x)
detail = (f'<td style="{ctd}{r}">{e(b["per"])}</td><td style="{ctd}{r}">{e(b["count"])}</td>') if simple else (
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>')
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 ""
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>{detail}'
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
foot_pp = f'{fmt_num(money["pp_kg"], 0)} kg' if money["pp_kg"] is not None else ""
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
bg = "background:#f6f7f9;"
box_totals = [t for t in (line_boxes(x)["total"] for x in lines) if t is not None]
foot_boxes = f"{sum(box_totals):,}박스" if box_totals else ""
if box_totals and len(box_totals) < len(lines):
foot_boxes += f" (미설정 {len(lines) - len(box_totals)}종 제외)"
head_detail = f'<th style="{td}">박스당 수량</th><th style="{td}">박스 수</th>' if simple else (
f'<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>')
foot_detail = f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_boxes)}</th>' if simple else (
f'<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>')
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 style="border-collapse:collapse;margin:8px 0 16px">{fact_rows}</table>'
'<table style="border-collapse:collapse;min-width:640px">'
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'<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}">{"번호" if simple else "No"}</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
f'<th style="{td}">수량</th>{head_detail}'
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}{r}">{total:,}</th>{foot_detail}'
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>'
@@ -346,6 +397,138 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
return {"subject": subject, "text": "\n".join(text), "html": html}
# 발주 메일 본문 고치기(2026-10-27) — 미리보기 창에서 사람이 고친 HTML 을 그대로 보낸다.
# 표·서식(인라인 style)은 남기고 스크립트·이벤트 속성·외부 리소스(url()·img)는 뺀다. 글 버전은 고친 HTML 에서 다시 만든다.
MAIL_HTML_MAX = 300_000
_MAIL_TAGS = {"div", "p", "br", "span", "b", "strong", "i", "em", "u", "s", "strike", "font", "a", "ul", "ol", "li",
"h1", "h2", "h3", "h4", "blockquote", "sub", "sup", "hr",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup", "col", "caption"}
_MAIL_VOID = {"br", "hr", "col"}
_MAIL_DROP = {"script", "style", "iframe", "object", "embed", "head", "title", "template", "noscript", "svg", "math",
"textarea", "select", "button", "form", "input", "link", "meta"}
_MAIL_ATTRS = {"colspan", "rowspan", "cellpadding", "cellspacing", "border", "align", "valign", "width", "height", "color"}
_MAIL_STYLE_PROPS = {"color", "background", "background-color", "font-family", "font-size", "font-weight", "font-style",
"text-decoration", "text-align", "vertical-align", "white-space", "line-height", "height", "width",
"min-width", "max-width", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left",
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "border", "border-top",
"border-right", "border-bottom", "border-left", "border-color", "border-collapse", "border-spacing"}
_MAIL_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()'\"-]{1,120}$")
_MAIL_ATTR_VALUE_RE = re.compile(r"^[#\w%.-]{1,20}$")
def _mail_style(value: str) -> str:
out = []
for decl in value.split(";"):
prop, _, val = decl.partition(":")
prop, val = prop.strip().lower(), val.strip()
if prop == "text-decoration-line": # 서식 막대(Chrome execCommand)가 밑줄·취소선을 이렇게 만든다 — 메일 프로그램은 text-decoration 만 아는 곳이 많다
prop = "text-decoration"
if prop in _MAIL_STYLE_PROPS and _MAIL_STYLE_VALUE_RE.match(val) and not re.search(r"url|expression|@import", val, re.I):
out.append(f"{prop}:{val}")
return ";".join(out)
class _MailSanitizer(_html_parser.HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.out: list[str] = []
self.stack: list[str] = []
self.skip = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in _MAIL_DROP:
self.skip += 1
return
if self.skip or tag not in _MAIL_TAGS:
return
extra = ""
for k, v in attrs:
v = (v or "").strip()
if k == "style":
style = _mail_style(v)
if style:
extra += f' style="{_html.escape(style)}"'
elif k == "href" and tag == "a" and re.match(r"^(https?:|mailto:)", v, re.I):
extra += f' href="{_html.escape(v)}"'
elif k in _MAIL_ATTRS and _MAIL_ATTR_VALUE_RE.match(v):
extra += f' {k}="{_html.escape(v)}"'
self.out.append(f"<{tag}{extra}>")
if tag not in _MAIL_VOID:
self.stack.append(tag)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in _MAIL_VOID:
self.handle_starttag(tag, attrs)
def handle_endtag(self, tag: str) -> None:
if tag in _MAIL_DROP:
self.skip = max(0, self.skip - 1)
return
if self.skip or tag not in self.stack:
return
while self.stack:
t = self.stack.pop()
self.out.append(f"</{t}>")
if t == tag:
break
def handle_data(self, data: str) -> None:
if not self.skip:
self.out.append(_html.escape(data, quote=False))
def result(self) -> str:
self.close()
while self.stack:
self.out.append(f"</{self.stack.pop()}>")
return "".join(self.out)
class _MailText(_html_parser.HTMLParser):
"""HTML → 글 버전 — 문단·줄은 줄바꿈, 표 칸은 " | " 로 잇는다."""
_BLOCK = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "blockquote", "table", "hr"}
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self.cell = False # 이 줄에 이미 칸이 있다 — 다음 칸 앞에 구분자
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "br" or tag in self._BLOCK:
self.parts.append("\n")
self.cell = False
elif tag in ("td", "th"):
if self.cell:
self.parts.append(" | ")
self.cell = True
if tag == "li":
self.parts.append("- ")
def handle_data(self, data: str) -> None:
self.parts.append(re.sub(r"\s+", " ", data.replace("\xa0", " ")))
def clean_mail_html(html: Any) -> str:
"""고친 메일 본문 HTML → 보낼 HTML(허용 태그·속성·글자 서식만). 너무 길거나 글이 없으면 ValueError."""
raw = str(html or "")
if len(raw) > MAIL_HTML_MAX:
raise ValueError("메일 본문이 너무 깁니다.")
p = _MailSanitizer()
p.feed(raw)
out = p.result()
if not mail_html_to_text(out).strip():
raise ValueError("메일 본문이 비어 있습니다.")
return out
def mail_html_to_text(html: str) -> str:
p = _MailText()
p.feed(str(html or ""))
p.close()
lines = [ln.strip() for ln in "".join(p.parts).split("\n")]
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
# ════════════════════════════════════════════════════════════
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
@@ -380,6 +563,15 @@ def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
def line_usage(x: dict[str, Any]) -> dict[str, Decimal | None]:
"""발주 품목 한 줄의 발주 수량 전체 사용량(kg) — 전체 무게 = 개당 g × 수량, 은 = 전체 무게 × %, PP 사용량 = 전체 − 은
(은 함유량이 없으면 PP 사용량도 없음 — order_totals 의 pp_use_kg 와 같은 기준). 메일 표·발주서 화면 품목 표가 같이 쓴다."""
w, pct, q = to_dec(x.get("weight_g")), to_dec(x.get("silver_pct")), int(x["qty"])
total_kg = w * q / Decimal(1000) if w is not None else None
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
return {"total_kg": total_kg, "ag_kg": ag_kg, "pp_use_kg": total_kg - ag_kg if ag_kg is not None else None}
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)
@@ -394,7 +586,8 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
q = int(x["qty"])
a = line_amount(q, x.get("unit_price"))
if a is None:
missing += 1
if not is_bag(x.get("item_name")): # 봉투·백은 단가가 원래 없음 — "단가 미입력" 안내에서 뺀다
missing += 1
else:
amount = (amount or Decimal(0)) + a
w = to_dec(x.get("weight_g"))
@@ -404,7 +597,7 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
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,
return {"amount": amount, "missing_price": missing, "pp_kg": pp, "silver_g": ag,
"pp_use_kg": use}
@@ -431,8 +624,101 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
def has_values(p: dict[str, Any]) -> bool:
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS)
or p.get("boxes_per_pallet") is not None)
# ════════════════════════════════════════════════════════════
# 박스 입수(2026-10-21, 마이그레이션 007) — 통·뚜껑이 한 박스에 몇 개. 뚜껑이 없는 상품은 빈칸.
# 새 발주서 화면이 수량 → 통·뚜껑 박스 수(올림)·전체 파렛트(1파렛트 = PALLET_BOXES 박스, 올림)를 계산한다(메일엔 안 넣음).
# ════════════════════════════════════════════════════════════
BOX_FIELDS = {"body_per_box": "통 수량(박스)", "lid_per_box": "뚜껑 수량(박스)"}
MAX_PER_BOX = 1_000_000
PALLET_BOXES = 30
def parse_per_box(raw: Any, *, key: str = "", label: str = "") -> int | None:
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
label = label or BOX_FIELDS[key]
s = str(raw if raw is not None else "").replace(",", "").strip()
if not s:
return None
if not s.isdigit():
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
n = int(s)
if n < 1:
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(없으면 빈칸).")
if n > MAX_PER_BOX:
raise ValueError(f"{label}이(가) 너무 큽니다.")
return n
def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
# 봉투·백(2026-11-04, 마이그레이션 008) — 이름으로 판단(저장 안 함). 뚜껑 없음, 박스당 수량 = body_per_box, 1파렛트 박스 수는 상품마다.
BAG_NAME_WORDS = ("미라클 봉투", "미라클백")
def is_bag(name: Any) -> bool:
return any(word in str(name or "") for word in BAG_NAME_WORDS)
def validate_bag_values(values: dict[str, Any]) -> dict[str, int | None]:
return {"body_per_box": parse_per_box(values.get("body_per_box"), label="박스당 수량"), "lid_per_box": None,
"boxes_per_pallet": parse_per_box(values.get("boxes_per_pallet"), label="1파렛트당 박스 수량")}
def box_info(row: dict[str, Any]) -> dict[str, Any]:
"""발주서 화면 박스 계산 값 — 008 미적용(열 없음)이면 모두 일반 상품으로."""
bag = "boxes_per_pallet" in row and is_bag(row.get("item_name"))
return {"body_per_box": row.get("body_per_box"), "lid_per_box": None if bag else row.get("lid_per_box"),
"is_bag": bag, "boxes_per_pallet": row.get("boxes_per_pallet") if bag else None}
# ════════════════════════════════════════════════════════════
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
# 색상 = 키 → (이름, 칸 색). 발주 메일 품목 표에서 색상 있는 품목 줄 전체 배경 = 칸 색(옅게 — 글자가 읽히게).
# ════════════════════════════════════════════════════════════
COLORS = {"none": ("색없음", ""), "orange": ("오렌지", "#FFD8B0"), "blue": ("파랑", "#CFE0FA"),
"gray": ("회색", "#DDDFE3"), "ivory": ("아이보리색", "#FFF6D9")}
MAX_GROUP_NAME = 100
def norm_color(raw: Any) -> str:
"""색상 키(none·orange·blue·gray·ivory). 빈칸 = none. 모르는 값은 ValueError."""
key = str(raw if raw is not None else "").strip().lower() or "none"
if key not in COLORS:
raise ValueError("색상은 " + "·".join(v[0] for v in COLORS.values()) + " 중에서 고르세요.")
return key
def color_hex(key: Any) -> str:
"""색상 키 → 칸 색(#RRGGBB). 색없음·모름 = ''."""
return COLORS.get(str(key or "none"), ("", ""))[1]
def color_name(key: Any) -> str:
return COLORS.get(str(key or "none"), COLORS["none"])[0]
def validate_group(values: dict[str, Any]) -> dict[str, Any]:
"""그룹 저장 값 — 이름(필수, 100자)·은 함유량(빈칸 = 미입력)·색상·순서."""
name = str(values.get("name") or "").strip()
if not name:
raise ValueError("그룹 이름을 넣으세요.")
if len(name) > MAX_GROUP_NAME:
raise ValueError(f"그룹 이름은 {MAX_GROUP_NAME}자까지입니다.")
try:
sort_order = int(str(values.get("sort_order") or "0").strip() or 0)
except ValueError:
raise ValueError("순서는 숫자로 넣으세요.") from None
return {"name": name, "silver_pct": parse_decimal(values.get("silver_pct"), key="silver_pct"),
"color": norm_color(values.get("color")), "sort_order": max(-9999, min(9999, sort_order))}
# ════════════════════════════════════════════════════════════
@@ -475,6 +761,41 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
return out
def rotate_image(data: bytes, degrees: int) -> bytes:
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
from io import BytesIO # noqa: WPS433
from PIL import Image, ImageOps # noqa: WPS433
if degrees not in (90, 270):
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
kind = sniff_image(data)
if kind == "image/heic":
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
try:
im = Image.open(BytesIO(data))
if getattr(im, "n_frames", 1) > 1:
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
icc = im.info.get("icc_profile")
im = ImageOps.exif_transpose(im)
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
if fmt in ("JPEG", "WEBP"):
opts["quality"] = 92
buf = BytesIO()
im.save(buf, format=fmt, **opts)
except ValueError:
raise
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
out = buf.getvalue()
if len(out) > MAX_PHOTO_BYTES:
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
return out
# ════════════════════════════════════════════════════════════
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
@@ -482,7 +803,9 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
# ════════════════════════════════════════════════════════════
SETTING_LOGISTICS_EMAILS = "logistics_emails"
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"}
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
@@ -638,3 +961,38 @@ def sabangnet_xlsx(rows: list[list[Any]]) -> bytes:
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,32 @@
{# 오른쪽 달력(2026-10-21) — 입출고 모든 화면 오른쪽 위 300×320, 오른쪽 열 너비 = 달력 너비.
프로젝트 달력과 같은 모양(일요일 시작 · 요일 줄 회색 · 오늘 검은 동그라미 · 토 파랑 · 일/공휴일 빨강 · 다른 달 흐리게).
날짜 칸 = 발주(발주일, 파랑) · 입고(입고일, 초록) 건수, 누르면 그날 목록(발주서로 이동). 내용은 inout.js 가 GET /inout/api/calendar 로 그린다. #}
<aside class="io-side" aria-label="발주·입고 달력">
<div class="io-cal" id="io-cal" data-month="{{ today.strftime('%Y-%m') }}">
<div class="io-cal-head">
<button type="button" class="io-cal-nav" data-step="-1" aria-label="이전 달" title="이전 달">‹</button>
<h3 class="io-cal-title" aria-live="polite">{{ today.year }}년 {{ today.month }}월</h3>
<button type="button" class="io-cal-nav" data-step="1" aria-label="다음 달" title="다음 달">›</button>
<button type="button" class="io-cal-today">오늘</button>
</div>
<div class="io-cal-box">
<div class="io-cal-wd" aria-hidden="true">
<span class="is-sun">일</span><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span>
</div>
<div class="io-cal-days" role="grid"></div>
</div>
</div>
{# 화면을 옮겨도 달력이 다시 그려지지 않게 — 마지막 달력(sessionStorage, inout.js 가 저장)을 그리기 전에 바로 붙인다.
inout.js 는 서버 값을 다시 받아 바뀐 게 있을 때만 다시 그린다. #}
<script>(function () {
try {
var c = JSON.parse(sessionStorage.getItem("io_cal_v1") || "null"), cal = document.getElementById("io-cal");
if (!c || !c.html || !c.month || !cal) return;
cal.dataset.month = c.month;
cal.dataset.restored = "1";
cal.querySelector(".io-cal-title").textContent = c.title;
cal.querySelector(".io-cal-days").innerHTML = c.html;
} catch (e) {}
})();</script>
<p class="io-cal-legend"><i class="io-cal-m is-order">n</i>발주 <i class="io-cal-m is-receipt">n</i>입고 <span class="io-sub">· 날짜를 누르면 목록</span></p>
</aside>
@@ -26,3 +26,8 @@
{%- endmacro %}
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
{# 색상 사각형(006) — 색이 칠해진 네모. 색없음은 빗금 없는 흰 네모 + 테두리. colors = store.COLORS #}
{% macro swatch(key, colors) -%}
<i class="io-swatch{% if not colors.get(key or 'none', ('', ''))[1] %} is-none{% endif %}" style="background:{{ colors.get(key or 'none', ('', ''))[1] or '#fff' }}" aria-hidden="true"></i>
{%- endmacro %}
@@ -1,9 +1,10 @@
{% from "inout/_macros.html" import ymd %}
{% from "inout/_macros.html" import ymd, swatch %}
{# 옵션 팝업 내용(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="groups" tabindex="-1">상품 그룹 <span class="io-dlg-count">{{ groups|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>
@@ -20,7 +21,11 @@
<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>
<td><span class="io-person">
{% if c.picture %}<img class="io-avatar" src="{{ c.picture }}" alt="" referrerpolicy="no-referrer" loading="lazy" />
{% else %}<svg class="io-avatar io-avatar-empty" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="12" fill="#d5d9de"/><circle cx="12" cy="9.5" r="4" fill="#fff"/><path d="M4.6 19.6a8.6 8.6 0 0 1 14.8 0A11.9 11.9 0 0 1 12 24a11.9 11.9 0 0 1-7.4-4.4z" fill="#fff"/></svg>{% endif %}
<span class="io-person-text"><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></span>
</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>
@@ -37,6 +42,12 @@
<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">
@@ -75,6 +86,52 @@
</table>
</section>
<section class="io-dlg-pane" data-pane="groups" role="tabpanel" hidden>
{% if not groups_ready %}
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
{% else %}
<p class="io-help">
그룹마다 <b>은(Ag) 함유량</b>·<b>색상</b>을 한 번만 넣습니다 — <b>상품 정보</b> 탭에서 상품마다 그룹을 고르면 그 상품은 그룹 값을 씁니다(그룹 없는 상품은 상품마다).
색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다. 그룹을 지우면 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.
</p>
{% for g in groups %}<form method="post" action="/inout/settings/groups" id="io-g{{ g.id }}" class="io-dlg-form io-group-form"><input type="hidden" name="id" value="{{ g.id }}" /></form>{% endfor %}
<form method="post" action="/inout/settings/groups" id="io-gnew" class="io-dlg-form io-group-form"></form>
<table class="io-dlg-table io-group-table">
<colgroup><col class="w-gname" /><col class="w-num" /><col class="w-color" /><col class="w-sort" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>그룹 이름</th><th class="io-r">은 함유량(%)</th><th>색상</th><th class="io-c">순서</th><th class="io-c">상품</th><th></th></tr></thead>
<tbody>
{% for g in groups %}
{% set gf = 'io-g' ~ g.id %}
<tr>
<td><input class="io-in" form="{{ gf }}" type="text" name="name" value="{{ g.name }}" maxlength="100" required aria-label="그룹 이름" /></td>
<td><input class="io-in io-in-num" form="{{ gf }}" type="text" name="silver_pct" value="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ g.name }} 은 함유량" /></td>
<td><span class="io-color">{{ swatch(g.color, colors) }}<select class="io-in io-color-select" form="{{ gf }}" name="color" aria-label="{{ g.name }} 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if g.color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
</select></span></td>
<td class="io-c"><input class="io-in io-in-num" form="{{ gf }}" type="number" name="sort_order" value="{{ g.sort_order }}" aria-label="순서" /></td>
<td class="io-c io-sub">{{ g.product_count }}개</td>
<td class="io-btns">
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
<button form="{{ gf }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/groups/{{ g.id }}/delete"
formnovalidate data-confirm="그룹 '{{ g.name }}' 을(를) 지울까요? 그룹 상품 {{ g.product_count }}개는 그룹 없음(상품마다 값)으로 바뀝니다.">지우기</button>
</td>
</tr>
{% endfor %}
<tr class="io-new-row">
<td><input class="io-in" form="io-gnew" type="text" name="name" maxlength="100" required placeholder="새 그룹 이름" aria-label="새 그룹 이름" /></td>
<td><input class="io-in io-in-num" form="io-gnew" type="text" name="silver_pct" inputmode="decimal" placeholder="%" aria-label="새 그룹 은 함유량" /></td>
<td><span class="io-color">{{ swatch('none', colors) }}<select class="io-in io-color-select" form="io-gnew" name="color" aria-label="새 그룹 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}">{{ c[0] }}</option>{% endfor %}
</select></span></td>
<td class="io-c"><input class="io-in io-in-num" form="io-gnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
<td></td>
<td class="io-btns"><button form="io-gnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
</tr>
</tbody>
</table>
{% endif %}
</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>
@@ -82,6 +139,9 @@
<p class="io-help">
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 <b>봉투·백</b> 표에서 <b>박스당 수량</b>·<b>1파렛트당 박스 수량</b>을 넣습니다(단가·무게·은 없음).
</p>
<div class="io-prod-bar">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
@@ -92,23 +152,57 @@
</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>
{# 봉투·백(008) = 일반 상품과 표를 나눔, 짧은 목록이라 위에. 박스 칸 두 개만 다르고 나머지 칸은 같다 #}
{% set bags = products|selectattr('is_bag')|list %}
{% for bag_table, rows in [(true, bags), (false, products|rejectattr('is_bag')|list)] if rows %}
<div class="io-prod-part">
{% if bags %}<div class="io-prod-part-title">{{ '봉투·백' if bag_table else '일반 상품' }} <span class="io-sub">{{ rows|length }}개</span></div>{% endif %}
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}{% if not bag_table %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% endif %}{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}{% if not bag_table %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% endif %}{% if bag_table %}<th title="한 박스에 몇 개">박스당 수량</th><th title="한 파렛트에 몇 박스">1파렛트당 박스 수량</th>{% elif boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<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>
{% for p in rows %}
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
<td class="io-code">{{ p.item_code }}{% if bag_table %}
{# 봉투·백엔 단가·무게·은 칸이 없다 — 전에 넣은 값이 저장 때 지워지지 않게 숨은 칸으로 그대로 보낸다 #}
<input type="hidden" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" />
<input type="hidden" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" />
<input type="hidden" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" />{% endif %}</td>
<td class="io-prod-name">{{ p.item_name }}</td>
{% if groups_ready %}
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
<option value="" data-silver="" data-color="">그룹 없음</option>
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
</select></td>
{% endif %}
{% if not bag_table %}
<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><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
{% endif %}
{% if bag_table %}
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 박스당 수량" /></td>
<td><input class="io-in io-in-num" data-key="boxes_per_pallet" value="{{ '{:,}'.format(p.boxes_per_pallet) if p.boxes_per_pallet else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 1파렛트당 박스 수량" /></td>
{% elif boxes_ready %}
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
{% endif %}
{% if groups_ready %}
<td><span class="io-color io-own">{{ swatch(p.own_color, colors) }}<select class="io-in io-color-select" data-key="color" aria-label="{{ p.item_code }} 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if p.own_color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
</select></span>
<span class="io-color io-group-val" title="그룹 값 — 그룹에서 바꿉니다">{{ swatch(p.color, colors) }}<span class="io-color-name">{{ colors[p.color][0] if p.color in colors else '' }}</span></span></td>
{% endif %}
<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>
{% endfor %}
</div>
{% else %}
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
+5 -2
View File
@@ -1,8 +1,9 @@
{% 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=20261019c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io">
{% include "inout/_nav.html" %}
@@ -67,5 +68,7 @@
</div>
</div>
</section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
@@ -20,7 +20,7 @@
</footer>
</dialog>
{%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
@@ -29,6 +29,7 @@
{% 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 %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io">
{% include "inout/_nav.html" %}
@@ -104,10 +105,10 @@
{% endif %}
<div class="erp-table-wrap">
<table class="erp-table io-table">
<table class="erp-table io-table io-items-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 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" title="발주 수량 전체 PP 사용량 = 전체 무게 − 은 무게(아래 작은 글씨 = 개당 무게)">PP 사용량</th><th class="io-num io-col-spec" title="발주 수량 전체 은 무게(아래 작은 글씨 = 함유량 %·개당 은)">은(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>
@@ -118,11 +119,12 @@
<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) %}
{% set amt = line_amount(ln.qty, ln.unit_price) %}{% set ag = silver_g(ln.weight_g, ln.silver_pct) %}{% set use = line_usage(ln) %}
<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>
{# 발주 수량 전체 사용량(2026-10-21) — PP 사용량·은 함유량 kg(메일 표와 같은 값), 아래 작은 글씨 = 개당 값 #}
<td class="io-num io-col-spec">{% if use.pp_use_kg is not none %}{{ fmt_num(use.pp_use_kg, 3) }}kg{% else %}-{% endif %}{% if ln.weight_g is not none %}<div class="erp-row-sub">{{ fmt_num(ln.weight_g) }}g/개</div>{% endif %}</td>
<td class="io-num io-col-spec">{% if use.ag_kg is not none %}{{ fmt_num(use.ag_kg, 3) }}kg{% else %}-{% endif %}{% if ln.silver_pct is not none %}<div class="erp-row-sub">{{ fmt_num(ln.silver_pct, 4) }}%{% if ag is not none %} · {{ fmt_num(ag, 4) }}g/개{% endif %}</div>{% endif %}</td>
{% endif %}
{% if not items_limited %}
<td class="io-num">{{ n(ln.received) }}</td>
@@ -138,12 +140,13 @@
</tbody>
{% if show_prices and order.lines %}
<tfoot><tr class="io-total-row">
<td colspan="3">합계</td>
<td colspan="3" class="io-total-label">합계</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>
<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>
{# 합계 무게 = 소수 첫째 자리에서 반올림(정수 kg) #}
<td class="io-num io-col-spec">{% if totals.pp_use_kg is not none %}{{ fmt_num(totals.pp_use_kg, 0) }} kg{% else %}-{% endif %}</td>
<td class="io-num io-col-spec">{% if totals.silver_g is not none %}{{ fmt_num(totals.silver_g / 1000, 0) }} kg{% else %}-{% endif %}</td>
{% if not items_limited %}<td colspan="3"></td>{% endif %}
{% if receiving %}<td></td>{% endif %}
</tr></tfoot>
@@ -158,8 +161,8 @@
<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 viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
사진 고르기·찍기
<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>
@@ -229,6 +232,10 @@
<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>
{% if photo_admin %}
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="270" title="왼쪽으로 돌리기" aria-label="왼쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4v6h6"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L3 10"/></svg></button>
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="90" title="오른쪽으로 돌리기" aria-label="오른쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4v6h-6"/><path d="M20.5 15a9 9 0 1 1-2.1-9.4L21 10"/></svg></button>
{% endif %}
<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>
@@ -252,5 +259,7 @@
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
{% endif %}
</section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
@@ -1,11 +1,12 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io">
{% include "inout/_nav.html" %}
<form class="erp-card-block io-order-form" method="post" id="io-order-form"
<form class="erp-card-block io-order-form" method="post" id="io-order-form"{% if boxes_ready %} data-pallet-boxes="{{ pallet_boxes }}"{% endif %}
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>
@@ -29,11 +30,11 @@
<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>
<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>{% if boxes_ready %}<th class="io-col-box" title="통·뚜껑 박스 입수(옵션 → 상품 정보)로 계산 — 저장·메일에는 넣지 않습니다">통·뚜껑 박스</th>{% endif %}<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 '' }}">
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}" data-bag="{{ '1' if ln.is_bag else '' }}" data-pallet-box="{{ ln.boxes_per_pallet or '' }}"{% endif %}>
<td class="io-col-no"></td>
<td class="io-item-cell">
<input type="hidden" name="item_code" value="{{ ln.code }}" />
@@ -42,32 +43,51 @@
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-qty"><span class="io-qty-wrap"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" />{% if boxes_ready %}<span class="io-steps"><button type="button" class="io-step" data-step="-1" aria-label="공배수만큼 줄이기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button><button type="button" class="io-step" data-step="1" aria-label="공배수만큼 늘리기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button></span>{% endif %}</span></td>
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
<td class="io-col-money io-amount">-</td>
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
<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">
<tfoot><tr><td colspan="{{ 8 if boxes_ready else 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>
{% if boxes_ready %}
{# 박스·파렛트(2026-10-21) — 통·뚜껑 박스 수 합계 → 전체 파렛트(1파렛트 = {{ pallet_boxes }}박스, 올림). 화면 계산만(저장·메일 없음) #}
<div class="io-pallet" id="io-pallet" aria-live="polite">
<span>통 <b data-k="body">0</b>박스</span><span>뚜껑 <b data-k="lid">0</b>박스</span><span>전체 <b data-k="boxes">0</b>박스</span>
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
{# 파렛트 그림 — 꽉 찬 파렛트 + 잔량 파렛트(실린 박스만큼 색, %·몇 박스 더) #}
<span class="io-pallet-vis" data-k="vis"></span>
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
</div>
{# 봉투·백(008) — 상품마다 1파렛트 박스 수가 달라 통·뚜껑 파렛트와 따로 셈 #}
<div class="io-pallet" id="io-pallet-bag" aria-live="polite" hidden>
<span>봉투·백 <b data-k="boxes">0</b>박스</span>
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
<span class="io-pallet-vis" data-k="vis"></span>
<span class="erp-muted" data-k="note"></span>
</div>
{% endif %}
</td></tr></tfoot>
</table>
</div>
<template id="io-line-tpl">
<tr class="io-line">
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box="" data-bag="" data-pallet-box=""{% endif %}>
<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-qty"><span class="io-qty-wrap"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" />{% if boxes_ready %}<span class="io-steps"><button type="button" class="io-step" data-step="-1" aria-label="공배수만큼 줄이기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button><button type="button" class="io-step" data-step="1" aria-label="공배수만큼 늘리기" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button></span>{% endif %}</span></td>
<td class="io-col-money io-price">-</td>
<td class="io-col-money io-amount">-</td>
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
<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>
@@ -79,5 +99,7 @@
</div>
</form>
</section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
@@ -1,8 +1,9 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io">
{% include "inout/_nav.html" %}
@@ -87,5 +88,7 @@
</div>
{% endif %}
</section>
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
+22
View File
@@ -0,0 +1,22 @@
# [라이브커머스] 라이브 커머스 모듈 — `app/modules/live/`, `live_db`(2026-11-04)
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인).
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
- **호스트 설정** `/live/settings` — Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number·Tiktok Handle(`@`·주소를 붙여 넣어도 계정명만 저장).
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·틱톡·사용 여부)만 넘긴다.
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
- **호스트 비용**(`store.session_pay`, 저장 안 함 — 화면마다 계산) = 시간 × RM 25(`HOURLY_RATE`) + 판매금액 × 10%(`COMMISSION_PERCENT`). 요율이 코드 상수라 바꾸면 지난 방송 금액도 바뀐다.
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
**AD SPEND** = 날짜별 광고비 `live_daily_ad_spend`(마이그레이션 002, `POST /live/ad-spend`, 빈칸 = 지우기), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). 002 미적용이면 0 으로 보이고 저장만 안내.
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
+21
View File
@@ -0,0 +1,21 @@
"""라이브 커머스(live) 모듈 — 말레이시아 라이브 방송의 호스트 정보와 방송 스케줄(2026-11-04).
- 라우터: `router.py` (prefix=/live) · 저장소: `db.py` (live_db) · 순수 함수: `store.py`(입력 검사·표시 형식)
- 템플릿: `templates/live/`, 화면 스크립트·스타일 `static/live.{js,css}`
LIVE_DB_URL 미설정이면 build_live_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `live`.
"""
from typing import Any
from .router import router
__all__ = ["router", "build_live_store"]
def build_live_store(*, dsn: str | None) -> Any:
if not dsn:
return None
from .db import LiveDBStore # 지연 import
return LiveDBStore(dsn)
+175
View File
@@ -0,0 +1,175 @@
"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04).
- 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:<pwd>@postgres-db:5432/live_db)
- 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
"""
from __future__ import annotations
from datetime import date, time
from decimal import Decimal
from typing import Any
from psycopg.errors import ForeignKeyViolation, UndefinedTable
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from . import store
from .i18n import LiveError
_HOST_COLUMNS = ("full_name", "phone", "email", "address", "bank_name", "bank_account", "tiktok_handle")
class LiveDBStore:
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
self._pool.open(wait=False)
def close(self) -> None:
self._pool.close()
# ── 호스트 ─────────────────────────────────────────────
def list_hosts(self) -> list[dict[str, Any]]:
"""전체 정보(계좌 포함) — 설정 화면(ERP 관리자)에서만 쓴다."""
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM live_hosts ORDER BY is_active DESC, full_name, id").fetchall()
def host_choices(self) -> list[dict[str, Any]]:
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
with self._pool.connection() as conn:
return conn.execute("SELECT id, full_name, tiktok_handle, is_active FROM live_hosts "
"ORDER BY full_name, id").fetchall()
def save_host(self, host_id: int | None, values: dict[str, str], *, is_active: bool, by: str) -> int:
cols = [values[k] for k in _HOST_COLUMNS]
with self._pool.connection() as conn:
if host_id is None:
row = conn.execute(
"INSERT INTO live_hosts (full_name, phone, email, address, bank_name, bank_account, tiktok_handle, "
"is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id",
(*cols, is_active, by, by)).fetchone()
else:
row = conn.execute(
"UPDATE live_hosts SET full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
"tiktok_handle=%s, is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
(*cols, is_active, by, host_id)).fetchone()
if not row:
raise LiveError("호스트를 찾을 수 없습니다.")
return int(row["id"])
def delete_host(self, host_id: int) -> None:
try:
with self._pool.connection() as conn:
row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone()
except ForeignKeyViolation:
raise LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None
if not row:
raise LiveError("호스트를 찾을 수 없습니다.")
# ── 방송 스케줄 ─────────────────────────────────────────
def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]:
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT b.*, h.full_name AS host_name, h.tiktok_handle FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
"WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id",
(start, end)).fetchall()
images = conn.execute(
"SELECT id, broadcast_id, filename FROM live_broadcast_images WHERE broadcast_id = ANY(%s) ORDER BY id",
([r["id"] for r in rows],)).fetchall()
for r in rows:
r["images"] = [i for i in images if i["broadcast_id"] == r["id"]]
return rows
def save_broadcast(self, broadcast_id: int | None, values: dict[str, Any], images: list[dict[str, Any]], *, by: str) -> int:
"""방송·이미지를 한 트랜잭션으로. 사용 안 함 호스트는 이미 그 호스트인 방송을 고칠 때만 허용."""
with self._pool.connection() as conn, conn.transaction():
current = None
if broadcast_id is not None:
found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
if not found:
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
current = found["host_id"]
host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone()
if not host:
raise LiveError("호스트를 찾을 수 없습니다.")
if not host["is_active"] and values["host_id"] != current:
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"],
values["sales_amount"], by)
if broadcast_id is None:
broadcast_id = int(conn.execute(
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, venue, sales_amount, updated_by, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
else:
conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, venue=%s, "
"sales_amount=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
have = conn.execute("SELECT count(*) AS n FROM live_broadcast_images WHERE broadcast_id=%s", (broadcast_id,)).fetchone()["n"]
if have + len(images) > store.MAX_IMAGES:
raise LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have)
for im in images:
conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
(broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by))
return broadcast_id
def delete_broadcast(self, broadcast_id: int) -> None:
with self._pool.connection() as conn:
if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone():
raise LiveError("방송을 찾을 수 없습니다.")
def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None:
"""달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로."""
with self._pool.connection() as conn, conn.transaction():
row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
if not row:
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
(day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id))
def swap_broadcasts(self, first_id: int, second_id: int, *, by: str) -> None:
"""달력에서 다른 방송 위로 놓기 — 두 방송의 날짜·시간을 맞바꾼다(id 순서로 잠가 교착 방지)."""
if first_id == second_id:
return
with self._pool.connection() as conn, conn.transaction():
rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
([first_id, second_id],)).fetchall()
if len(rows) != 2:
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])):
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
(other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"]))
# ── 날짜별 광고비(002) ───────────────────────────────────
def ad_spends(self, start: date, end: date) -> dict[date, Decimal]:
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT ad_date, ad_spend FROM live_daily_ad_spend WHERE ad_date >= %s AND ad_date < %s", (start, end)).fetchall()
except UndefinedTable:
return {}
return {r["ad_date"]: r["ad_spend"] for r in rows}
def save_ad_spend(self, day: date, amount: Decimal | None, *, by: str) -> None:
"""빈칸(None) = 지우기."""
try:
with self._pool.connection() as conn:
if amount is None:
conn.execute("DELETE FROM live_daily_ad_spend WHERE ad_date=%s", (day,))
else:
conn.execute("INSERT INTO live_daily_ad_spend (ad_date, ad_spend, updated_by) VALUES (%s,%s,%s) "
"ON CONFLICT (ad_date) DO UPDATE SET ad_spend=EXCLUDED.ad_spend, updated_by=EXCLUDED.updated_by, updated_at=now()",
(day, amount, by))
except UndefinedTable:
raise LiveError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None
# ── 결과 이미지 ─────────────────────────────────────────
def get_image(self, image_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone()
def delete_image(self, image_id: int) -> None:
with self._pool.connection() as conn:
if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone():
raise LiveError("이미지를 찾을 수 없습니다.")
+112
View File
@@ -0,0 +1,112 @@
"""라이브 커머스 한글·영문 전환(2026-11-04) — 한글 문구가 키, 없으면 한글 그대로. 언어는 쿠키 `live_lang`(브라우저마다).
새 문구는 여기에도 넣는다 — tests/test_live.py 가 템플릿·오류 문구가 모두 있는지, 영문 화면에 한글이 없는지 확인한다.
"""
from __future__ import annotations
from typing import Any
LANG_COOKIE = "live_lang"
EN: dict[str, str] = {
# 위 막대·보기
"이전 달": "Previous month", "다음 달": "Next month", "보기 방식": "View", "표": "Table", "달력": "Calendar",
"호스트 설정": "Host Settings", "+ 방송 추가": "+ Add Broadcast", "언어": "Language",
"방송을 추가하려면 먼저 호스트를 등록해야 합니다.": "Register a host before adding a broadcast.",
"ERP 관리자에게 등록을 요청하세요.": "Ask an ERP admin to register one.",
# 방송 창
"방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host",
"사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time",
"시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "방송 장소": "Venue", "판매금액 (RM)": "Sales (RM)",
"방송 후 입력": "Enter after the broadcast",
"방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)": "Result images (JPG, PNG, WebP, 8 MB each, up to {n} per broadcast)",
"취소": "Cancel", "저장": "Save", "확인": "OK",
# 표
"날짜": "Date", "시간": "Time", "판매금액(RM)": "Sales (RM)", "커미션 10%(RM)": "Commission 10% (RM)",
"호스트 비용(RM)": "Host Fee (RM)", "방송 결과": "Result", "고치기": "Edit", "지우기": "Delete",
"기본 요금 RM {base} + 커미션 RM {commission}": "Base RM {base} + commission RM {commission}",
"{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.",
"이 달에 등록한 방송이 없습니다.": "No broadcasts this month.",
# 달력
"판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales",
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS", "날짜로 이동": "Jump to Date",
"팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.":
"Tip: Drag & drop any host header to move or swap dates. Scroll right to see all {n} days of the month.",
"{date} {slot} 방송 추가": "Add broadcast on {date} {slot}", "{name} {date} {times} 고치기": "Edit {name} {date} {times}",
"{date} 광고비 고치기": "Edit ad spend for {date}", "방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
# 호스트 설정
"◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host",
"이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name",
"계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active",
"{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.",
"사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)",
# 화면 스크립트(live.js)
"서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.": "Could not reach the server. Your entries are kept — please try saving again.",
"이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?", "{day} 광고비 (RM) — 비우면 지웁니다": "{day} ad spend (RM) — leave empty to clear",
# 저장 결과·입력 오류
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.", "광고비를 저장했습니다.": "Ad spend saved.", "방송을 지웠습니다.": "Broadcast deleted.",
"이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.",
"잘못된 요청입니다.": "Invalid request.",
"이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).",
"이메일 형식이 올바르지 않습니다.": "The email format is invalid.", "전화번호는 숫자·+·-·괄호만 입력하세요.": "Phone Number may contain only digits, +, - and brackets.",
"계좌번호는 숫자·-만 입력하세요.": "Bank Account Number may contain only digits and -.",
"틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.": "Tiktok Handle may contain only letters, digits, underscores and dots.",
"판매금액은 숫자로 입력하세요.": "Sales must be a number.", "판매금액은 0 이상 숫자로 입력하세요.": "Sales must be a number of 0 or more.", "판매금액이 너무 큽니다.": "Sales is too large.",
"{label}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.",
"호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.", "방송 장소가 너무 깁니다(200자까지).": "Venue is too long (up to 200 characters).",
"끝 시간이 시작 시간과 같습니다.": "End time is the same as start time.", "날짜가 올바르지 않습니다.": "The date is invalid.",
"호스트를 찾을 수 없습니다.": "Host not found.", "방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.": "A host with broadcasts can't be deleted — set the host to Inactive instead.",
"방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).": "Broadcast not found (someone may have deleted it).", "방송을 찾을 수 없습니다.": "Broadcast not found.",
"사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.": "This host is Inactive — select another host.",
"방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).": "Up to {max} images per broadcast (currently {have}).", "방송 한 건에 이미지는 {max}장까지입니다.": "Up to {max} images per broadcast.",
"DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.": "DB migration live_db 002 (ad spend) has not been applied yet.", "이미지를 찾을 수 없습니다.": "Image not found.",
"{name}: {detail}": "{name}: {detail}",
# 권한·설정
"로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.",
"호스트 정보는 ERP 관리자만 볼 수 있습니다.": "Only ERP admins can view host information.", "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.": "The Live Commerce DB (LIVE_DB_URL) is not configured.",
"라이브 커머스 모듈 접근 권한이 없습니다.": "You don't have access to the Live Commerce module.",
"라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 .env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.":
"The Live Commerce module is not set up yet. Create live_db with scripts/sql/live_db_init.sql, add LIVE_DB_URL to .env and restart the container.",
# 자산 모듈 prepare_photo 오류(이미지 검사를 함께 쓴다)
"사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.": "The image must be a non-empty file of 8 MB or less.", "JPG, PNG, WebP 사진만 등록할 수 있습니다.": "Only JPG, PNG and WebP images are allowed.",
"사진은 2천만 화소 이하로 등록하세요.": "The image must be 20 megapixels or less.", "사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.": "Please compress the image and try again (5 MB or less once stored).",
"사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.": "The image can't be read. Please choose a valid JPG, PNG or WebP file.",
}
# 화면 스크립트에 넘기는 문구(window.LV_T)
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
"{day} 광고비 (RM) — 비우면 지웁니다")
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
def norm_lang(raw: Any) -> str:
return "en" if raw == "en" else "ko"
def t(text: str, lang: str = "ko") -> str:
return EN.get(text, text) if lang == "en" else text
def js_text(lang: str) -> dict[str, str]:
return {k: t(k, lang) for k in JS_KEYS}
def month_label(year: int, month: int, lang: str = "ko") -> str:
return f"{_MONTH_NAMES[month - 1]} {year}" if lang == "en" else f"{year}년 {month}월"
class LiveError(ValueError):
"""입력·저장 오류 — 언어에 맞게 다시 쓸 수 있게 문구 틀과 값을 따로 둔다. str() = 한글."""
def __init__(self, template: str, **params: Any):
self.template, self.params = template, params
super().__init__(template.format(**params))
def text(self, lang: str) -> str:
return t(self.template, lang).format(**{k: t(v, lang) if isinstance(v, str) else v for k, v in self.params.items()})
def error_text(exc: Exception, lang: str) -> str:
return exc.text(lang) if isinstance(exc, LiveError) else t(str(exc), lang)
+284
View File
@@ -0,0 +1,284 @@
"""라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04).
GET /live/ 스케줄표(?month=YYYY-MM) · GET /live/calendar 달력 보기(같은 달 값)
POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기
POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께)
POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with)
POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기)
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보)
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자. DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
"""
from __future__ import annotations
from pathlib import PurePath
from typing import Any
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, Response
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
from app.timezone import today_kst
from . import i18n, store
router = APIRouter(prefix="/live", tags=["live"])
def _store(request: Request) -> Any:
return getattr(request.app.state, "live_store", None)
def _lang(request: Request) -> str:
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE))
def _t(request: Request, text: str) -> str:
return i18n.t(text, _lang(request))
def _user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail=_t(request, "로그인이 필요합니다."))
if not has_module(user, "live"):
raise HTTPException(status_code=403, detail=_t(request, "라이브 커머스 모듈 권한이 없습니다."))
return user
def _admin(request: Request) -> dict[str, Any]:
from app.store import is_admin # noqa: WPS433
user = _user(request)
if not is_admin(user):
raise HTTPException(status_code=403, detail=_t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."))
return user
def _db(request: Request) -> Any:
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail=_t(request, "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다."))
return st
def _page(request: Request) -> Any:
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return login_redirect(request)
if not has_module(user, "live"):
return render_template(request, "denied.html", {"reason": _t(request, "라이브 커머스 모듈 접근 권한이 없습니다."),
"is_admin": is_admin(user)}, status_code=403)
st = _store(request)
if st is None:
return render_template(request, "denied.html", {
"reason": _t(request, "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 "
".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요."),
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503)
return st, user
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
lang = _lang(request)
return render_template(request, name, {"user": user, "is_admin": is_admin(user), "lang": lang,
"t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang),
"nav_items": build_erp_nav(user, active="live"), **ctx})
def _ok(request: Request, message: str) -> JSONResponse:
return JSONResponse({"ok": True, "message": _t(request, message)})
def _fail(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse({"ok": False, "message": i18n.error_text(exc, _lang(request))}, status_code=400)
def _opt_id(raw: str) -> int | None:
s = (raw or "").strip()
if not s:
return None
if not s.isdigit():
raise ValueError("잘못된 요청입니다.")
return int(s)
@router.get("/health")
def health(request: Request) -> JSONResponse:
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
# ────────────────────────────────────────────────────────────
# 스케줄표
# ────────────────────────────────────────────────────────────
@router.get("/", response_class=HTMLResponse)
def index(request: Request, month: str = "") -> Any:
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
lang = _lang(request)
span = store.month_range(month, today_kst(), lang)
rows = [store.broadcast_view(b, lang) for b in st.list_broadcasts(span["start"], span["end"])]
return _render(request, "live/index.html", user, {"view": "table", "span": span, "rows": rows, "hosts": st.host_choices(),
"max_images": store.MAX_IMAGES})
@router.get("/calendar", response_class=HTMLResponse)
def calendar(request: Request, month: str = "") -> Any:
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
today, lang = today_kst(), _lang(request)
span = store.month_range(month, today, lang)
cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), st.ad_spends(span["start"], span["end"]), today, lang)
return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(),
"max_images": store.MAX_IMAGES})
@router.post("/broadcasts/{broadcast_id}/move")
def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Form(""), start_time: str = Form(""),
swap_with: str = Form("")) -> JSONResponse:
user = _user(request)
st = _db(request)
try:
other = _opt_id(swap_with)
if other is not None:
st.swap_broadcasts(broadcast_id, other, by=user.get("email", ""))
else:
day, start = store.parse_move(broadcast_date, start_time)
st.move_broadcast(broadcast_id, day, start, by=user.get("email", ""))
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "옮겼습니다.")
@router.post("/ad-spend")
def ad_spend_save(request: Request, day: str = Form(""), amount: str = Form("")) -> JSONResponse:
user = _user(request)
st = _db(request)
try:
when, _ = store.parse_move(day, "00:00")
st.save_ad_spend(when, store.parse_money(amount), by=user.get("email", ""))
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "광고비를 저장했습니다.")
def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
"""고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에."""
picked = [f for f in files if f.filename]
if len(picked) > store.MAX_IMAGES:
raise i18n.LiveError("방송 한 건에 이미지는 {max}장까지입니다.", max=store.MAX_IMAGES)
out = []
for f in picked:
name = PurePath(f.filename.replace("\\", "/")).name[:200]
try:
data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1))
except ValueError as exc:
raise i18n.LiveError("{name}: {detail}", name=name, detail=str(exc)) from None
out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height})
return out
@router.post("/broadcasts")
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), sales_amount: str = Form(""),
images: list[UploadFile] = File(default=[])) -> JSONResponse:
user = _user(request)
st = _db(request)
try:
broadcast_id = _opt_id(id)
values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time,
"end_time": end_time, "venue": venue, "sales_amount": sales_amount})
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "저장했습니다.")
@router.post("/broadcasts/{broadcast_id}/delete")
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
_user(request)
try:
_db(request).delete_broadcast(broadcast_id)
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "방송을 지웠습니다.")
@router.get("/images/{image_id}")
def image(request: Request, image_id: int, thumb: int = 0) -> Response:
_user(request)
row = _db(request).get_image(image_id)
if not row:
raise HTTPException(status_code=404, detail=_t(request, "이미지를 찾을 수 없습니다."))
data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"])
# 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private.
return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"})
@router.post("/images/{image_id}/delete")
def image_delete(request: Request, image_id: int) -> JSONResponse:
_user(request)
try:
_db(request).delete_image(image_id)
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "이미지를 지웠습니다.")
# ────────────────────────────────────────────────────────────
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보)
# ────────────────────────────────────────────────────────────
@router.get("/settings", response_class=HTMLResponse)
def settings(request: Request) -> Any:
from app.main import render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
if not is_admin(user):
return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False},
status_code=403)
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()})
@router.post("/settings/hosts")
def host_save(request: Request, id: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), tiktok_handle: str = Form(""),
is_active: str = Form("")) -> JSONResponse:
user = _admin(request)
st = _db(request)
try:
values = store.clean_host({"full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
"bank_account": bank_account, "tiktok_handle": tiktok_handle})
st.save_host(_opt_id(id), values, is_active=bool(is_active), by=user.get("email", ""))
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "호스트를 저장했습니다.")
@router.post("/settings/hosts/{host_id}/delete")
def host_delete(request: Request, host_id: int) -> JSONResponse:
_admin(request)
try:
_db(request).delete_host(host_id)
except ValueError as exc:
return _fail(request, exc)
return _ok(request, "호스트를 지웠습니다.")
+231
View File
@@ -0,0 +1,231 @@
"""라이브 커머스 순수 함수 — 입력 검사·표시 형식(DB 없이 시험 가능)."""
from __future__ import annotations
import io
import re
from datetime import date, datetime, time, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any
from PIL import Image
from .i18n import LiveError, month_label
MAX_IMAGES = 10 # 방송 한 건에
MAX_SALES = Decimal("999999999999.99")
THUMB_SIZE = 160
# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것
HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM)
COMMISSION_PERCENT = Decimal("10") # 판매금액의 %
SLOT_HOURS = 2 # 달력 한 칸
FIRST_SLOT_HOUR = 6 # 달력에 늘 보이는 첫 칸(이보다 이른 칸은 방송이 있을 때만)
HOST_COLORS = ("#66d4e6", "#6ee05a", "#d4f06a", "#e9cf7a", "#ec9d88", "#cdb9ea", "#f4a9c8", "#a9c4f5")
_CENT = Decimal("0.01")
_WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")
_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64}
_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
"bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"}
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
_PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$")
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
_HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$")
_HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I)
WEEKDAYS_KO = "월화수목금토일"
_WEEKDAYS_EN_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
def clean_handle(raw: Any) -> str:
"""'@name'·'https://www.tiktok.com/@name?lang=en' → 'name'."""
s = _HANDLE_URL_RE.sub("", str(raw or "").strip())
return re.split(r"[/?#]", s, maxsplit=1)[0].lstrip("@")
def clean_host(values: dict[str, Any]) -> dict[str, str]:
"""호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
out["tiktok_handle"] = clean_handle(values.get("tiktok_handle"))
if not out["full_name"]:
raise LiveError("이름 (IC 기준)을 입력하세요.")
for key, limit in HOST_LIMITS.items():
if len(out[key]) > limit:
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label=_LABELS[key], limit=limit)
if out["email"] and not _EMAIL_RE.match(out["email"]):
raise LiveError("이메일 형식이 올바르지 않습니다.")
if out["phone"] and not _PHONE_RE.match(out["phone"]):
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]):
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
return out
def parse_money(raw: Any) -> Decimal | None:
"""판매금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용."""
s = re.sub(r"(?i)^rm|[,\s]", "", str(raw if raw is not None else "").strip())
if not s:
return None
try:
n = Decimal(s)
except InvalidOperation:
raise LiveError("판매금액은 숫자로 입력하세요.") from None
if not n.is_finite() or n < 0:
raise LiveError("판매금액은 0 이상 숫자로 입력하세요.")
if n > MAX_SALES:
raise LiveError("판매금액이 너무 큽니다.")
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
def _parse_time(raw: Any, *, label: str, required: bool) -> time | None:
s = str(raw or "").strip()
if not s:
if required:
raise LiveError("{label}을 입력하세요.", label=label)
return None
try:
return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None)
except ValueError:
raise LiveError("{label}이 올바르지 않습니다.", label=label) from None
def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
"""방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError."""
host = str(values.get("host_id") or "").strip()
if not host.isdigit():
raise LiveError("호스트를 고르세요.")
try:
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
except ValueError:
raise LiveError("방송 날짜를 입력하세요.") from None
venue = str(values.get("venue") or "").strip()
if len(venue) > 200:
raise LiveError("방송 장소가 너무 깁니다(200자까지).")
start = _parse_time(values.get("start_time"), label="시작 시간", required=True)
end = _parse_time(values.get("end_time"), label="끝 시간", required=True)
if start == end:
raise LiveError("끝 시간이 시작 시간과 같습니다.")
return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end,
"venue": venue, "sales_amount": parse_money(values.get("sales_amount"))}
def parse_move(day: Any, start: Any) -> tuple[date, time]:
"""달력 칸 — 날짜·시작 시간. 틀리면 ValueError."""
try:
when = date.fromisoformat(str(day or "").strip())
except ValueError:
raise LiveError("날짜가 올바르지 않습니다.") from None
return when, _parse_time(start, label="시간", required=True)
def moved_end(old_start: time, old_end: time | None, new_start: time) -> time | None:
"""칸을 옮겨도 방송 길이는 그대로."""
if old_end is None:
return None
return (datetime.combine(date.min, new_start) + _duration(old_start, old_end)).time()
def _duration(start: time, end: time) -> timedelta:
minutes = (end.hour * 60 + end.minute - start.hour * 60 - start.minute) % 1440 # 끝이 더 이르면 자정을 넘긴 방송
return timedelta(minutes=minutes)
def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]:
"""호스트 비용 — 기본 요금(시간 × 시간당 요금) + 커미션(판매금액 × %)."""
hours = Decimal(_duration(start, end).seconds) / 3600 if end else Decimal(0)
base = (hours * HOURLY_RATE).quantize(_CENT, rounding=ROUND_HALF_UP)
commission = ((sales or Decimal(0)) * COMMISSION_PERCENT / 100).quantize(_CENT, rounding=ROUND_HALF_UP)
return {"hours": hours, "base": base, "commission": commission, "fee": base + commission}
def fmt_short(n: Decimal) -> str:
"""카드·합계용 — 소수점 아래가 0 이면 뺀다(48, 4.80, 1,234.50)."""
return f"{n:,.2f}".removesuffix(".00")
def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]:
"""방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄."""
pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"])
return {
"date": fmt_date(b["broadcast_date"], lang), "times": fmt_times(b["start_time"], b["end_time"]),
"host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"],
"sales": fmt_money(b["sales_amount"]), "commission": fmt_money(pay["commission"]), "fee": fmt_money(pay["fee"]),
"images": b["images"], "pay": pay, "id": b["id"],
"label": b["tiktok_handle"] or b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)],
"card_sales": fmt_short(b["sales_amount"] or Decimal(0)), "card_commission": fmt_short(pay["commission"]),
"card_fee": fmt_short(pay["fee"]),
"edit": {"id": b["id"], "host_id": b["host_id"], "broadcast_date": b["broadcast_date"].isoformat(),
"start_time": f"{b['start_time']:%H:%M}", "end_time": f"{b['end_time']:%H:%M}" if b["end_time"] else "",
"venue": b["venue"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None else "",
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
}
def _roas(sales: Decimal, ad_spend: Decimal) -> str:
return f"{sales / ad_spend:.2f}" if ad_spend else "-"
def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date, lang: str = "ko") -> dict[str, Any]:
"""달력 보기 값 — 날짜(열)·2시간 칸(줄)·날짜별 합계·달 합계. 칸은 시작 시간으로 정한다."""
views = [(b, broadcast_view(b, lang)) for b in broadcasts]
used = {b["start_time"].hour // SLOT_HOURS * SLOT_HOURS for b, _ in views}
days = []
day = span["start"]
while day < span["end"]:
mine = [(b, v) for b, v in views if b["broadcast_date"] == day]
sales = sum((b["sales_amount"] or Decimal(0) for b, _ in mine), Decimal(0))
fee = sum((v["pay"]["fee"] for _, v in mine), Decimal(0))
spend = ad_spend.get(day, Decimal(0))
days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()] if lang == "en" else WEEKDAYS_KO[day.weekday()] + "요일",
"label": f"{day.day} {_MONTHS[day.month - 1]}" if lang == "en" else f"{day.month}월 {day.day}일", "is_weekend": day.weekday() >= 5, "is_today": day == today,
"count": len(mine), "sales": sales, "fee": fee, "spend": spend,
"sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)})
day += timedelta(days=1)
slots = []
for hour in sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used):
end_hour = (hour + SLOT_HOURS) % 24
cells = [{"iso": d["iso"], "is_weekend": d["is_weekend"],
"cards": [v for b, v in views if b["broadcast_date"] == d["date"] and b["start_time"].hour // SLOT_HOURS * SLOT_HOURS == hour]}
for d in days]
slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00", "cells": cells})
sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend"))
return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})",
"commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0],
"totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}}
def month_range(raw: Any, today: date, lang: str = "ko") -> dict[str, Any]:
"""'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목."""
m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip())
year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month)
start = date(year, month, 1)
end = date(year + (month == 12), month % 12 + 1, 1)
prev = date(year - (month == 1), (month - 2) % 12 + 1, 1)
return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"),
"label": month_label(year, month, lang)}
def fmt_date(d: date, lang: str = "ko") -> str:
return f"{d:%Y.%m.%d} ({_WEEKDAYS_EN_SHORT[d.weekday()]})" if lang == "en" else f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
def fmt_times(start: time, end: time | None) -> str:
return f"{start:%H:%M}" + (f" ~ {end:%H:%M}" if end else "")
def fmt_money(n: Decimal | None) -> str:
return f"{n:,.2f}" if n is not None else ""
def thumbnail(data: bytes) -> bytes:
"""목록 작은 그림 — JPEG(투명은 흰 바탕). 저장할 때 이미 확인한 이미지만 들어온다."""
with Image.open(io.BytesIO(data)) as source:
source.thumbnail((THUMB_SIZE, THUMB_SIZE))
rgba = source.convert("RGBA")
canvas = Image.new("RGB", rgba.size, "white")
canvas.paste(rgba, mask=rgba.getchannel("A"))
out = io.BytesIO()
canvas.save(out, format="JPEG", quality=80)
return out.getvalue()
+19
View File
@@ -0,0 +1,19 @@
{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 언어, 호스트 설정, 방송 추가. view = table | calendar -#}
{% set here = '/live/calendar' if view == 'calendar' else '/live/' %}
{% set can_add = hosts | selectattr('is_active') | list %}
<div class="lv-bar">
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.prev }}" aria-label="{{ t('이전 달') }}">◀</a>
<h2 class="lv-month">{{ span.label }}</h2>
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.next }}" aria-label="{{ t('다음 달') }}">▶</a>
<nav class="lv-views" aria-label="{{ t('보기 방식') }}">
<a class="erp-btn {{ 'erp-btn-primary' if view == 'table' else 'erp-btn-outline' }}" href="/live/?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'table' %} aria-current="page"{% endif %}>{{ t('표') }}</a>
<a class="erp-btn {{ 'erp-btn-primary' if view == 'calendar' else 'erp-btn-outline' }}" href="/live/calendar?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'calendar' %} aria-current="page"{% endif %}>{{ t('달력') }}</a>
</nav>
<span class="lv-gap"></span>
{% include "live/_lang.html" %}
{% if is_admin %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not can_add %} disabled{% endif %}>{{ t('+ 방송 추가') }}</button>
</div>
{% if not can_add %}
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if is_admin %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
{% endif %}
@@ -0,0 +1,30 @@
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#}
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
<form id="lv-form" action="/live/broadcasts">
<h3 id="lv-dlg-title" data-add="{{ t('방송 추가') }}" data-edit="{{ t('방송 고치기') }}"></h3>
<input type="hidden" name="id" />
<label class="lv-field">{{ t('호스트') }}
<select class="erp-select" name="host_id" required>
<option value="">{{ t('호스트를 고르세요') }}</option>
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.full_name }}{% if h.tiktok_handle %} (@{{ h.tiktok_handle }}){% endif %}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
</select>
</label>
<div class="lv-row">
<label class="lv-field">{{ t('방송 날짜') }} <input class="erp-input" type="date" name="broadcast_date" required /></label>
<label class="lv-field">{{ t('시작 시간') }} <input class="erp-input" type="time" name="start_time" required /></label>
<label class="lv-field">{{ t('끝 시간') }} <input class="erp-input" type="time" name="end_time" required /></label>
</div>
<p class="lv-sub">{{ t('시간은 말레이시아 시간으로 입력합니다.') }}</p>
<label class="lv-field">{{ t('방송 장소') }} <input class="erp-input" type="text" name="venue" maxlength="200" /></label>
<label class="lv-field">{{ t('판매금액 (RM)') }} <input class="erp-input lv-num" type="text" name="sales_amount" inputmode="decimal" placeholder="{{ t('방송 후 입력') }}" /></label>
<label class="lv-field">{{ t('방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)').format(n=max_images) }}
<input type="file" name="images" accept="image/jpeg,image/png,image/webp" multiple />
</label>
<ul class="lv-saved" data-saved hidden></ul>
<p class="lv-msg" data-msg role="alert" hidden></p>
<div class="lv-foot">
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
</div>
</form>
</dialog>
@@ -0,0 +1,5 @@
{#- 한글·영문 전환 — 누르면 쿠키에 저장하고 다시 그린다(live.js). 언어 이름은 언어와 상관없이 그대로 보인다. -#}
<div class="lv-lang" role="group" aria-label="{{ t('언어') }}">
<button type="button" data-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
<button type="button" data-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
</div>
@@ -0,0 +1,2 @@
<script>window.LV_T = {{ js_text | tojson }};</script>
<script src="/static/live.js?v=20261104c" defer></script>
@@ -0,0 +1,86 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름).
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
{% include "live/_bar.html" %}
<div class="lv-kpis">
<div class="lv-kpi"><span>{{ t('총 판매금액') }}</span><b>RM {{ cal.totals.sales }}</b></div>
<div class="lv-kpi"><span>{{ t('광고비') }}</span><b>RM {{ cal.totals.spend }}</b></div>
<div class="lv-kpi"><span>{{ t('호스트 비용') }}</span><b>RM {{ cal.totals.fee }}</b></div>
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
</div>
<nav class="lv-jump" aria-label="{{ t('날짜로 이동') }}">
<span class="lv-jump-label">{{ t('날짜로 이동') }}:</span>
{% for d in cal.days %}<button type="button" class="lv-jump-day{% if d.is_weekend %} is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}" data-jump="{{ d.iso }}">{{ d.day }}</button>{% endfor %}
</nav>
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
<div class="lv-cal-wrap" id="lv-cal-wrap">
<table class="lv-cal">
<thead>
<tr>
<th class="lv-cal-time" scope="col">{{ t('시간') }}</th>
{% for d in cal.days %}
<th scope="col" data-day="{{ d.iso }}"{% if d.is_today %} data-today="1"{% endif %} class="{% if d.is_weekend %}is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}">
<div class="lv-cal-weekday">{{ d.weekday }} <span class="lv-cal-count">{{ d.count }}</span></div>
<div class="lv-cal-date">{{ d.label }}</div>
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for slot in cal.slots %}
<tr>
<th class="lv-cal-time" scope="row">{{ slot.label }}<small>{{ cal.slot_note }}</small></th>
{% for cell in slot.cells %}
<td class="lv-cell{% if cell.is_weekend %} is-weekend{% endif %}" data-drop data-day="{{ cell.iso }}" data-start="{{ slot.start }}">
{% for c in cell.cards %}
<article class="lv-card" data-card="{{ c.id }}">
<header class="lv-card-head" draggable="true" style="background:{{ c.color }}" title="{{ c.host_name }} · {{ c.times }}{% if c.venue %} · {{ c.venue }}{% endif %}">
<span class="lv-card-grip" aria-hidden="true">✥</span>
<span class="lv-card-name">{{ c.label }}</span>
<button type="button" class="lv-card-edit" data-edit='{{ c.edit | tojson }}' aria-label="{{ t('{name} {date} {times} 고치기').format(name=c.label, date=c.date, times=c.times) }}">✎</button>
</header>
<div class="lv-card-nums">
<div><span>{{ t('판매금액') }}</span><b>{{ c.card_sales }}</b></div>
<div><span>{{ t('커미션') }} ({{ cal.commission_percent }}%)</span><b>{{ c.card_commission }}</b></div>
</div>
<footer class="lv-card-foot"><span>{{ t('비용') }}: <b>RM{{ c.card_fee }}</b></span>{% if c.images %}<a href="/live/images/{{ c.images[0].id }}" target="_blank" rel="noopener" title="{{ t('방송 결과 이미지') }}">{{ t('이미지 {n}').format(n=c.images | length) }}</a>{% endif %}</footer>
</article>
{% endfor %}
{% if not cell.cards and hosts | selectattr('is_active') | list %}
<button type="button" class="lv-cell-add" data-new='{{ {"broadcast_date": cell.iso, "start_time": slot.start, "end_time": slot.end} | tojson }}' aria-label="{{ t('{date} {slot} 방송 추가').format(date=cell.iso, slot=slot.label) }}">+</button>
{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th class="lv-cal-time" scope="row">{{ t('합계 & ROAS') }}</th>
{% for d in cal.days %}
<td>
<dl class="lv-total">
<div><dt>{{ t('총 판매금액') }}:</dt><dd class="is-sales">RM {{ d.sales_text }}</dd></div>
<div><dt>{{ t('광고비') }}:</dt><dd>RM {{ d.spend_text }} <button type="button" class="lv-total-edit" data-spend="{{ d.iso }}" data-value="{{ d.spend if d.spend else '' }}" aria-label="{{ t('{date} 광고비 고치기').format(date=d.iso) }}">✎</button></dd></div>
<div><dt>{{ t('호스트 비용') }}:</dt><dd>RM {{ d.fee_text }}</dd></div>
<div><dt>ROAS:</dt><dd>{{ d.roas }}</dd></div>
</dl>
</td>
{% endfor %}
</tr>
</tfoot>
</table>
</div>
</section>
{% include "live/_dialog.html" %}
{% endblock %}
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
@@ -0,0 +1,41 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
{% include "live/_bar.html" %}
<div class="erp-card-block">
<div class="erp-table-wrap">
<table class="erp-table lv-table">
<thead><tr><th>{{ t('날짜') }}</th><th>{{ t('시간') }}</th><th>{{ t('호스트') }}</th><th>{{ t('방송 장소') }}</th><th class="lv-r">{{ t('판매금액(RM)') }}</th><th class="lv-r">{{ t('커미션 10%(RM)') }}</th><th class="lv-r">{{ t('호스트 비용(RM)') }}</th><th>{{ t('방송 결과') }}</th><th></th></tr></thead>
<tbody>
{% for r in rows %}
<tr>
<td class="lv-nowrap" data-label="{{ t('날짜') }}">{{ r.date }}</td>
<td class="lv-nowrap" data-label="{{ t('시간') }}">{{ r.times }}</td>
<td data-label="{{ t('호스트') }}">{{ r.host_name }}{% if r.tiktok_handle %}<div class="lv-sub">@{{ r.tiktok_handle }}</div>{% endif %}</td>
<td data-label="{{ t('방송 장소') }}">{{ r.venue }}</td>
<td class="lv-r lv-num" data-label="{{ t('판매금액(RM)') }}">{{ r.sales }}</td>
<td class="lv-r lv-num" data-label="{{ t('커미션 10%(RM)') }}">{{ r.commission }}</td>
<td class="lv-r lv-num" data-label="{{ t('호스트 비용(RM)') }}" title="{{ t('기본 요금 RM {base} + 커미션 RM {commission}').format(base=r.pay.base, commission=r.pay.commission) }}">{{ r.fee }}</td>
<td data-label="{{ t('방송 결과') }}"><div class="lv-thumbs">{% for im in r.images %}<a href="/live/images/{{ im.id }}" target="_blank" rel="noopener" title="{{ im.filename }}"><img src="/live/images/{{ im.id }}?thumb=1" alt="{{ im.filename }}" loading="lazy" /></a>{% endfor %}</div></td>
<td class="lv-actions">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ r.edit | tojson }}'>{{ t('고치기') }}</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/broadcasts/{{ r.id }}/delete" data-confirm="{{ t('{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.').format(date=r.date, host=r.host_name) }}">{{ t('지우기') }}</button>
</td>
</tr>
{% else %}
<tr><td colspan="9" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</section>
{% include "live/_dialog.html" %}
{% endblock %}
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
@@ -0,0 +1,67 @@
{% extends "erp_base.html" %}
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
{% block content %}
<section class="lv" lang="{{ lang }}">
<div class="lv-bar">
<a class="erp-btn erp-btn-outline" href="/live/">{{ t('◀ 스케줄표') }}</a>
<h2 class="lv-month">{{ t('호스트 설정') }}</h2>
<span class="lv-gap"></span>
{% include "live/_lang.html" %}
<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>
</div>
<div class="erp-card-block">
<div class="erp-table-wrap">
<table class="erp-table lv-table">
<thead><tr><th>{{ t('이름 (IC 기준)') }}</th><th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th><th>{{ t('틱톡 핸들') }}</th><th>{{ t('상태') }}</th><th></th></tr></thead>
<tbody>
{% for h in hosts %}
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
<td class="lv-nowrap" data-label="{{ t('전화번호') }}">{{ h.phone }}</td>
<td data-label="{{ t('이메일') }}">{{ h.email }}</td>
<td data-label="{{ t('주소') }}">{{ h.address }}</td>
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
<td data-label="{{ t('틱톡 핸들') }}">{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %}</td>
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
<td class="lv-actions">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "tiktok_handle": h.tiktok_handle, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ t('{name} 호스트를 지울까요?').format(name=h.full_name) }}">{{ t('지우기') }}</button>
</td>
</tr>
{% else %}
<tr><td colspan="9" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</section>
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
<form id="lv-form" action="/live/settings/hosts">
<h3 id="lv-dlg-title" data-add="{{ t('호스트 등록') }}" data-edit="{{ t('호스트 고치기') }}"></h3>
<input type="hidden" name="id" />
<label class="lv-field">{{ t('이름 (IC 기준)') }} <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
<label class="lv-field">{{ t('전화번호') }} <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
<label class="lv-field">{{ t('이메일') }} <input class="erp-input" type="email" name="email" maxlength="254" /></label>
<label class="lv-field">{{ t('주소') }} <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
<div class="lv-row">
<label class="lv-field">{{ t('은행명') }} <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
<label class="lv-field">{{ t('계좌번호') }} <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
</div>
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" /></label>
<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>
<p class="lv-msg" data-msg role="alert" hidden></p>
<div class="lv-foot">
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
</div>
</form>
</dialog>
{% endblock %}
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
+2 -2
View File
@@ -90,11 +90,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, "malaysia"):
return render_template(
request,
@@ -2,7 +2,7 @@
{% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261019c" />
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<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 %}
@@ -64,7 +64,7 @@
</section>
</div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261019c" defer></script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %}
{% endblock %}
+40
View File
@@ -0,0 +1,40 @@
# [안내문 발송] 안내문 발송 모듈 — `app/modules/outreach/`, `outreach_db`
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
> 정적 파일: `app/static/outreach.js`, `app/static/outreach.css`. 템플릿: `templates/outreach/`. 테스트: `tests/test_outreach.py`,
> `tests/js/outreach.browser.test.js`·`outreach_settings.browser.test.js`(`render_outreach.py`). 편집기 = `app/static/vendor/quill/`(Quill 2.0.3, BSD).
> 다른 모듈과 연결: 메일 = 입출고 Gmail 연결(`inout_store.inout_gmail_tokens`, `app/modules/inout/gmail.py`, 콜백 `/inout/gmail/callback` 이
> 세션 `_gmail_origin=outreach` 를 보고 `_GMAIL_ORIGINS` 로 처리) — 입출고·휴가와 같은 연결.
- 리스트(주소 + 이름)에 안내문을 보낸다(2026-10-27). 권한키 `outreach`(보기·리스트·보내기·설정 모두), DB `OUTREACH_DB_URL`(없으면 "설정 필요" 안내).
- **주소를 보고 메일/DM 판별**(`store.detect`): `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
게시물 주소(`/p/`·`/reel/`)·한글만은 오류. 같은 주소는 한 번(`UNIQUE(kind, handle)`, 이메일·계정명 소문자).
- 리스트 추가 = 붙여넣기(한 줄에 한 사람 `주소, 이름` — 쉼표·탭·띄어쓰기, 순서는 어느 쪽이든, `store.parse_line`) → [미리보기](메일/DM/오류·중복·이미 있음) → [리스트에 추가].
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시.
- **메일 본문 = HTML**(설정 편집기, `fmt: "html"`) — 저장·읽을 때마다 `store.sanitize_html`(허용 태그 p·br·strong·em·u·s·span·a·ul·ol·li 등,
style 은 color·background-color·font-size·font-weight·font-style·text-decoration·text-align 만, 링크는 http(s)/mailto, `&nbsp;` → 띄어쓰기, 빈 문단 = `<br>`).
예전 글·기본 문구(`fmt` 없음) = `text_to_html`(줄마다 문단, `**굵게**`, 주소 링크). 메일 글 버전·DM 대체 글·{이름} 찾기 = `html_to_text`.
`{이름}` 은 글자마다 서식이 달라도 `fill_html` 이 바꾼다. 메일 HTML 은 `<p>` 에 margin:0(메일 프로그램 문단 여백 없앰).
- **메일** = [고른 메일 보내기] → `db.claim_for_send`(고른 줄 중 메일·대기/실패만 '발송중'으로 한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번) →
`send.send_batch`(백그라운드, **보내는 사람 본인 Gmail**, 한 사람에 한 통·1초 간격, 설정 사진 = 본문 아래 cid) → 보냄/실패 + `outreach_logs`.
Gmail 연결 없으면 409(화면이 [Gmail 연결] 안내), 끊기면 남은 줄 실패. 서버 재시작 때 남은 '발송중' = 실패(`release_stuck`).
- **인스타 DM = 반자동** — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다(상대가 먼저 보낸 24시간 안만, 자동 DM 은 약관 위반·계정 정지 위험).
[DM 보내기] = 그 사람 이름이 든 문구 복사 + `https://ig.me/m/계정` 새 탭(누르는 순간 — 문구는 리스트 데이터에 미리 담음) → 붙여 넣어 보낸 뒤 [보냄](`dm-sent`, 기록).
**DM 문구** = 설정 `dm_body`(글, `store.dm_text`, 최대 1000자 `DM_MAX`, `{이름}`, 별표만 뺌) — 비어 있으면 메일 본문 글 + 끝 문구. "이름 필요"도 구분별(`needs_name(t, kind)`).
- **탭**(2026-10-30, `templates/outreach/_tabs.html`) — [발송 리스트](`/outreach/`) [DM 수동 보내기](`/outreach/dm`) + 맨 오른쪽 설정 톱니.
- **DM 수동 보내기 탭** `/outreach/dm`(`dm.html`, JS `outreach.js initDm`) — 3단:
왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸, 머리글 "이름"·빈 줄·이미 있는 이름 뺌, 넣을 때마다 목록에 더함) + 이름 목록(× 한 명씩·[전체 삭제], 브라우저만 — 저장 안 함),
가운데 = 본문(`contenteditable="plaintext-only"`, 바로 고침, `{이름}` 자리 = 분홍 칩 — 직접 `{이름}` 이라 써도 됨), 오른쪽 = 저장한 본문 목록
(맨 위 "설정 DM 문구(기본)" = `dm_template` = `store.dm_text(template, NAME_TAG)`, 그 아래 저장한 것 — 누르면 불러옴(고친 글 있으면 확인)·× 하나씩 지우기).
이름을 누르면 칩이 그 이름으로 바뀌고 고친 글 + 이름을 바로 클립보드 복사 + 짧은 안내(1.6초). 글자 수 = 이름 넣은 글 기준, 1000자(`DM_MAX`) 넘으면 빨강.
**저장한 본문** = outreach_db 마이그레이션 002 `outreach_dm_bodies`(모듈 권한자 모두 같은 목록, 제목 = 첫 글 줄 40자 `store.dm_saved_body`, 1000자까지):
`POST /outreach/api/dm-bodies`(새 본문으로 저장)·`PUT …/{id}`(고른 본문 [저장])·`DELETE …/{id}` — 모두 `{items}` 돌려줌. 002 미적용이면 목록 안내만, API 503.
- 설정 = 탭 줄 맨 오른쪽 톱니(`.otr-gear`, 공용 `vendor/material-symbols`). `.otr .erp-card[hidden]` — 공용 `.erp-card` display:flex 가 hidden 을 덮어
[리스트 추가] 창이 늘 열려 있던 것 고침(2026-10-30).
- **설정** `/outreach/settings`(모듈 권한자 누구나) — **세로 2단**: 왼쪽 메일(제목·"(광고)"·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
오른쪽 인스타 DM(서식 없는 편집기·글자 수·[메일 본문 글 가져오기]), 위 막대 [저장]·[기본 문구로 되돌리기](칸만, 저장해야 적용) — 1100px 아래는 위아래.
입력 칸은 `form="otr-set-form"` 으로 위 막대 폼에 묶음(사진 폼과 겹치지 않게). 편집기 = Quill snow(글자 크기 px·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
저장 = `getSemanticHTML()` → `body`(fmt=html), DM `getText()` → `dm_body`. **`{이름}` 빨강 굵게 = 화면에서만**(class `otr-nametag-on`, 서버 정리 때 class 가 빠져 메일에는 안 남음).
기본 본문 = 미라네주방 공동구매 제안 문구(`store.DEFAULT_TEMPLATE`, 글). "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조 대상일 수 있어 칸을 둠(법무 확인 권장).
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶).
- 리스트 줄: 이름 바로 고치기(칸 떠나면 저장), [미리보기](메일 = 제목·HTML, DM = 글), 고른 줄 다시 대기·지우기(발송중은 못 지움), 걸러 보기(전체·메일·DM·대기·보냄·실패).
+28
View File
@@ -0,0 +1,28 @@
"""안내문 발송(outreach) 모듈 — 리스트(이메일·인스타그램 주소 + 이름)에 안내문을 보낸다(2026-10-27).
- 라우터: `router.py` (prefix=/outreach) · 저장소: `db.py` (outreach_db) · 순수 함수: `store.py`(주소 판별·{이름}·본문)
- 메일 일괄 발송: `send.py` — 보내는 사람 본인 Gmail(입출고·휴가와 같은 Gmail 연결)
- 인스타 DM: 반자동(문구 복사 + DM 창 열기 + [보냄] 기록) — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다.
- 템플릿: `templates/outreach/`, 화면 스크립트·스타일 `static/outreach.{js,css}`
OUTREACH_DB_URL 미설정이면 build_outreach_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `outreach`.
"""
from typing import Any
from .router import router
__all__ = ["router", "build_outreach_store"]
def build_outreach_store(*, dsn: str | None) -> Any:
if not dsn:
return None
from .db import OutreachDBStore # 지연 import
st = OutreachDBStore(dsn)
try:
st.release_stuck() # 서버가 보내던 중 다시 시작됨 → 발송중 줄을 실패로(다시 보낼 수 있게)
except Exception: # noqa: BLE001 — DB 가 잠시 없어도 앱은 뜬다
pass
return st
+253
View File
@@ -0,0 +1,253 @@
"""outreach_db PostgreSQL 저장소 — 안내문 발송(2026-10-27).
- 연결: 환경변수 `OUTREACH_DB_URL` (예: postgresql://outreach_app:<pwd>@postgres-db:5432/outreach_db)
- 스키마는 앱이 만들지 않는다 — `scripts/sql/outreach_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from psycopg.errors import UndefinedTable
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool
from app.timezone import KST
from . import store
MAX_IMAGES = 10
def _iso(v: Any) -> str:
return v.astimezone(KST).isoformat(timespec="seconds") if isinstance(v, datetime) else ""
class OutreachDBStore:
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
self._pool.open(wait=False)
def close(self) -> None:
self._pool.close()
# ── 설정(제목·본문·보내는 이름·끝 문구·(광고)) ─────────────────
def get_template(self) -> dict[str, Any]:
with self._pool.connection() as conn:
row = conn.execute("SELECT value, updated_by, updated_at FROM outreach_settings WHERE key = 'template'").fetchone()
t = store.normalize_template(row["value"] if row and isinstance(row["value"], dict) else None)
t["updated_by"] = row["updated_by"] if row else ""
t["updated_at"] = _iso(row["updated_at"]) if row else ""
t["is_default"] = row is None
return t
def save_template(self, value: dict[str, Any], *, by: str) -> dict[str, Any]:
t = store.normalize_template(value)
if not t["subject"]:
raise ValueError("메일 제목을 쓰세요.")
if not store.html_to_text(t["body"]).strip():
raise ValueError("본문을 쓰세요.")
if len(t["body"]) > store.BODY_MAX:
raise ValueError("본문이 너무 깁니다(서식 포함) — 줄여 주세요.")
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO outreach_settings (key, value, updated_by, updated_at) VALUES ('template', %s, %s, now()) "
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, updated_at = now()",
(Jsonb({k: t[k] for k in store.DEFAULT_TEMPLATE}), (by or "").lower()),
)
return self.get_template()
# ── 메일 본문 아래 사진 ────────────────────────────────
def list_images(self, *, with_data: bool = False) -> list[dict[str, Any]]:
cols = "id, filename, width, height, sort_order" + (", data" if with_data else "")
with self._pool.connection() as conn:
rows = conn.execute(f"SELECT {cols} FROM outreach_images ORDER BY sort_order, id").fetchall()
return [dict(r) for r in rows]
def get_image(self, image_id: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM outreach_images WHERE id = %s", (image_id,)).fetchone()
def add_image(self, *, filename: str, data: bytes, width: int, height: int, by: str) -> int:
with self._pool.connection() as conn:
with conn.transaction():
n = conn.execute("SELECT COUNT(*) AS n, COALESCE(MAX(sort_order), -1) + 1 AS nxt FROM outreach_images").fetchone()
if n["n"] >= MAX_IMAGES:
raise ValueError(f"사진은 {MAX_IMAGES}장까지 넣을 수 있습니다.")
return int(conn.execute(
"INSERT INTO outreach_images (filename, data, width, height, sort_order, created_by) "
"VALUES (%s, %s, %s, %s, %s, %s) RETURNING id",
(filename[:200], data, width, height, int(n["nxt"]), (by or "").lower()),
).fetchone()["id"])
def delete_image(self, image_id: int) -> None:
with self._pool.connection() as conn:
conn.execute("DELETE FROM outreach_images WHERE id = %s", (image_id,))
def move_image(self, image_id: int, direction: int) -> None:
"""사진 순서 한 칸 앞/뒤(-1/1)."""
ids = [r["id"] for r in self.list_images()]
if image_id not in ids:
return
i = ids.index(image_id)
j = i + (-1 if direction < 0 else 1)
if not 0 <= j < len(ids):
return
ids[i], ids[j] = ids[j], ids[i]
with self._pool.connection() as conn:
conn.execute("UPDATE outreach_images m SET sort_order = v.ord FROM unnest(%s::int[]) WITH ORDINALITY AS v(id, ord) "
"WHERE m.id = v.id", (ids,))
# ── 리스트 ───────────────────────────────────────────
@staticmethod
def _row(r: dict[str, Any]) -> dict[str, Any]:
d = dict(r)
d["id"] = int(d["id"])
for k in ("sent_at", "created_at", "updated_at"):
d[k] = _iso(d.get(k))
return d
def list_recipients(self) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute("SELECT * FROM outreach_recipients ORDER BY id").fetchall()
return [self._row(r) for r in rows]
def get_recipient(self, rid: int) -> dict[str, Any] | None:
with self._pool.connection() as conn:
r = conn.execute("SELECT * FROM outreach_recipients WHERE id = %s", (rid,)).fetchone()
return self._row(r) if r else None
def add_recipients(self, rows: list[dict[str, Any]], *, by: str) -> dict[str, int]:
"""[{address, name}] 추가 — 주소를 보고 메일/DM 을 정한다. 이미 있는 주소는 이름만 비어 있으면 채우고 건너뜀.
반환 {added, existed, invalid}. 틀린 주소는 저장하지 않고 센다(화면이 미리 보여 줌)."""
out = {"added": 0, "existed": 0, "invalid": 0}
who = (by or "").lower()
with self._pool.connection() as conn:
with conn.transaction():
for r in rows:
d = store.detect(r.get("address"))
if not d["kind"]:
out["invalid"] += 1
continue
name = str(r.get("name") or "").strip()[:100]
got = conn.execute(
"INSERT INTO outreach_recipients (kind, handle, address, name, created_by) VALUES (%s, %s, %s, %s, %s) "
"ON CONFLICT (kind, handle) DO UPDATE SET name = CASE WHEN outreach_recipients.name = '' "
"THEN EXCLUDED.name ELSE outreach_recipients.name END RETURNING (xmax = 0) AS inserted",
(d["kind"], d["handle"], str(r.get("address") or "").strip()[:320], name, who),
).fetchone()
out["added" if got["inserted"] else "existed"] += 1
return out
def update_recipient(self, rid: int, *, name: Any = None, memo: Any = None, status: Any = None) -> dict[str, Any]:
sets, params = [], []
if name is not None:
sets.append("name = %s")
params.append(str(name).strip()[:100])
if memo is not None:
sets.append("memo = %s")
params.append(str(memo).strip()[:500])
if status is not None:
if status != "대기":
raise ValueError("상태는 '대기'(다시 보내기)로만 바꿀 수 있습니다.")
sets += ["status = '대기'", "last_error = ''"]
if not sets:
raise ValueError("바꿀 내용이 없습니다.")
with self._pool.connection() as conn:
r = conn.execute(f"UPDATE outreach_recipients SET {', '.join(sets)} WHERE id = %s RETURNING *", (*params, rid)).fetchone()
if not r:
raise KeyError(rid)
return self._row(r)
def delete_recipients(self, ids: list[int]) -> int:
with self._pool.connection() as conn:
cur = conn.execute("DELETE FROM outreach_recipients WHERE id = ANY(%s) AND status <> '발송중'", ([int(i) for i in ids],))
return cur.rowcount
# ── 보내기 ───────────────────────────────────────────
def claim_for_send(self, ids: list[int]) -> list[dict[str, Any]]:
"""메일 일괄 발송 — 고른 줄 중 메일·대기/실패만 '발송중'으로 바꾸며 가져온다(한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번만)."""
with self._pool.connection() as conn:
rows = conn.execute(
"UPDATE outreach_recipients SET status = '발송중', last_error = '' "
"WHERE id = ANY(%s) AND kind = 'email' AND status IN ('대기', '실패') RETURNING *",
([int(i) for i in ids],),
).fetchall()
return sorted((self._row(r) for r in rows), key=lambda r: r["id"])
def finish_send(self, rid: int, *, ok: bool, via: str, by: str, subject: str, error: str = "") -> None:
with self._pool.connection() as conn:
with conn.transaction():
r = conn.execute(
"UPDATE outreach_recipients SET status = %s, sent_at = CASE WHEN %s THEN now() ELSE sent_at END, "
"sent_by = CASE WHEN %s THEN %s ELSE sent_by END, sent_via = CASE WHEN %s THEN %s ELSE sent_via END, "
"last_error = %s WHERE id = %s RETURNING kind, address, name",
("보냄" if ok else "실패", ok, ok, (by or "").lower(), ok, via, (error or "")[:500], rid),
).fetchone()
if r:
conn.execute(
"INSERT INTO outreach_logs (recipient_id, kind, address, name, subject, via, sent_by, ok, error) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
(rid, r["kind"], r["address"], r["name"], (subject or "")[:300], via, (by or "").lower(), ok, (error or "")[:500]),
)
def mark_dm_sent(self, rid: int, *, by: str, subject: str) -> dict[str, Any]:
"""DM [보냄] — 인스타 줄만(사람이 DM 창에서 보낸 뒤 누름)."""
r = self.get_recipient(rid)
if r is None:
raise KeyError(rid)
if r["kind"] != "instagram":
raise ValueError("메일 줄은 [일괄 발송]으로 보냅니다.")
self.finish_send(rid, ok=True, via="dm", by=by, subject=subject)
return self.get_recipient(rid) # type: ignore[return-value]
def release_stuck(self) -> int:
"""서버가 보내던 중 멈춘 줄(발송중)을 실패로 — 서버 시작 때(앱은 프로세스 하나, 보내기는 메모리 작업)."""
with self._pool.connection() as conn:
cur = conn.execute("UPDATE outreach_recipients SET status = '실패', last_error = '보내던 중 서버가 다시 시작됨 — 다시 보내세요' "
"WHERE status = '발송중'")
return cur.rowcount
# ── DM 수동 보내기 탭의 저장한 본문(마이그레이션 002) ──────────
def list_dm_bodies(self) -> list[dict[str, Any]] | None:
"""새로 고친 것부터. 표가 없으면(002 미적용) None — 화면이 저장 목록만 숨긴다."""
try:
with self._pool.connection() as conn:
rows = conn.execute("SELECT id, title, body, created_by, updated_by, updated_at FROM outreach_dm_bodies "
"ORDER BY updated_at DESC, id DESC").fetchall()
except UndefinedTable:
return None
return [{**dict(r), "id": int(r["id"]), "updated_at": _iso(r["updated_at"])} for r in rows]
def save_dm_body(self, body: Any, *, by: str, body_id: int | None = None) -> int:
"""새로 저장(body_id 없음) 또는 그 본문 고치기. 저장한 id. 없는 id = KeyError."""
title, text = store.dm_saved_body(body)
by = (by or "").lower()
with self._pool.connection() as conn:
if body_id is None:
return int(conn.execute(
"INSERT INTO outreach_dm_bodies (title, body, created_by, updated_by) VALUES (%s, %s, %s, %s) RETURNING id",
(title, text, by, by)).fetchone()["id"])
row = conn.execute("UPDATE outreach_dm_bodies SET title = %s, body = %s, updated_by = %s, updated_at = now() "
"WHERE id = %s RETURNING id", (title, text, by, body_id)).fetchone()
if row is None:
raise KeyError(body_id)
return int(row["id"])
def delete_dm_body(self, body_id: int) -> None:
with self._pool.connection() as conn:
conn.execute("DELETE FROM outreach_dm_bodies WHERE id = %s", (body_id,))
def list_logs(self, *, limit: int = 200) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute("SELECT * FROM outreach_logs ORDER BY sent_at DESC, id DESC LIMIT %s", (limit,)).fetchall()
out = []
for r in rows:
d = dict(r)
d["sent_at"] = _iso(d["sent_at"])
out.append(d)
return out
+450
View File
@@ -0,0 +1,450 @@
"""안내문 발송(outreach) 라우터 — 리스트(이메일·인스타 주소 + 이름)에 안내문 메일 일괄 발송·인스타 DM 반자동(2026-10-27).
GET /outreach/ 리스트 + 보내기 화면
GET /outreach/settings 설정 — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고)·본문 아래 사진
POST /outreach/settings 설정 저장 · POST /settings/images(올리기) · /settings/images/{id}/delete · /move
GET /outreach/images/{id} 사진(설정·미리보기)
GET /outreach/api/recipients 리스트(JSON — 발송 중 진행 보기)
POST /outreach/api/recipients/parse 붙여 넣은 글 해석 미리보기(메일/DM/오류)
POST /outreach/api/recipients 리스트에 추가 {text}
PUT /outreach/api/recipients/{id} 이름·메모 고치기, 다시 대기로 {status: "대기"}
POST /outreach/api/recipients/delete 지우기 {ids}
GET /outreach/api/recipients/{id}/preview 그 사람에게 갈 제목·HTML·DM 글
POST /outreach/api/send 고른 메일 줄 일괄 발송 {ids} — 본인 Gmail, 백그라운드
POST /outreach/api/recipients/{id}/dm-sent DM 보냄 표시(사람이 DM 창에서 보낸 뒤)
GET /outreach/gmail/connect · POST /gmail/disconnect 내 Gmail 연결(입출고·휴가와 같은 연결, 같은 구글 콜백)
권한: 모듈 권한키 `outreach`(보기·리스트·보내기·설정 모두). DB: OUTREACH_DB_URL(outreach_db) — 없으면 "설정 필요" 안내.
"""
from __future__ import annotations
from io import BytesIO
from typing import Any
from urllib.parse import urlencode
from fastapi import APIRouter, BackgroundTasks, Body, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from . import store
router = APIRouter(prefix="/outreach", tags=["outreach"])
IMAGE_MAX_W = 700
IMAGE_MAX_BYTES = 15 * 1024 * 1024
MAX_ADD = 2000
def _store(request: Request) -> Any:
return getattr(request.app.state, "outreach_store", None)
def _inout(request: Request) -> Any:
return getattr(request.app.state, "inout_store", None)
def _user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
if not has_module(user, "outreach"):
raise HTTPException(status_code=403, detail="안내문 발송 모듈 권한이 없습니다.")
return user
def _db(request: Request) -> Any:
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="안내문 발송 DB(OUTREACH_DB_URL)가 설정되지 않았습니다.")
return st
def _page(request: Request) -> Any:
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return login_redirect(request)
if not has_module(user, "outreach"):
return render_template(request, "denied.html", {"reason": "안내문 발송 모듈 접근 권한이 없습니다.",
"is_admin": is_admin(user)}, status_code=403)
st = _store(request)
if st is None:
return render_template(request, "denied.html", {
"reason": "안내문 발송 모듈이 아직 설정되지 않았습니다. scripts/sql/outreach_db_init.sql 로 outreach_db 를 만들고 "
".env 에 OUTREACH_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.",
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="outreach")}, status_code=503)
return st, user
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
return render_template(request, name, {"user": user, "is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active="outreach"), **ctx})
def _gmail_state(request: Request, user: dict[str, Any]) -> dict[str, Any]:
from app.modules.inout import gmail # noqa: WPS433
inout = _inout(request)
connected = False
if inout is not None:
try:
connected = inout.gmail_token(user["email"]) is not None
except Exception: # noqa: BLE001
connected = False
return {"available": inout is not None and gmail.configured(), "connected": connected, "email": user["email"]}
def _view(r: dict[str, Any], template: dict[str, Any]) -> dict[str, Any]:
"""리스트 한 줄 화면용 — 구분 라벨, DM 이면 그 사람 이름을 넣은 DM 글·DM 창 주소(누르는 순간 복사·열기라 미리 담아 둔다)."""
out = {k: r.get(k) for k in ("id", "kind", "handle", "address", "name", "memo", "status", "sent_at", "sent_by", "sent_via",
"last_error")}
out["kind_label"] = store.KIND_LABELS.get(r["kind"], "")
out["needs_name"] = store.needs_name(template, r["kind"]) and not (r.get("name") or "").strip()
if r["kind"] == "instagram":
out["dm_link"] = store.dm_link(r["handle"])
out["profile_link"] = store.profile_link(r["handle"])
out["dm_text"] = store.dm_text(template, r.get("name") or "")
return out
# ════════════════════════════════════════════════════════════
# 화면
# ════════════════════════════════════════════════════════════
@router.get("/health")
def health(request: Request) -> JSONResponse:
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
@router.get("/", response_class=HTMLResponse)
def index(request: Request) -> Any:
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
template = st.get_template()
rows = [_view(r, template) for r in st.list_recipients()]
return _render(request, "outreach/index.html", user, {
"page_title": "안내문 발송", "page_subtitle": "메일 일괄 발송 · 인스타 DM",
"template": template, "body_text": store.html_to_text(template["body"]), "needs_name": store.needs_name(template),
"images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50), "active_tab": "list",
"gmail": _gmail_state(request, user), "msg": request.query_params.get("msg", ""),
})
@router.get("/dm", response_class=HTMLResponse)
def dm_page(request: Request) -> Any:
"""DM 수동 보내기 탭(2026-10-30) — 이름 목록 | 고칠 수 있는 본문(화면이 {이름} 을 바꿔 복사) | 저장한 본문 목록."""
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
return _render(request, "outreach/dm.html", user, {
"page_title": "안내문 발송", "page_subtitle": "DM 수동 보내기", "active_tab": "dm",
# {이름} 을 그대로 둔 DM 문구(리스트 줄 [DM 보내기]와 같은 글) + 저장한 본문 목록(002 미적용 = None)
"dm_template": store.dm_text(st.get_template(), store.NAME_TAG),
"dm_bodies": st.list_dm_bodies(), "dm_max": store.DM_MAX,
})
_DM_BODIES_MIGRATION_MSG = "본문 저장 표가 없습니다 — outreach_db 마이그레이션 002(scripts/sql/outreach_db_002_dm_bodies.sql)를 적용하세요."
def _dm_body_save(request: Request, payload: dict[str, Any], body_id: int | None) -> JSONResponse:
from psycopg.errors import UndefinedTable # noqa: WPS433
user = _user(request)
st = _db(request)
try:
saved = st.save_dm_body(payload.get("body"), by=user.get("email", ""), body_id=body_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError:
raise HTTPException(status_code=404, detail="저장한 본문이 없습니다(다른 사람이 지웠을 수 있음).")
except UndefinedTable:
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
return JSONResponse({"id": saved, "items": st.list_dm_bodies() or []})
@router.post("/api/dm-bodies")
def api_dm_body_add(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""DM 수동 보내기 — 본문 새로 저장(제목 = 첫 줄)."""
return _dm_body_save(request, payload, None)
@router.put("/api/dm-bodies/{body_id:int}")
def api_dm_body_update(request: Request, body_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""DM 수동 보내기 — 고른 저장 본문 고치기."""
return _dm_body_save(request, payload, body_id)
@router.delete("/api/dm-bodies/{body_id:int}")
def api_dm_body_delete(request: Request, body_id: int) -> JSONResponse:
from psycopg.errors import UndefinedTable # noqa: WPS433
_user(request)
st = _db(request)
try:
st.delete_dm_body(body_id)
except UndefinedTable:
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
return JSONResponse({"items": st.list_dm_bodies() or []})
@router.get("/settings", response_class=HTMLResponse)
def settings_page(request: Request) -> Any:
got = _page(request)
if not isinstance(got, tuple):
return got
st, user = got
return _render(request, "outreach/settings.html", user, {
"page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · DM 문구 · 사진",
"template": st.get_template(), "default": store.normalize_template(None), "images": st.list_images(),
"max_images": 10, "dm_max": store.DM_MAX, "msg": request.query_params.get("msg", ""),
})
@router.post("/settings")
def settings_save(request: Request, subject: str = Form(""), body: str = Form(""), sender_name: str = Form(""),
footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form(""),
fmt: str = Form("text")) -> RedirectResponse:
"""body = 설정 화면 편집기 HTML(fmt=html, 서버가 다시 정리) — fmt 없이 오면 글로 본다."""
user = _user(request)
st = _db(request)
try:
st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer, "dm_body": dm_body,
"ad_label": ad_label in ("1", "on", "true"), "fmt": "html" if fmt == "html" else "text"},
by=user["email"])
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "설정을 저장했습니다."}), status_code=303)
def _shrink(data: bytes) -> tuple[bytes, int, int]:
"""사진 → 메일용 JPEG(가로 최대 700px, 회전 정보 반영, 투명 = 흰 바탕). 못 여는 파일(HEIC 등)은 ValueError."""
from PIL import Image, ImageOps # noqa: WPS433
try:
im = Image.open(BytesIO(data))
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 > IMAGE_MAX_W:
im = im.resize((IMAGE_MAX_W, max(1, round(im.height * IMAGE_MAX_W / im.width))), Image.LANCZOS)
buf = BytesIO()
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
except Exception: # noqa: BLE001
raise ValueError("사진을 열 수 없습니다(JPG·PNG·WEBP 를 올리세요 — HEIC 는 안 됩니다).") from None
return buf.getvalue(), im.width, im.height
@router.post("/settings/images")
def images_upload(request: Request, files: list[UploadFile] = File(...)) -> RedirectResponse:
user = _user(request)
st = _db(request)
added, errors = 0, []
for f in files:
data = f.file.read(IMAGE_MAX_BYTES + 1)
if not data:
continue
if len(data) > IMAGE_MAX_BYTES:
errors.append(f"{f.filename}: 15MB 보다 큽니다")
continue
try:
jpg, w, h = _shrink(data)
st.add_image(filename=f.filename or "photo.jpg", data=jpg, width=w, height=h, by=user["email"])
added += 1
except ValueError as exc:
errors.append(f"{f.filename}: {exc}")
msg = f"사진 {added}장을 넣었습니다." + (" · " + " · ".join(errors) if errors else "")
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": msg}) + "#images", status_code=303)
@router.post("/settings/images/{image_id:int}/delete")
def images_delete(request: Request, image_id: int) -> RedirectResponse:
_user(request)
_db(request).delete_image(image_id)
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "사진을 뺐습니다."}) + "#images", status_code=303)
@router.post("/settings/images/{image_id:int}/move")
def images_move(request: Request, image_id: int, direction: int = Form(...)) -> RedirectResponse:
_user(request)
_db(request).move_image(image_id, direction)
return RedirectResponse(url="/outreach/settings#images", status_code=303)
@router.get("/images/{image_id:int}")
def image_view(request: Request, image_id: int) -> Response:
_user(request)
im = _db(request).get_image(image_id)
if im is None:
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
return Response(content=bytes(im["data"]), media_type="image/jpeg", headers={"Cache-Control": "private, max-age=3600"})
# ════════════════════════════════════════════════════════════
# 리스트 API
# ════════════════════════════════════════════════════════════
@router.get("/api/recipients")
def api_list(request: Request) -> JSONResponse:
_user(request)
st = _db(request)
template = st.get_template()
return JSONResponse({"rows": [_view(r, template) for r in st.list_recipients()]})
@router.post("/api/recipients/parse")
def api_parse(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""붙여 넣은 글 → 줄마다 {address, name, kind, kind_label, handle, error, dup, exists} (저장 안 함)."""
_user(request)
st = _db(request)
rows = store.parse_bulk(str(payload.get("text") or ""))[:MAX_ADD]
have = {(r["kind"], r["handle"]) for r in st.list_recipients()}
for r in rows:
r["kind_label"] = store.KIND_LABELS.get(r["kind"] or "", "오류")
r["exists"] = bool(r["kind"]) and (r["kind"], r["handle"]) in have
return JSONResponse({"rows": rows})
@router.post("/api/recipients")
def api_add(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
user = _user(request)
st = _db(request)
rows = [r for r in store.parse_bulk(str(payload.get("text") or "")) if not r["dup"]]
if len(rows) > MAX_ADD:
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_ADD}줄까지 넣을 수 있습니다.")
res = st.add_recipients(rows, by=user["email"])
return JSONResponse({"ok": True, **res})
@router.put("/api/recipients/{rid:int}")
def api_update(request: Request, rid: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_user(request)
st = _db(request)
try:
r = st.update_recipient(rid, name=payload.get("name"), memo=payload.get("memo"), status=payload.get("status"))
except KeyError:
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return JSONResponse({"row": _view(r, st.get_template())})
@router.post("/api/recipients/delete")
def api_delete(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
_user(request)
try:
ids = [int(i) for i in payload.get("ids") or []]
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ids 가 올바르지 않습니다.")
return JSONResponse({"ok": True, "deleted": _db(request).delete_recipients(ids)})
@router.get("/api/recipients/{rid:int}/preview")
def api_preview(request: Request, rid: int) -> JSONResponse:
"""그 사람에게 갈 제목·HTML(사진은 /outreach/images 주소로)·DM 글."""
_user(request)
st = _db(request)
r = st.get_recipient(rid)
if r is None:
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
t = st.get_template()
html = store.html_body(t, r["name"], [f"img-{im['id']}" for im in st.list_images()])
for im in st.list_images():
html = html.replace(f"cid:img-{im['id']}", f"/outreach/images/{im['id']}")
return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html,
"text": store.dm_text(t, r["name"]) if r["kind"] == "instagram" else store.plain_text(t, r["name"]),
"kind": r["kind"], "to": r["handle"], "sender_name": t["sender_name"]})
@router.post("/api/send")
def api_send(request: Request, bg: BackgroundTasks, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""고른 줄 중 메일·대기/실패를 '발송중'으로 잡고(한 번만) 백그라운드로 본인 Gmail 발송. 진행은 GET /api/recipients 로."""
from . import send # noqa: WPS433
user = _user(request)
st = _db(request)
try:
ids = [int(i) for i in payload.get("ids") or []]
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail="ids 가 올바르지 않습니다.")
if not ids:
raise HTTPException(status_code=400, detail="보낼 줄을 고르세요.")
gm = _gmail_state(request, user)
if not gm["connected"]:
return JSONResponse({"ok": False, "reconnect": True,
"message": "Gmail 이 연결되지 않았습니다 — [Gmail 연결]을 먼저 하세요(내 Gmail 로 보냅니다)."},
status_code=409)
rows = st.claim_for_send(ids)
if not rows:
return JSONResponse({"ok": False, "message": "보낼 메일 줄이 없습니다(이미 보냈거나 보내는 중, 또는 DM 줄)."}, status_code=409)
bg.add_task(send.send_batch, st, _inout(request), rows=rows, user=dict(user))
return JSONResponse({"ok": True, "queued": len(rows)}, status_code=202)
@router.post("/api/recipients/{rid:int}/dm-sent")
def api_dm_sent(request: Request, rid: int) -> JSONResponse:
user = _user(request)
st = _db(request)
t = st.get_template()
r0 = st.get_recipient(rid)
if r0 is None:
raise HTTPException(status_code=404, detail="리스트에 없는 줄입니다.")
try:
r = st.mark_dm_sent(rid, by=user["email"], subject=store.subject_for(t, r0["name"]))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
return JSONResponse({"row": _view(r, t)})
# ════════════════════════════════════════════════════════════
# 내 Gmail 연결 — 입출고·휴가와 같은 연결(inout_gmail_tokens), 같은 구글 콜백(/inout/gmail/callback)
# ════════════════════════════════════════════════════════════
@router.get("/gmail/connect")
async def gmail_connect(request: Request) -> Any:
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
from app.modules.inout import gmail # noqa: WPS433
user = _user(request)
if _inout(request) is None:
return RedirectResponse(url="/outreach/?" + urlencode({"msg": "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다."}),
status_code=303)
try:
client = gmail.oauth_client()
except gmail.GmailError as exc:
return RedirectResponse(url="/outreach/?" + urlencode({"msg": str(exc)}), status_code=303)
request.session["_gmail_origin"] = "outreach"
request.session["_gmail_next"] = "/outreach/"
return await client.authorize_redirect(
request, public_url_for(request, "inout_gmail_callback"),
access_type="offline", prompt="consent", include_granted_scopes="true",
login_hint=user.get("email", ""), hd=ALLOWED_DOMAIN)
@router.post("/gmail/disconnect")
def gmail_disconnect(request: Request) -> RedirectResponse:
from app.modules.inout import gmail # noqa: WPS433
user = _user(request)
inout = _inout(request)
if inout is not None:
row = inout.gmail_token(user["email"])
if row:
try:
gmail.revoke(gmail.decrypt_token(user["email"], row["refresh_token_enc"]))
except (gmail.GmailError, gmail.GmailNotConnected):
pass
inout.delete_gmail_token(user["email"])
return RedirectResponse(url="/outreach/?" + urlencode({"msg": "Gmail 연결을 끊었습니다(입출고·휴가 메일 연결도 함께)."}),
status_code=303)
+94
View File
@@ -0,0 +1,94 @@
"""안내문 메일 일괄 발송(2026-10-27) — 보내는 사람 본인 Gmail(입출고·휴가와 같은 Gmail 연결, gmail.send 만)로 한 사람에 한 통.
라우터가 고른 줄을 '발송중'으로 잡은 뒤(db.claim_for_send — 두 번 눌러도 한 번) 응답하고, 이 함수가 백그라운드에서 차례로 보낸다.
줄마다 {이름} 을 바꾼 제목·본문 + 설정 사진(본문 아래, cid)을 만들어 보내고 보냄/실패와 기록(outreach_logs)을 남긴다.
본문에 {이름} 이 있는데 이름이 빈 줄은 보내지 않고 실패('이름 없음'). Gmail 연결이 끊기면 남은 줄은 실패(다시 연결 안내).
"""
from __future__ import annotations
import logging
import time
from typing import Any
from . import store
logger = logging.getLogger("app.outreach.send")
SEND_GAP_SECONDS = 1.0 # 한 통마다 쉬는 시간 — Gmail 이 짧은 시간에 몰린 발송을 막지 않게
def _cid(image_id: int) -> str:
return f"outreach-{image_id}@dbx"
def build_mail(template: dict[str, Any], images: list[dict[str, Any]], *, name: str, sender_name: str, sender_email: str,
to: str) -> bytes:
from app.modules.inout import gmail # noqa: WPS433
cids = [_cid(int(im["id"])) for im in images]
return gmail.build_message(
sender_name=template.get("sender_name") or sender_name, sender_email=sender_email, to=[to], cc=[],
subject=store.subject_for(template, name), text=store.plain_text(template, name),
html=store.html_body(template, name, cids),
inline_images=[{"cid": c, "data": bytes(im["data"])} for c, im in zip(cids, images)],
)
def send_batch(db: Any, inout_store: Any, *, rows: list[dict[str, Any]], user: dict[str, Any],
gap: float = SEND_GAP_SECONDS) -> dict[str, int]:
"""잡아 둔 줄(rows)을 차례로 보낸다 — {"sent", "failed"}. 예외를 밖으로 던지지 않는다(줄마다 결과를 남김)."""
from app.modules.inout import gmail # noqa: WPS433
email = str(user.get("email") or "").lower()
result = {"sent": 0, "failed": 0}
try:
template = db.get_template()
images = db.list_images(with_data=True)
subject_of = lambda r: store.subject_for(template, r["name"]) # noqa: E731
row = inout_store.gmail_token(email) if inout_store is not None else None
refresh = gmail.decrypt_token(email, row["refresh_token_enc"]) if row else None
except Exception as exc: # noqa: BLE001 — 준비 실패 = 잡아 둔 줄 모두 실패(발송중으로 남지 않게)
for r in rows:
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject="", error=f"보낼 준비 실패: {exc}")
result["failed"] = len(rows)
return result
stop_reason = "" if refresh else "Gmail 이 연결되지 않았습니다 — 안내문 발송 → [Gmail 연결] 뒤 다시 보내세요."
need_name = store.needs_name(template)
for i, r in enumerate(rows):
if stop_reason:
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason)
result["failed"] += 1
continue
if need_name and not (r.get("name") or "").strip():
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r),
error="이름 없음 — 본문에 {이름} 이 있어 이름을 넣은 뒤 다시 보내세요.")
result["failed"] += 1
continue
try:
raw = build_mail(template, images, name=r["name"], sender_name=str(user.get("name") or ""),
sender_email=email, to=r["handle"])
gmail.send(refresh, raw)
except gmail.GmailNotConnected as exc:
try:
inout_store.delete_gmail_token(email)
except Exception: # noqa: BLE001
pass
stop_reason = f"Gmail 연결이 끊겼습니다 — 다시 연결한 뒤 보내세요. ({exc})"
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=stop_reason)
result["failed"] += 1
continue
except Exception as exc: # noqa: BLE001 — 그 사람만 실패(받는 주소 오류 등), 다음 사람은 계속
db.finish_send(r["id"], ok=False, via="gmail", by=email, subject=subject_of(r), error=str(exc)[:300])
result["failed"] += 1
continue
db.finish_send(r["id"], ok=True, via="gmail", by=email, subject=subject_of(r))
result["sent"] += 1
if gap and i < len(rows) - 1:
time.sleep(gap)
try:
if inout_store is not None and result["sent"]:
inout_store.mark_gmail(email)
except Exception: # noqa: BLE001
pass
logger.info("안내문 메일 %s: 보냄 %s · 실패 %s", email, result["sent"], result["failed"])
return result
+369
View File
@@ -0,0 +1,369 @@
"""안내문 발송 — 순수 함수(DB 없음): 주소 판별(이메일 / 인스타그램), 리스트 붙여넣기 해석, {이름} 바꾸기, 메일 HTML·DM 글.
- 주소를 보고 정한다: `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
- 본문 `{이름}` = 그 줄 이름. 메일 본문 = 설정 화면 편집기의 HTML(`fmt: "html"`) — 저장·읽을 때마다 `sanitize_html`(허용 태그·스타일만).
예전 글·기본 문구(`fmt` 없음 = 글)는 `text_to_html`(`**굵게**` → 굵게, 주소 → 링크, 줄마다 문단).
- DM 글 = 설정 `dm_body`(인스타 DM 용 글, 서식 없음). 비어 있으면 메일 본문 글 + 끝 문구.
"""
from __future__ import annotations
import re
from html import escape
from html.parser import HTMLParser
from typing import Any
NAME_TAG = "{이름}"
KINDS = ("email", "instagram")
KIND_LABELS = {"email": "메일", "instagram": "DM"}
STATUSES = ("대기", "발송중", "보냄", "실패")
_EMAIL_RE = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$")
_IG_USER_RE = re.compile(r"^[A-Za-z0-9._]{1,30}$")
_IG_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?(?:instagram\.com|instagr\.am)/([^/?#\s]+)", re.IGNORECASE)
_IG_ME_RE = re.compile(r"^(?:https?://)?ig\.me/m/([^/?#\s]+)", re.IGNORECASE)
# instagram.com 아래 계정이 아닌 주소(게시물·릴스 등)
_IG_RESERVED = {"p", "reel", "reels", "tv", "explore", "stories", "direct", "accounts", "about", "legal", "developer"}
DEFAULT_TEMPLATE: dict[str, Any] = {
"subject": "누적매출 300억. 800만개 판매 신화 미라클통 '미라네주방'입니다.",
"sender_name": "미라네주방",
"ad_label": False,
"footer": "",
"dm_body": "",
"fmt": "text", # body 형식 — 기본 문구는 글, 설정 화면에서 저장하면 "html"
"body": """안녕하세요, {이름}님.
주방의 본질을 지키며 6년간 묵묵히 300억 매출의 신화를 써온 **'미라네주방'**입니다.
저희는 지난 6년간 제품력 하나로 국내/해외 800만 개 판매를 돌파하고 호주, 동남아 등 글로벌 시장에서 인정받았습니다.
브랜드의 가치를 지키기 위해 공동구매를 극도로 자제해왔으나,
최근 'ㅎ 인플루언서'와의 PPL 및 전용 상품 협업을 통해 단일 프로젝트 매출 약3억, 누적 약 8억원이라는 놀라운 기록을 확인하였고,
ㄷ'인플루언서'님과는 약 2억원의 매출을 달성하는 등 인플루언서 파트너십의 새로운 가능성을 보았습니다.
이에, 압도적인 신뢰도와 감각을 보유하신 {이름}님과의 공동구매 파트너십을 정중히 제안드립니다.
왜 '미라네주방'이어야 하는가?
시장 점유율로 증명된 '미라클통'의 힘: 누적 800만 개 판매. 이미 시장에서 검증된 제품은 팔로워들에게 구구절절 설명할 필요가 없습니다.
희소성의 가치: 아무나 할 수 있는 공구가 아닙니다. 공구를 지양해온 브랜드이기에 {이름}님의 피드에서 진행되는 공구는 팔로워들에게 더욱 특별한 기회로 인식될 것입니다.
1단계: 검증된 베스트셀러로 화력 확인 (Existing Product)
이미 800만 개가 팔려나가며 시장성이 검증된 ‘미라클통’ 등 기존 베스트셀러 라인으로 공동구매를 진행합니다.
팔로워들에게는 '구하고 싶어도 공구로 만나기 힘들었던 제품'이라는 명분을, 인플루언서님께는 확실한 수익과 유입을 보장합니다.
2단계: 화력 입증 시 {이름}님 전용 상품 개발 (Exclusive Product)
첫 공구에서 유의미한 매출 성과가 확인될 경우, 저희는 즉시 {이름}님만을 위한 전용 상품(PB/콜라보) 개발에 착수합니다.
전용 컬러, 단독 구성, 혹은 니즈를 반영한 신규 기능을 담아, 어디에서도 볼 수 없는 '귀하만의 제품'을 시장에 선보이게 됩니다.
이는 인플루언서로서의 브랜드 가치를 한 단계 높이는 결정적인 계기가 될 것입니다.
"'ㅎ인플루언서님'과의 콜라보 사례를 하단과 같이 사진 공유드립니다."
미라네주방은 단순히 한 번의 공구로 끝나는 관계를 원하지 않습니다.
{이름}님의 감각과 저희의 기술력이 만나 주방용품 시장의 판도를 바꿀 '전용 브랜드'를 함께 만들어가길 희망합니다.
긍정적인 검토 부탁드리며, 미라네주방의 성공 신화에 함께 올라타실 파트너가 되어주시길 기다리겠습니다.
감사합니다.
미라네주방 팀 드림
https://miras.co.kr/""",
}
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 100000, 2000 # BODY_MAX = 정리한 HTML 길이
DM_MAX = 1000 # 인스타 DM 한 통 글자 수 한도
def _ig_user(value: str) -> str | None:
v = value.strip().strip("/")
if v.startswith("@"):
v = v[1:]
if not _IG_USER_RE.match(v) or v.startswith(".") or v.endswith(".") or ".." in v:
return None
if v.lower() in _IG_RESERVED:
return None
return v.lower()
def detect(address: Any) -> dict[str, Any]:
"""주소 → {"kind": "email"|"instagram"|None, "handle", "error"}. handle = 이메일 소문자 / 인스타 계정명 소문자."""
raw = str(address or "").strip().strip("<>").strip()
if raw.lower().startswith("mailto:"):
raw = raw[7:]
if not raw:
return {"kind": None, "handle": "", "error": "주소가 비었습니다."}
if "@" in raw and not raw.startswith("@") and "/" not in raw:
if _EMAIL_RE.match(raw) and len(raw) <= 320:
return {"kind": "email", "handle": raw.lower(), "error": ""}
return {"kind": None, "handle": "", "error": f"이메일 주소가 올바르지 않습니다: {raw}"}
for rx in (_IG_ME_RE, _IG_URL_RE):
m = rx.match(raw)
if m:
user = _ig_user(m.group(1))
if user:
return {"kind": "instagram", "handle": user, "error": ""}
return {"kind": None, "handle": "", "error": f"인스타그램 계정 주소가 아닙니다: {raw}"}
user = _ig_user(raw)
if user and (raw.startswith("@") or re.search(r"[A-Za-z]", raw)):
return {"kind": "instagram", "handle": user, "error": ""}
return {"kind": None, "handle": "", "error": f"이메일도 인스타그램 주소도 아닙니다: {raw}"}
def _looks_explicit(part: str) -> bool:
"""이메일·@계정·인스타 주소처럼 '주소'가 분명한 칸인가(계정명만 쓴 칸보다 먼저 주소로 고른다)."""
p = part.strip()
return "@" in p or "instagram.com" in p.lower() or "instagr.am" in p.lower() or "ig.me/" in p.lower()
def parse_line(line: str) -> dict[str, Any] | None:
"""붙여 넣은 한 줄 → {"address", "name", ...detect}. 빈 줄·#주석 = None.
칸 나누기 = 탭 · 쉼표 · (둘 다 없으면) 공백. 주소가 분명한 칸(이메일·@·인스타 링크)을 주소로, 나머지는 이름.
둘 다 분명하지 않으면 '주소, 이름' 순서로 본다."""
s = line.strip()
if not s or s.startswith("#"):
return None
parts = [p.strip() for p in re.split(r"\t|,", s) if p.strip()]
if len(parts) == 1:
parts = s.split()
addr_i = next((i for i, p in enumerate(parts) if _looks_explicit(p) and detect(p)["kind"]), None)
if addr_i is None:
addr_i = next((i for i, p in enumerate(parts) if detect(p)["kind"]), 0)
address = parts[addr_i]
name = " ".join(p for i, p in enumerate(parts) if i != addr_i).strip()
return {"address": address, "name": name[:100], **detect(address)}
def parse_bulk(text: str) -> list[dict[str, Any]]:
"""여러 줄 붙여넣기 → 줄마다 parse_line(빈 줄 건너뜀), 같은 주소는 처음 것만(dup=True 표시)."""
out: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
for i, line in enumerate(str(text or "").splitlines(), 1):
r = parse_line(line)
if r is None:
continue
r["line"] = i
key = (r["kind"] or "", r["handle"])
r["dup"] = bool(r["kind"]) and key in seen
seen.add(key)
out.append(r)
return out
def normalize_template(value: dict[str, Any] | None) -> dict[str, Any]:
"""설정 값 정리 — 빠진 칸은 기본값, 길이 제한."""
v = dict(DEFAULT_TEMPLATE)
for k, val in (value or {}).items():
if k in v:
v[k] = val
v["subject"] = str(v["subject"] or "").strip()[:SUBJECT_MAX]
body = str(v["body"] or "")[:BODY_MAX * 3]
v["body"] = sanitize_html(body if v["fmt"] == "html" else text_to_html(body))
v["fmt"] = "html"
v["footer"] = str(v["footer"] or "").replace("\r\n", "\n").strip()[:FOOTER_MAX]
v["dm_body"] = str(v["dm_body"] or "").replace("\r\n", "\n").strip()[:DM_MAX]
v["sender_name"] = str(v["sender_name"] or "").strip()[:60]
v["ad_label"] = bool(v["ad_label"])
return v
def needs_name(template: dict[str, Any], kind: str = "email") -> bool:
"""그 구분(메일/DM)으로 갈 글에 {이름}이 있는가 — DM 은 DM 문구(없으면 메일 본문)만 본다."""
if kind == "instagram" and (template.get("dm_body") or "").strip():
return NAME_TAG in template["dm_body"]
body = html_to_text(template.get("body") or "")
if kind == "instagram":
return NAME_TAG in body or NAME_TAG in (template.get("footer") or "")
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in body
def fill(text: str, name: str) -> str:
return str(text or "").replace(NAME_TAG, str(name or "").strip())
def subject_for(template: dict[str, Any], name: str) -> str:
s = fill(template.get("subject") or "", name)
return ("(광고) " + s) if template.get("ad_label") and not s.startswith("(광고)") else s
def plain_text(template: dict[str, Any], name: str) -> str:
"""메일 글 부분(HTML 메일의 글 버전)·DM 문구가 없을 때의 DM 글 — 본문 글 + 끝 문구."""
body = fill(html_to_text(template.get("body") or ""), name).rstrip()
footer = (template.get("footer") or "").strip()
return body + ("\n\n" + fill(footer, name) if footer else "")
def dm_text(template: dict[str, Any], name: str) -> str:
"""인스타 DM 글 — DM 문구가 있으면 그것, 없으면 메일 글(plain_text). **굵게** 는 별표만 뺀다."""
dm = (template.get("dm_body") or "").strip()
if not dm:
return plain_text(template, name)
return re.sub(r"\*\*(.+?)\*\*", r"\1", fill(dm, name))
def dm_saved_body(value: Any) -> tuple[str, str]:
"""DM 수동 보내기 탭에 저장할 본문 → (제목, 본문). 제목 = 첫 글 줄 40자(목록 표시용). 비었거나 너무 길면 ValueError."""
body = str(value or "").replace("\r\n", "\n").strip()
if not body:
raise ValueError("본문을 쓰세요.")
if len(body) > DM_MAX:
raise ValueError(f"본문은 {DM_MAX}자까지입니다(인스타 DM 한도) — 지금 {len(body)}자.")
title = next((ln.strip() for ln in body.split("\n") if ln.strip()), "")
return (title[:40] + ("…" if len(title) > 40 else "")), body
# ── 메일 본문 HTML ─────────────────────────────────────────
_URL_RE = re.compile(r"https?://[^\s<>\"']+")
_ALLOWED_TAGS = {"p", "br", "strong", "b", "em", "i", "u", "s", "strike", "span", "a", "ul", "ol", "li",
"h1", "h2", "h3", "blockquote", "sub", "sup"}
_DROP_WITH_CONTENT = {"script", "style", "iframe", "object", "head", "title", "template", "noscript", "svg", "math",
"textarea", "select"}
_STYLE_PROPS = {"color", "background-color", "font-size", "font-weight", "font-style", "text-decoration", "text-align"}
_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()-]{1,60}$")
# {이름} — 편집기에서 글자마다 서식이 달라 태그가 끼어도 찾는다(태그는 남기고 글자만 이름으로)
_NAME_IN_HTML_RE = re.compile(r"\{((?:<[^>]*>)*)이((?:<[^>]*>)*)름((?:<[^>]*>)*)\}")
def _clean_style(value: str) -> str:
out = []
for decl in value.split(";"):
prop, _, val = decl.partition(":")
prop, val = prop.strip().lower(), val.strip()
if prop in _STYLE_PROPS and _STYLE_VALUE_RE.match(val) and not re.search(r"url|expression", val, re.I):
out.append(f"{prop}: {val}")
return "; ".join(out)
class _Sanitizer(HTMLParser):
"""허용 태그·속성(style 은 글자 서식만, a 는 http(s)/mailto 링크만)만 남기고 글은 escape. 태그 짝은 맞춰 닫는다.
편집기(Quill getSemanticHTML)가 띄어쓰기를 &nbsp; 로 내보내 보통 띄어쓰기로 바꾼다(메일은 pre-wrap 이라 여러 칸도 그대로)."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.out: list[str] = []
self.stack: list[str] = []
self.skip = 0
self.empty_p = False # 지금 연 <p> 에 아직 글이 없다 — 닫을 때 <br> 을 넣어 빈 줄 높이를 지킨다
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in _DROP_WITH_CONTENT:
self.skip += 1
return
if self.skip or tag not in _ALLOWED_TAGS:
return
if tag == "br":
self.out.append("<br>")
self.empty_p = False
return
a = {k: v or "" for k, v in attrs}
extra = ""
style = _clean_style(a.get("style", ""))
if style:
extra += f' style="{escape(style)}"'
href = a.get("href", "").strip()
if tag == "a" and re.match(r"^(https?:|mailto:)", href, re.I):
extra += f' href="{escape(href)}"'
self.out.append(f"<{tag}{extra}>")
self.stack.append(tag)
if tag == "p":
self.empty_p = True
def handle_endtag(self, tag: str) -> None:
if tag in _DROP_WITH_CONTENT:
self.skip = max(0, self.skip - 1)
return
if self.skip or tag not in self.stack:
return
while self.stack:
t = self.stack.pop()
if t == "p" and self.empty_p:
self.out.append("<br>")
self.empty_p = False
self.out.append(f"</{t}>")
if t == tag:
break
def handle_data(self, data: str) -> None:
if self.skip:
return
text = data.replace("\r", "").replace("\n", " ").replace("\xa0", " ")
if not text.strip() and (not self.stack or self.stack[-1] in ("ul", "ol")):
return
if text:
self.out.append(escape(text, quote=False))
self.empty_p = False
def result(self) -> str:
self.close()
while self.stack:
self.handle_endtag(self.stack[-1])
return "".join(self.out)
def sanitize_html(html: str) -> str:
p = _Sanitizer()
p.feed(str(html or ""))
return p.result()
def text_to_html(text: str) -> str:
"""글(예전 본문·기본 문구) → 본문 HTML — 줄마다 문단, 빈 줄 = <p><br></p>, **굵게** → <strong>, 주소 → 링크."""
out = []
for line in str(text or "").replace("\r\n", "\n").rstrip("\n").split("\n"):
h = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", escape(line, quote=False))
h = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}">{m.group(0)}</a>', h)
out.append(f"<p>{h or '<br>'}</p>")
return "".join(out)
class _Text(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag == "br":
self.parts.append("\x00") # 문단 끝 바로 앞의 <br>(빈 줄 표시)은 줄을 하나 더 만들지 않는다
elif tag == "li":
self.parts.append("- ")
def handle_endtag(self, tag: str) -> None:
if tag in ("p", "li", "h1", "h2", "h3", "blockquote"):
if self.parts and self.parts[-1] == "\x00":
self.parts.pop()
self.parts.append("\n")
def handle_data(self, data: str) -> None:
self.parts.append(data.replace("\xa0", " "))
def html_to_text(html: str) -> str:
"""본문 HTML → 글(메일 글 버전·DM·{이름} 찾기·리스트 화면 요약)."""
p = _Text()
p.feed(str(html or ""))
p.close()
return "".join(p.parts).replace("\x00", "\n").rstrip()
def fill_html(html: str, name: str) -> str:
return _NAME_IN_HTML_RE.sub(lambda m: escape(str(name or "").strip()) + m.group(1) + m.group(2) + m.group(3), str(html or ""))
def _p_margin(html: str) -> str:
"""메일 프로그램은 <p> 에 위아래 여백을 줘 편집기보다 줄 간격이 벌어진다 — margin:0 을 붙인다."""
return re.sub(r'<p( style=")?', lambda m: '<p style="margin:0;' if m.group(1) else '<p style="margin:0"', html)
def html_body(template: dict[str, Any], name: str, image_cids: list[str] | None = None) -> str:
"""메일 HTML — 본문(정리된 편집기 HTML, {이름} 바꿈) + 끝 문구(글 → escape·링크) + 사진은 본문 아래(cid)."""
body = fill_html(sanitize_html(template.get("body") or ""), name)
footer = (template.get("footer") or "").strip()
if footer:
body += "<p><br></p>" + text_to_html(fill(footer, name))
imgs = "".join(f'<p style="margin:12px 0 0"><img src="cid:{c}" alt="" style="max-width:100%;height:auto;border-radius:6px"></p>'
for c in (image_cids or []))
return ('<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;line-height:1.7;color:#111;white-space:pre-wrap">'
f"{_p_margin(body)}</div>{imgs}")
def dm_link(handle: str) -> str:
"""인스타 DM 창 — ig.me/m/계정(앱·웹 모두 그 사람과의 대화로)."""
return f"https://ig.me/m/{handle}"
def profile_link(handle: str) -> str:
return f"https://www.instagram.com/{handle}/"
@@ -0,0 +1,13 @@
{#- 안내문 발송 탭(2026-10-30) — [발송 리스트] [DM 수동 보내기] + 맨 오른쪽 설정 톱니(실적·프로젝트와 같은 Material Symbols "settings") -#}
<nav class="otr-tabs" aria-label="안내문 발송 메뉴">
<div class="otr-tabs-main" role="tablist">
<a class="otr-tab{% if active_tab == 'list' %} is-active{% endif %}" href="/outreach/" role="tab"
aria-selected="{{ 'true' if active_tab == 'list' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">forward_to_inbox</span>발송 리스트</a>
<a class="otr-tab{% if active_tab == 'dm' %} is-active{% endif %}" href="/outreach/dm" role="tab"
aria-selected="{{ 'true' if active_tab == 'dm' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">chat</span>DM 수동 보내기</a>
</div>
<a class="otr-gear" href="/outreach/settings" title="설정" aria-label="설정">
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
</nav>
@@ -0,0 +1,51 @@
{% extends "erp_base.html" %}
{#- DM 수동 보내기 탭(2026-10-30) — 왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸) + 이름 목록(한 명씩·전체 지우기),
가운데 = 본문(고칠 수 있음, {이름} 자리는 분홍 이름 칩), 오른쪽 = 저장한 본문 목록(고르기·하나씩 지우기, outreach_db 002).
이름을 누르면 본문의 {이름} 이 그 이름으로 바뀌고 바로 클립보드에 복사. 이름 목록은 저장하지 않음(브라우저만). -#}
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
{% block content %}
<section class="otr otr-dm-page" id="otr-dm">
{% include "outreach/_tabs.html" %}
<div class="otr-dm-split">
<div class="erp-card otr-dm-left">
<div class="otr-add-head"><b>이름</b>
<span class="erp-muted">한 줄에 한 이름 — 붙여 넣거나 파일(.txt·.csv, 첫 칸)을 올리세요. 엑셀은 이름 칸을 복사해 붙여 넣으면 됩니다.</span></div>
<textarea class="erp-input otr-add-text" id="otr-dm-text" rows="4" placeholder="김철수&#10;미라네&#10;이수진"></textarea>
<div class="otr-add-actions">
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-load">이름 넣기</button>
<label class="erp-btn erp-btn-outline otr-dm-file">파일 올리기<input type="file" id="otr-dm-file" accept=".txt,.csv,text/plain,text/csv" hidden /></label>
</div>
<div class="otr-dm-listhead"><span class="erp-muted" id="otr-dm-sum">0명</span>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm otr-danger" id="otr-dm-clear" disabled>전체 삭제</button></div>
<ul class="otr-dm-names" id="otr-dm-names" aria-label="이름 목록"></ul>
</div>
<div class="erp-card otr-dm-right">
<div class="otr-add-head"><b>본문 <span class="otr-dm-cur" id="otr-dm-cur"></span></b>
<span class="erp-muted">바로 고칠 수 있습니다. 분홍 글자 = <code>{이름}</code> 자리(왼쪽 이름을 누르면 바뀌고 복사됨, 새 자리는 <code>{이름}</code> 이라고 쓰면 됨).</span></div>
<div class="otr-add-actions otr-dm-actions">
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-save" disabled title="오른쪽 목록에서 고른 본문을 이 글로 바꿉니다">저장</button>
<button type="button" class="erp-btn erp-btn-outline" id="otr-dm-saveas">새 본문으로 저장</button>
<span class="erp-muted" id="otr-dm-count"></span>
</div>
<div class="otr-dm-body" id="otr-dm-body" contenteditable="plaintext-only" spellcheck="false" role="textbox" aria-multiline="true" aria-label="본문"></div>
</div>
<div class="erp-card otr-dm-saved">
<div class="otr-add-head"><b>저장한 본문</b><span class="erp-muted">누르면 가운데 본문으로 불러옵니다.</span></div>
{% if dm_bodies is none %}
<p class="otr-msg">본문 저장 표가 아직 없습니다 — 관리자가 outreach_db 마이그레이션 002(<code>scripts/sql/outreach_db_002_dm_bodies.sql</code>)를 적용하면 저장할 수 있습니다.</p>
{% endif %}
<ul class="otr-dm-names otr-dm-bodies" id="otr-dm-bodies" aria-label="저장한 본문 목록"></ul>
</div>
</div>
</section>
<script type="application/json" id="otr-data">{{ {"dm_template": dm_template, "dm_bodies": dm_bodies, "dm_max": dm_max} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
@@ -0,0 +1,103 @@
{% extends "erp_base.html" %}
{#- 안내문 발송(2026-10-27) — 리스트(주소 + 이름) → 메일은 [선택한 메일 보내기](본인 Gmail, 한 사람에 한 통), 인스타는 [DM 보내기](문구 복사 + DM 창)
→ 보낸 뒤 [보냄]. 주소를 보고 메일/DM 을 정한다(store.detect). 본문 {이름} = 그 줄 이름. -#}
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
{% block content %}
<section class="otr" id="otr" data-needs-name="{{ '1' if needs_name else '' }}">
{% include "outreach/_tabs.html" %}
<div class="otr-top">
<div class="otr-top-main">
<button type="button" class="erp-btn erp-btn-primary" id="otr-add-open">+ 리스트 추가</button>
</div>
<div class="otr-gmail">
{% if gmail.connected %}
<span class="otr-gmail-on">보내는 메일: <b>{{ gmail.email }}</b> (Gmail 연결됨)</span>
<form method="post" action="/outreach/gmail/disconnect" onsubmit="return confirm('Gmail 연결을 끊을까요? 입출고·휴가 메일 연결도 함께 끊깁니다.');">
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">연결 끊기</button></form>
{% elif gmail.available %}
<span class="otr-gmail-off">메일은 내 Gmail 로 보냅니다 —</span>
<a class="erp-btn erp-btn-primary erp-btn-sm" href="/outreach/gmail/connect">Gmail 연결</a>
{% else %}
<span class="otr-gmail-off">Gmail 연결을 쓸 수 없는 서버입니다(입출고 DB·구글 OAuth·APP_ENCRYPTION_KEY 필요) — 메일은 보낼 수 없고 DM 만 됩니다.</span>
{% endif %}
</div>
</div>
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
<div class="erp-card otr-tpl">
<div class="otr-tpl-head"><b>보낼 내용</b><span class="erp-muted">(설정에서 바꿉니다)</span></div>
<div class="otr-tpl-subject">{% if template.ad_label %}(광고) {% endif %}{{ template.subject }}</div>
<div class="otr-tpl-body">{{ body_text[:160] }}{% if body_text | length > 160 %}…{% endif %}</div>
<div class="erp-muted otr-tpl-meta">보내는 이름 {{ template.sender_name or '—' }} · 본문 아래 사진 {{ images | length }}장 · <code>{이름}</code> = 줄마다 그 사람 이름</div>
</div>
{#- 리스트 추가 — 붙여 넣기 → [미리보기](메일/DM/오류 판별) → [리스트에 추가] -#}
<div class="erp-card otr-add" id="otr-add" hidden>
<div class="otr-add-head"><b>리스트 추가</b>
<span class="erp-muted">한 줄에 한 사람 — <code>주소, 이름</code> (쉼표·탭·띄어쓰기). 주소 = 이메일(<code>name@domain.com</code>) 또는
인스타(<code>@계정</code> · <code>instagram.com/계정</code> · 계정명). 엑셀에서 두 칸을 복사해 붙여도 됩니다.</span></div>
<textarea class="erp-input otr-add-text" id="otr-add-text" rows="6" placeholder="kim@miras.co.kr, 김철수&#10;@mira.kitchen 미라네&#10;https://www.instagram.com/lee_s/ 이수진"></textarea>
<div class="otr-add-actions">
<button type="button" class="erp-btn erp-btn-outline" id="otr-add-preview">미리보기</button>
<button type="button" class="erp-btn erp-btn-primary" id="otr-add-save" disabled>리스트에 추가</button>
<button type="button" class="erp-btn erp-btn-outline" id="otr-add-close">닫기</button>
<span class="erp-muted" id="otr-add-sum"></span>
</div>
<div class="erp-table-wrap otr-add-preview" id="otr-add-result" hidden></div>
</div>
<div class="erp-card otr-list">
<div class="otr-filter" role="tablist" aria-label="보기">
{% for key, label in (('all', '전체'), ('email', '메일'), ('instagram', 'DM'), ('대기', '대기'), ('보냄', '보냄'), ('실패', '실패')) %}
<button type="button" class="otr-seg{% if key == 'all' %} is-active{% endif %}" data-filter="{{ key }}">{{ label }} <span class="otr-cnt" data-cnt="{{ key }}"></span></button>
{% endfor %}
</div>
<div class="erp-table-wrap">
<table class="erp-table otr-table">
<thead><tr><th class="otr-c-check"><input type="checkbox" id="otr-check-all" aria-label="전체 고르기" /></th>
<th>구분</th><th>이름</th><th>주소</th><th>상태</th><th>보낸 때</th><th class="otr-c-acts"></th></tr></thead>
<tbody id="otr-tbody"></tbody>
</table>
</div>
<p class="erp-muted otr-empty" id="otr-empty" hidden>리스트가 비었습니다 — [+ 리스트 추가]로 넣으세요.</p>
<div class="otr-send-bar">
<span id="otr-selected">고른 줄 0</span>
<button type="button" class="erp-btn erp-btn-primary" id="otr-send"{% if not gmail.connected %} disabled title="Gmail 연결 뒤 보낼 수 있습니다"{% endif %}>고른 메일 보내기</button>
<button type="button" class="erp-btn erp-btn-outline" id="otr-reset">고른 줄 다시 대기로</button>
<button type="button" class="erp-btn erp-btn-outline otr-danger" id="otr-delete">고른 줄 지우기</button>
<span class="erp-muted otr-send-note">메일 = 한 사람에 한 통(본인 Gmail, 1초 간격). DM = 줄의 [DM 보내기] → 문구가 복사되고 인스타 DM 창이 열리면 붙여 넣어 보낸 뒤 [보냄].</span>
</div>
</div>
{% if logs %}
<div class="erp-card otr-logs">
<div class="otr-tpl-head"><b>최근 보낸 기록</b><span class="erp-muted">({{ logs | length }})</span></div>
<ul>
{% for l in logs %}
<li class="{{ 'is-ok' if l.ok else 'is-fail' }}"><span class="otr-when">{{ l.sent_at[5:16] | replace('T', ' ') }}</span>
<b>{{ '메일' if l.kind == 'email' else 'DM' }}</b> {{ l.name or '(이름 없음)' }} · {{ l.address }}
<span class="erp-muted">— {{ l.sent_by }}{% if not l.ok %} · <span class="otr-err">{{ l.error }}</span>{% endif %}</span></li>
{% endfor %}
</ul>
</div>
{% endif %}
</section>
{#- 미리보기 창 -#}
<div class="otr-modal" id="otr-preview" hidden>
<div class="otr-modal-card" role="dialog" aria-modal="true" aria-label="미리보기">
<div class="otr-modal-head"><b id="otr-pv-title">미리보기</b><button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-close>닫기</button></div>
<div class="otr-pv-subject" id="otr-pv-subject"></div>
<iframe class="otr-pv-frame" id="otr-pv-frame" title="본문 미리보기" sandbox></iframe>
</div>
</div>
<script type="application/json" id="otr-data">{{ {"rows": rows} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
@@ -0,0 +1,93 @@
{% extends "erp_base.html" %}
{#- 안내문 발송 설정(2026-10-27) — 화면 세로 2단: 왼쪽 = 메일(제목·(광고)·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
오른쪽 = 인스타 DM(서식 없는 편집기, 비우면 메일 본문 글 + 끝 문구). 두 편집기 모두 {이름} = 빨강 굵게(화면에서만).
편집기 = Quill(/static/vendor/quill). 입력 칸은 form="otr-set-form" 으로 위 막대의 저장 폼에 묶는다(사진 폼과 겹치지 않게). -#}
{% block head_extra %}
<link rel="stylesheet" href="/static/vendor/quill/quill.snow.css" />
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />
{% endblock %}
{% block content %}
<section class="otr otr-settings">
<form method="post" action="/outreach/settings" id="otr-set-form" class="otr-set-bar">
<a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a>
<span class="erp-muted otr-set-saved">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span>
<span class="otr-set-bar-gap"></span>
<input type="hidden" name="fmt" value="html" />
<input type="hidden" name="body" id="otr-body-input" />
<input type="hidden" name="dm_body" id="otr-dm-input" />
<button type="button" class="erp-btn erp-btn-outline" id="otr-default" title="칸만 바꿉니다 — [저장]을 눌러야 적용">기본 문구로 되돌리기</button>
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
</form>
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
<div class="otr-split">
{#- 왼쪽 — 메일 -#}
<div class="otr-col">
<div class="erp-card otr-set-card">
<div class="otr-col-head"><span class="otr-kind is-email">메일</span><b>이메일 안내문</b>
<span class="erp-muted">[고른 메일 보내기]로 내 Gmail 에서 한 사람에 한 통씩</span></div>
<label class="erp-field otr-field"><span>메일 제목</span>
<input class="erp-input" type="text" name="subject" form="otr-set-form" maxlength="200" required value="{{ template.subject }}" /></label>
<label class="otr-check"><input type="checkbox" name="ad_label" form="otr-set-form" value="1"{% if template.ad_label %} checked{% endif %} />
<span>제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></span></label>
<label class="erp-field otr-field"><span>보내는 이름</span>
<input class="erp-input" type="text" name="sender_name" form="otr-set-form" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
<div class="erp-field otr-field"><span>본문 <small class="erp-muted"><code class="otr-tag">{이름}</code> = 그 사람 이름(빨강은 이 화면에서만 — 메일에는 이름이 본문 서식대로) · 되돌리기 Ctrl+Z</small></span>
<div class="otr-editor" id="otr-body-editor"></div></div>
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
<textarea class="erp-input" name="footer" form="otr-set-form" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
</div>
<div class="erp-card otr-set-card" id="images">
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
<div class="otr-images">
{% for im in images %}
<figure class="otr-image">
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
<div class="otr-image-acts">
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
</div>
</figure>
{% else %}
<p class="erp-muted">사진이 없습니다.</p>
{% endfor %}
</div>
{% if images | length < max_images %}
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
</form>
{% endif %}
</div>
</div>
{#- 오른쪽 — 인스타 DM -#}
<div class="otr-col">
<div class="erp-card otr-set-card otr-dm-card">
<div class="otr-col-head"><span class="otr-kind is-instagram">DM</span><b>인스타 DM 문구</b>
<span class="erp-muted">[DM 보내기]를 누르면 복사되는 글</span></div>
<p class="erp-muted otr-note">인스타 DM 은 글자 서식·사진이 없어 글만 씁니다. <code class="otr-tag">{이름}</code> = 그 사람 이름.
비워 두면 메일 본문 글 + 끝 문구가 그대로 복사됩니다.</p>
<div class="otr-editor otr-editor-plain" id="otr-dm-editor"
data-placeholder="예: 안녕하세요, {이름}님! 누적 800만 개 판매 미라클통 '미라네주방'입니다. {이름}님과 공동구매를 함께하고 싶어 연락드렸어요. 자세한 제안서는 메일로 보내드릴 수 있습니다 — 편하신 메일 주소 알려주시면 감사하겠습니다 :)"></div>
<div class="otr-dm-foot">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="otr-dm-from-mail">메일 본문 글 가져오기</button>
<small class="erp-muted otr-count" id="otr-dm-count" data-max="{{ dm_max }}"></small>
</div>
</div>
</div>
</div>
</section>
<script type="application/json" id="otr-default-data">{{ default | tojson }}</script>
<script type="application/json" id="otr-current-data">{{ {"body": template.body, "dm_body": template.dm_body} | tojson }}</script>
{% endblock %}
{% block scripts %}
<script src="/static/vendor/quill/quill.js"></script>
<script src="/static/outreach.js?v=20261030c" defer></script>
{% endblock %}
+87 -8
View File
@@ -20,34 +20,113 @@
- 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 — 배포 뒤 대조.
## 매출 업데이트
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
- **업데이트 중에도 [매출 업데이트] 누르기 가능**(2026-10-19) — 버튼이 "업데이트 중 · 진행 보기"로 바뀌고, 누르면 `GET /api/sync/current` 의 진행 중 작업(수동·자동)을 새로 시작하지 않고 진행 창으로 다시 연다.
- 서버 시작 때 남은 `perf_sync_runs` running 행은 `abandon_running_runs` 로 "중단됨(서버 재시작)" 정리(앱은 프로세스 하나 — 진행 작업은 메모리에만). 예전엔 30분(`STALE_RUN_AFTER`) 동안 버튼이 '업데이트 중'으로 막히고 그 쇼핑몰이 '이미 진행 중'으로 건너뛰어졌다.
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`(끄기)·`_DAYS`·`_HOURS`(일정 저장 전 기본 시간대).
- **일정 = 실적 설정 "자동 업데이트" 카드**(2026-10-26, 관리자, 마이그레이션 011 `perf_settings` key `auto_sync`) — 매출 실적·광고비 **따로**:
사용·요일(0=월…6=일, [매일]·[평일])·시작/끝 시각(5분 단위)·간격(5~720분, 5분 단위, 기본 30). 회차 = 고른 요일의 시작, 시작+간격, … 끝까지(끝과 맞으면 끝도).
`PUT /api/auto-sync-schedule {sales, ads}`(`auto_sync.validate_schedule`, 011 미적용 503). 스레드(`auto_sync.Scheduler`)가 1분마다 일정을 다시 읽어
바뀐 종류만 지금부터 다시 계산, 종류마다 따로 스레드(`run_once(kinds=(kind,))`). 저장 값 없음·011 미적용 = 기본(매일 9~19시 30분마다).
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(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`) — 매출·광고비 공통, 연간 보기 "연간 합계"는 그대로 맨 아래.
- **기간 빠른 선택 = 이번달·올해·직접선택**(2026-10-26 — 오늘·이번주 버튼 삭제, `dashboard.build_dashboard`·`ad_spend.build_ad_dashboard` 의 `nav.quick`),
매출 실적 기본 기간도 **이번달**(`router.dashboard_page` `period="month"`, 광고비는 원래 이번달). day·week 주소(`?period=week`)는 그대로 열린다.
- **일자별 표 스크롤 고정**(2026-10-26, **10-27 다시** `.perf-main-wrap`) — 페이지(`.erp-page`)를 스크롤해도 제목 행 + 맨 위 기간 합계 행
(`tbody tr.perf-row-total:first-child`)이 화면 위에 붙어 있다. 표 상자는 가로 스크롤 상자라 CSS sticky 가 페이지 스크롤에 안 먹어서
`performance.js stickyHead` 가 스크롤(capture)·창 크기·표 크기마다 두 줄 칸을 `translateY` 로 내린다(표 끝에서 멈춤, 내려온 동안 `is-stuck` →
제목 칸 `::after` 가 아래 1px 선 — 표 칸 선(border-collapse)은 안 움직여 틈이 비쳤다). **표 상자 세로 스크롤 금지** — 10-26 판은 상자를 화면 높이로
묶어 상자 안에서 스크롤했는데, 진짜 셸에서는 상자 아래가 화면 밖에 잘리고(`overscroll-behavior: contain`) 휠이 페이지로 안 넘어갔다.
스크롤 막대 배경(트랙) 투명 = `scrollbar-color: #c3c6cb transparent`(표 상자·실적 화면 `.erp-page`). 테스트 `tests/js/perf_sticky.browser.test.js`
(진짜 `erp_base.html` 셸 렌더 `perf_*_shell.html` 로 휠 스크롤 — 스텁 셸로는 이 문제가 안 보였다).
- **새로고침해도 스크롤 유지**(2026-11-02) — 수기 입력을 마치면 합계를 다시 계산하려고 새로고침하는데, 세로 스크롤은 `.erp-page` 상자라 브라우저가 복원하지 않아 맨 위로 돌아갔다.
`performance.js keepScroll` 이 떠날 때 세로·가로 위치를 sessionStorage `perf_scroll` 에 저장 → **새로고침일 때만** 복원(같은 주소, 메뉴·기간 이동은 맨 위부터). 자동 새로 고침·업로드 뒤 새로고침도 같음.
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
- **직접 추가 쇼핑몰·그룹·순서 드래그**(2026-10-22, 마이그레이션 009 `is_custom`·`is_group`·`parent_code`) — 설정 [+ 쇼핑몰 추가(수동 입력)]
(코드 `custom_…`, `get_adapter` 가 `CustomManualAdapter` = 수동 입력 전용)·[+ 그룹 추가](`group_…`, 매출 없음·`include_in_sales` 꺼짐),
직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함),
▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces`
(그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
- **카페24(전체)·카페24(실적) 열**(2026-11-02, 예전 "공구 제외") — 카페24 열 이름 = 카페24(전체)(`_short_name`), 바로 오른쪽 카페24(실적) = 카페24 − 직접 추가 쇼핑몰 "자사몰(공동구매)"("카페24 공동구매"도, 이름으로 찾음·띄어쓰기 무시 — 없으면 전체 그대로, 쇼핑몰 필터·숨김과 무관하게 뺌).
광고비 줄은 카페24(전체)와 같은 구글·메타(`dashboard._cafe24_real_column`, kind `diff`, 표 열만 — 일 합계엔 안 더함, 클릭·메모 없음). 공동구매 칸을 저장하면 그 줄 칸이 바로 바뀜(`performance.js saveManual`, td `data-diff-minus`·`data-base`), 합계 줄은 입력 마친 뒤 새로고침 때. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
- **합계 기준**(2026-11-02) — 일 합계 = 카페24(실적) + 공동구매 + 나머지 쇼핑몰(카페24(전체)는 안 더함 — 공동구매가 들어 있어 중복). 일 합계·ROAS·KPI·추이·비중·월/연 누적 모두 `dashboard._summary_cells`(카페24 칸 = 실적, 그래프·누적의 카페24 줄 이름도 `summary_names` = 카페24(실적)), 표의 카페24(전체) 열만 원래 값. 광고비 탭 매출 대비 광고비·합계 ROAS = `total_sales_codes`(카페24 있으면 공동구매 코드 뺌, 같은 금액). **프로젝트 회의록 머리 카드는 아직 예전 합계**(`project/router.py` `total` — 공동구매 중복).
- **매출 실적 표 열 숨기기**(2026-11-02) — 실적 설정 "공통 보기 설정" 카드(관리자만, `PUT /api/hidden-marketplaces`, `perf_settings` key `hidden_marketplaces`, 011 미적용 503) → **모든 사용자에게 적용**. **열만** 숨김(`dashboard.load_hidden`) — 일 합계·KPI·그래프·누적은 그대로, 그룹 열 = 보이는 하위 합계(다 숨기면 그룹 열도 없음). 쇼핑몰 필터(합계까지 바뀜)와 다름. 광고비 탭은 적용 안 함.
- **일 합계 열 위치**(2026-11-02) — 매출 실적·광고비 표 모두 날짜 바로 오른쪽, 날짜 열과 함께 가로 고정(왼쪽 위치 `--perf-label-w` = 날짜 열 너비, `performance.js stickyHead`).
- **기간 이동**(2026-11-02, `_period_nav.html` 공통) — 날짜 바로 좌우 화살표 SVG(글자 높이, 진한 회색), 글자 버튼 없음.
- **매출 실적 표 모양(2026-10-22)** — `table.perf-autofit`(매출 탭만, 모든 기간 같음): 표가 100% 로 늘지 않고 **열 너비 = 내용 길이**, 날짜 열은 고정 210px 대신 자동 +
**가로 스크롤해도 고정**(sticky left, 오른쪽 그림자). 그룹 열 = 진한 보라 머리·왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠)·옅은 칸, 마지막 하위(`is-glast`, 접히면 그룹 열 `is-gclosed`) = 오른쪽 선.
접기 단추 = 22px ⊟/⊞(SVG, 세로 막대가 돌아 바뀜). 접기·펴기 애니메이션 = 하위 칸 내용 `.perf-gc` 너비·칸 여백·투명도 260ms(`setGroup(code, fold, animate)`,
끝나면 `is-gfolded` display:none, 빠르게 연속 클릭은 `groupRun` 번호로 마지막만, 움직임 줄이기면 바로).
## 매출 실적 화면 (2026-10-19)
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음.
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
화면 데이터 `update_watch`(`router._update_watch` = 그린 때 마지막으로 끝난 작업 id, 보는 사람 것 제외) ↔ `GET /api/update-status?kind=sales|ads`
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`.
- 일자별 표 매출 칸 아래 **광고비(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` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`).
수동 = 매출 실적·광고비 일자별 표에 `perf-colw-manual` → `performance.js initColWidths` 가 자동 너비를 잰 뒤 `table-layout:fixed`(`is-colw-fixed`, 넘치는 글자 …),
머리글 오른쪽 경계 `.perf-colw-grip` 드래그(최소 36px)·두 번 누르면 그 열만 자동. **날짜 열(`label`)은 조절 불가 — 늘 자동 너비, 손잡이 없음, 저장값 무시**. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지,
설정 [조절한 너비 초기화]가 둘 다 지움. 그룹 접기·펴기 때 열 너비도 함께 움직임(`colw.animate/settle`). 테스트 `tests/js/perf_colw.browser.test.js`.
- **매출 단위** 원·천원·백만원(2026-11-02 모든 사용자 공통) — 설정 "공통 보기 설정"(관리자, `PUT /api/display-unit`, `perf_settings` key `display_unit`, 저장 값 없음·011 미적용 = 원, 예전 쿠키 `perf_unit` 은 안 봄), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. 표 열 너비는 사람(브라우저)마다 그대로.
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`)
- 매출 실적·광고비 일자별 표의 **쇼핑몰(광고 채널) 날짜 칸 전부**(`td[data-memo-code]` — 매출 탭은 수동 입력 칸 + API 쇼핑몰 칸, 같은 날 넓힘; 그룹 열·주간합계·합계 줄은 아님)
우클릭 → [메모 삽입] / [메모 수정]·[메모 삭제](`.perf-ctx` 메뉴, 창에서 입력, Ctrl+Enter 저장). 왼쪽 클릭은 그대로(입력 칸 = 금액 입력, API 칸 = 주문 내역).
`PUT /performance/api/cell-memos/{kind}/{코드}/{날짜}` (kind = `sales` 쇼핑몰 / `ad` 광고 채널, 빈 메모 = 지움, 1,000자), 모듈 권한자 누구나.
- 메모 있는 칸 = 오른쪽 위 빨간 삼각형(`has-memo`, 엑셀 메모처럼), 마우스 올리면 노란 메모 상자(`.perf-memo-tip`). 금액과 따로 저장(금액 지워도 남음).
화면 데이터 `memo_cells`("날짜|코드" → 메모, `db.cell_memos`), 010 미적용이면 표시 없음·저장만 503. 표를 스크롤하면 열린 메뉴는 닫힌다.
- 테스트 `test_cell_memos.py`, `tests/js/perf_memo_ads.browser.test.js`.
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
- 쿠팡: 1열 날짜·19열 청구금액(+부가가치세).
- 네이버: 3열 기간·4열 총비용·12열 ROAS, 머리글 클릭 = 일자별 보고서 항목.
- 매출 대비 광고비 KPI.
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께. 결과는 `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 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [메타 광고 불러오기]·자동 업데이트 회차.
- 네이버: 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 는 **한 줄**(2026-10-30, 매출 실적처럼 `.perf-kpi-line` — 항목 `.perf-kpi-item` 을 세로 선으로 나눔, 좁은 화면은 한 항목씩): 광고비(전 기간 대비) · 매출 대비 광고비 · 연 누적 광고비. 월 누적 광고비 카드는 뺐다.
- 광고 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 으로 주는 문제**(2026-10-21 운영 확인, v26.0 — 링크 클릭·구매는 정상, 하루만 물으면 정상) →
"지출·노출 0 인데 링크 클릭·구매가 있는" 날만 하루씩 다시 물어 바꾼다(`meta_ads._refetch_suspect_days`). 원본 진단: `scripts/meta_insights_raw.py`
(`docker exec -i dbx-main python - 시작일 [종료일] < scripts/meta_insights_raw.py`, 읽기 전용).
@@ -19,6 +19,10 @@
부가세를 더하는(× 1.1) 것은 비용이 부가세 별도인 구글만이다.
- ROAS(%) = 구매 전환값 ÷ 지출 금액 × 100 — 광고 관리자 "구매 ROAS" 와 같은 값, 지출 0 이면 없음.
- 나머지 항목(노출수·클릭수·클릭률·링크 클릭·구매수·구매 전환값)은 광고비 탭 메타 머리글 → 일자별 표.
- **기간으로 물으면 지출·노출·클릭이 0 으로 오는 메타 응답(2026-10-21 운영 확인, v26.0)** — 10/01~10/21 을 한 번에 물으면 날마다
spend='0'·impressions='0'·clicks='0' 인데 링크 클릭·구매는 들어오고, 같은 날을 하루만 물으면 정상(10/20 지출 817,212원). 그래서 기간 응답에서
"지출·노출 0 인데 링크 클릭·구매가 있는" 날(실제로는 있을 수 없는 조합)은 그날 하루만 다시 물어 그 값으로 바꾼다(_refetch_suspect_days).
집행이 없는 계정·날은 행이 없거나 다 0 이라 다시 묻지 않는다. 진단: scripts/meta_insights_raw.py.
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 메타는 버전을 약 2년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
"""
@@ -291,6 +295,20 @@ class MetaAdsSource(AdSource):
msg += f" (원화가 아닌 계정은 날마다 그날 환율로 원화로 바꿔 넣습니다 — {fx.SOURCE_LABEL})"
return msg
def _refetch_suspect_days(self, ctx: AdapterContext, client: httpx.Client, version: str, params: dict[str, Any],
raw: list[tuple[str, date, str, dict[str, Any]]]) -> list[tuple[str, date, str, dict[str, Any]]]:
"""_suspect 줄은 그 계정·그날 하루만 다시 물어 바꾼다(하루 조회는 지출·노출·클릭이 정상). 하루 조회도 같으면 그대로 둔다."""
out = []
for acc, day, cur, r in raw:
if _suspect(r):
one = {**params, "time_range": json.dumps({"since": day.isoformat(), "until": day.isoformat()})}
rows = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}/insights", one).get("data") or []
fresh = next((x for x in rows if str(x.get("date_start")) == day.isoformat()), None)
if fresh is not None:
r, cur = fresh, str(fresh.get("account_currency") or cur).upper()
out.append((acc, day, cur, r))
return out
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
@@ -323,6 +341,7 @@ class MetaAdsSource(AdSource):
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
else:
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
raw = self._refetch_suspect_days(ctx, client, version, params, raw)
# 원화가 아닌 계정(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"}):
@@ -358,6 +377,12 @@ class MetaAdsSource(AdSource):
return out
def _suspect(r: dict[str, Any]) -> bool:
"""기간 응답에서 지출·노출이 0 인데 링크 클릭·구매가 있는 줄 — 메타 기간 조회가 핵심 칸을 0 으로 준 경우(2026-10-21)."""
return (_num(r.get("spend")) == 0 and _num(r.get("impressions")) == 0
and (_num(r.get("inline_link_clicks")) > 0 or _purchase(r.get("actions")) > 0))
def _zero() -> dict[str, Decimal]:
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
+85 -20
View File
@@ -45,6 +45,7 @@ CHANNELS: tuple[tuple[str, str], ...] = (
("lotteon", "롯데ON"),
("toss", "토스"),
("atomy", "애터미아자몰"),
("etc", "기타광고비"), # 2026-10-22 — 쇼핑몰에 딸리지 않은 광고비(직접 입력), ROAS 없음
)
CHANNEL_NAMES = dict(CHANNELS)
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
@@ -53,7 +54,8 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# 여러 날(주·월·합계)의 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}
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
@@ -189,8 +191,6 @@ def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") ->
res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀
elif abs(amt) > MAX_AMOUNT:
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
elif day > today:
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
else:
sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다
if len(sums) > MAX_DATA_ROWS:
@@ -228,11 +228,50 @@ def _json_num(num: Decimal | None) -> Any:
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(12열) + 나머지 항목. 잘못된 줄이 있으면 errors."""
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 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
@@ -245,6 +284,7 @@ def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResu
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
@@ -254,28 +294,24 @@ def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResu
res.skipped += 1
continue
try:
amt = parse_amount(row[NAVER_AMOUNT_COL] if len(row) > NAVER_AMOUNT_COL else None)
amt = parse_amount(row[amount_col] if len(row) > amount_col else None)
except ValueError:
res.errors.append(f"{r}행 4열: 총비용이 숫자가 아닙니다.")
res.errors.append(f"{r}행 {amount_col + 1}열: 총비용이 숫자가 아닙니다.")
continue
try:
ro = _number(row[NAVER_ROAS_COL] if len(row) > NAVER_ROAS_COL else None)
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}행 12열: 광고수익률(ROAS)이 숫자가 아닙니다.")
res.errors.append(f"{r}행 {(roas_col or 0) + 1}열: 광고수익률(ROAS)이 숫자가 아닙니다.")
continue
if amt is None:
res.errors.append(f"{r}행 4열: {day.isoformat()} 총비용이 비어 있습니다.")
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 > today:
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
elif day in seen:
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
else:
seen[day] = r
res.entries.append((day, amt))
if ro is not None:
res.roas[day] = ro
m: dict[str, Any] = {}
for i, v in enumerate(row):
name = header[i] if i < len(header) else f"{i + 1}열"
@@ -286,6 +322,10 @@ def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResu
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:
@@ -378,7 +418,30 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
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]
return {"columns": cols, "rows": out_rows, "total": total}
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]:
@@ -444,8 +507,6 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
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)
@@ -471,8 +532,6 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"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},
]
@@ -490,9 +549,8 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
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)
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 매출 실적과 같게)
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},
]}
@@ -538,6 +596,13 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
# 광고 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,
# 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
(store.cell_memos("ad", period.start, period.end) if hasattr(store, "cell_memos") else {}).items()},
}
+68 -11
View File
@@ -1,6 +1,7 @@
"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
- 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다.
- 광고비 탭 [광고비 업데이트](보고 있는 기간, 진행 창 — jobs kind="ads", 2026-10-20) · 매출 자동 업데이트와 같은 회차
(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다. 진행 창에서 채널별 [중지]·[업데이트 취소] = 저장 직전까지 받아들임.
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
@@ -14,7 +15,7 @@ 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
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError, Cancelled
from .credentials import CredentialService
from .db import AdCredentialTable
from .security.redact import redact_text
@@ -84,8 +85,9 @@ class AdSyncService:
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 = "") -> dict[str, Any]:
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy."""
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)
@@ -96,7 +98,14 @@ class AdSyncService:
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")
@@ -110,17 +119,65 @@ class AdSyncService:
finally:
lock.release()
def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]:
"""설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다."""
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, ok in self.configured().items():
if not ok:
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:
out.append(self.sync(code, start, end, user=user))
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:
out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)})
res = {"ok": False, "code": code, "skipped": True, "message": str(exc)}
except Exception as exc: # noqa: BLE001 — 다음 채널은 계속
logger.exception("ad sync failed: %s", code)
out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"})
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
+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]:
@@ -23,3 +23,10 @@ class CoupangRocketAdapter(ManualOnlyAdapter):
class AtomyAzmallAdapter(ManualOnlyAdapter):
code = "atomy"
name = "애터미아자몰"
class CustomManualAdapter(ManualOnlyAdapter):
"""실적 설정에서 사용자가 직접 추가한 쇼핑몰(마이그레이션 009, 코드 custom_…) — 이름은 DB(perf_marketplaces.name)."""
def __init__(self, code: str) -> None:
self.code = code
+103 -12
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.
판매분석의 환불금액처럼 결제일이 아니라 환불일 매출에서 빠진다.
- 구매자 이름·연락처·주소는 저장하지 않는다.
"""
@@ -173,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 {}
@@ -183,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 "")
@@ -201,6 +208,61 @@ 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")
@@ -335,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):
@@ -352,8 +415,9 @@ class NaverAdapter(MarketplaceAdapter):
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)
@@ -363,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")
@@ -372,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],
)]
@@ -420,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 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, "
"미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}
+10 -2
View File
@@ -14,7 +14,7 @@ from .gmarket import GmarketAdapter
from .gsshop import GsshopAdapter
from .kakao import KakaoAdapter
from .lotteon import LotteonAdapter
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter, CustomManualAdapter
from .naver import NaverAdapter
from .ohouse import OhouseAdapter
from .toss import TossAdapter
@@ -36,10 +36,18 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
)
_BY_CODE = {a.code: a for a in _ADAPTERS}
# 실적 설정에서 직접 추가한 행(마이그레이션 009) — 쇼핑몰은 수동 입력 전용 어댑터, 그룹은 어댑터 없음(매출 없음)
CUSTOM_PREFIX = "custom_"
GROUP_PREFIX = "group_"
def all_adapters() -> tuple[MarketplaceAdapter, ...]:
return _ADAPTERS
def get_adapter(code: str) -> MarketplaceAdapter | None:
return _BY_CODE.get(code)
"""코드 → 어댑터. 직접 추가 쇼핑몰(custom_…)은 수동 입력 전용 어댑터, 그룹·모르는 코드는 None."""
adapter = _BY_CODE.get(code)
if adapter is None and code.startswith(CUSTOM_PREFIX):
return CustomManualAdapter(code)
return adapter
+236 -63
View File
@@ -1,16 +1,20 @@
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
"""매출·광고비 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
일정(2026-10-26) — 실적 설정 "자동 업데이트" 카드에서 매출 실적·광고비를 **따로** 정한다(마이그레이션 011 perf_settings,
key 'auto_sync'). 종류마다 {enabled, interval(분, 5분 단위, 기본 30), days(0=월 … 6=일), start "HH:MM", end "HH:MM"}.
- 회차 = 고른 요일의 start, start+interval, … end 까지(end 와 딱 맞으면 end 도). 시각은 5분 단위, KST.
- 저장한 일정은 1분 안에 반영(스레드가 1분마다 다시 읽는다). 저장 값이 없으면(011 미적용 포함) 기본 일정 =
매일 env PERFORMANCE_AUTO_SYNC_HOURS(기본 9-19)시 정각 ~ 마지막 시 정각, 30분마다.
- 매출 = 진행 창 작업(jobs kind="sales") — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
- 광고비 = 설정된 광고 API(구글·메타) — 광고비 진행 창 작업(jobs kind="ads"). 광고비 탭 [광고비 업데이트]도 같은 진행 상황.
- 두 종류의 회차가 같은 시각이면 동시에 돈다(따로 스레드). 그 시각에 이미 같은 종류 업데이트가 돌고 있으면 그 종류는 그 회차를
건너뛴다. 한 회차가 간격을 넘기면 지나간 회차는 건너뛰고 다음 회차를 기다린다(밀린 회차를 몰아서 돌리지 않음).
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
환경변수(.env)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐) — 끄면 설정 화면 일정과 상관없이 안 돈다
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
PERFORMANCE_AUTO_SYNC_HOURS=9-19 설정 화면에서 일정을 저장하기 전 기본 시간대(시작시-마지막시)
"""
from __future__ import annotations
@@ -30,7 +34,13 @@ logger = logging.getLogger("performance.auto_sync")
AUTO_USER = "자동 업데이트"
DEFAULT_DAYS = 10
DEFAULT_HOURS = (9, 19)
SLOT_MINUTES = 30
DEFAULT_INTERVAL = 30
INTERVAL_STEP = 5
INTERVAL_MAX = 720
SETTING_KEY = "auto_sync"
KINDS = ("sales", "ads")
KIND_NAMES = {"sales": "매출 실적", "ads": "광고비"}
WEEKDAYS = ("월", "화", "수", "목", "금", "토", "일")
_started = False
_start_lock = threading.Lock()
@@ -61,90 +71,253 @@ def hour_window() -> tuple[int, int]:
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:
# ════════════════════════════════════════════════════════════
# 일정
# ════════════════════════════════════════════════════════════
def default_schedule() -> dict[str, Any]:
first, last = hour_window()
return {"enabled": True, "interval": DEFAULT_INTERVAL, "days": list(range(7)),
"start": f"{first:02d}:00", "end": f"{last:02d}:00"}
def _minutes(hhmm: str) -> int:
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def _time(raw: Any, label: str) -> str:
m = re.fullmatch(r"(\d{1,2}):(\d{2})", str(raw or "").strip())
if not m or not (0 <= int(m.group(1)) <= 23 and 0 <= int(m.group(2)) <= 59):
raise ValueError(f"{label}을 HH:MM 으로 넣어 주세요.")
if int(m.group(2)) % INTERVAL_STEP:
raise ValueError(f"{label}은 {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
return f"{int(m.group(1)):02d}:{m.group(2)}"
def validate_schedule(raw: Any) -> dict[str, Any]:
"""설정 화면에서 받은 일정 하나 → 정리한 값. 잘못되면 ValueError(화면에 그대로 보여 줄 문구)."""
if not isinstance(raw, dict):
raise ValueError("일정 형식이 잘못되었습니다.")
on = bool(raw.get("enabled"))
try:
interval = int(raw.get("interval"))
except (TypeError, ValueError):
raise ValueError("간격(분)을 숫자로 넣어 주세요.") from None
if not (INTERVAL_STEP <= interval <= INTERVAL_MAX) or interval % INTERVAL_STEP:
raise ValueError(f"간격은 {INTERVAL_STEP}분 ~ {INTERVAL_MAX}분, {INTERVAL_STEP}분 단위로 정할 수 있습니다.")
days = raw.get("days")
if not isinstance(days, list) or any(not isinstance(d, int) or isinstance(d, bool) or not 0 <= d <= 6 for d in days):
raise ValueError("요일이 잘못되었습니다.")
days = sorted(set(days))
if on and not days:
raise ValueError("요일을 하나 이상 고르세요(자동 업데이트를 쓰지 않으려면 [사용]을 끄세요).")
start, end = _time(raw.get("start"), "시작 시각"), _time(raw.get("end"), "끝 시각")
if _minutes(end) < _minutes(start):
raise ValueError("끝 시각은 시작 시각과 같거나 뒤여야 합니다(밤을 넘기는 시간대는 안 됩니다).")
return {"enabled": on, "interval": interval, "days": days, "start": start, "end": end}
def normalize(raw: Any) -> dict[str, dict[str, Any]]:
"""DB 에 저장된 값 → 종류마다 일정. 없거나 잘못된 종류는 기본 일정."""
out = {}
for k in KINDS:
try:
out[k] = validate_schedule((raw or {}).get(k)) if isinstance(raw, dict) else default_schedule()
except ValueError:
out[k] = default_schedule()
return out
def load_schedules(store: Any) -> tuple[dict[str, dict[str, Any]], bool]:
"""(종류 → 일정, 011 적용 여부). DB 오류는 그대로 올린다(스레드는 직전 일정을 계속 쓴다)."""
from .db import SettingsMigrationNeeded # noqa: WPS433
getter = getattr(store, "get_setting", None)
if getter is None: # 테스트용 가짜 저장소 등
return normalize(None), True
try:
return normalize(getter(SETTING_KEY)), True
except SettingsMigrationNeeded:
return normalize(None), False
def describe(sched: dict[str, Any]) -> str:
"""'매일 09:00~19:00 · 30분마다' / '평일 …' / '월·수·금 …' / '꺼짐'."""
if not sched.get("enabled") or not sched.get("days"):
return "꺼짐"
days = sched["days"]
if days == list(range(7)):
when = "매일"
elif days == list(range(5)):
when = "평일"
elif days == [5, 6]:
when = "주말"
else:
when = "·".join(WEEKDAYS[d] for d in days)
span = sched["start"] if sched["start"] == sched["end"] else f"{sched['start']}~{sched['end']}"
every = sched["interval"]
every_txt = f"{every // 60}시간" + (f" {every % 60}분" if every % 60 else "") if every >= 60 else f"{every}분"
return f"{when} {span}" + ("" if sched["start"] == sched["end"] else f" · {every_txt}마다")
def is_slot(t: datetime, sched: dict[str, Any]) -> bool:
"""t(분 단위로 자른 KST 시각)가 회차인가."""
if not sched.get("enabled") or t.weekday() not in sched["days"]:
return False
return first <= t.hour < last or (t.hour == last and t.minute == 0)
m, start, end = t.hour * 60 + t.minute, _minutes(sched["start"]), _minutes(sched["end"])
return start <= m <= end and (m - start) % sched["interval"] == 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 next_slot(after: datetime, sched: dict[str, Any]) -> datetime | None:
"""after 보다 뒤의 첫 회차 시각(KST). 꺼져 있거나 요일이 없으면 None."""
if not sched.get("enabled") or not sched.get("days"):
return None
start, end, step = _minutes(sched["start"]), _minutes(sched["end"]), sched["interval"]
day0 = after.replace(hour=0, minute=0, second=0, microsecond=0)
for d in range(8):
base = day0 + timedelta(days=d)
if base.weekday() not in sched["days"]:
continue
first = base + timedelta(minutes=start)
k = 0 if first > after else int((after - first).total_seconds() // (step * 60)) + 1
m = start + k * step
if m <= end:
return base + timedelta(minutes=m)
return None
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
# ════════════════════════════════════════════════════════════
# 회차 실행
# ════════════════════════════════════════════════════════════
def run_once(store: Any, app_state: Any, *, today: Any, days: int,
kinds: tuple[str, ...] = KINDS) -> dict[str, Any]:
"""한 회차 — 오늘 포함 최근 days 일. kinds 의 매출(진행 창 작업)·광고비(광고 진행 창 작업)를 동시에.
각각 이미 돌고 있으면 그 종류만 건너뜀."""
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
if jobs.running_job() is not None:
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
start, end = today - timedelta(days=days - 1), today
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
ads: list[dict[str, Any]] = []
ad_thread = None
ads_skipped = "ads" not in kinds or 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 = "sales" not in kinds or jobs.running_job("sales") is not None
error = ""
results: list[dict[str, Any]] = []
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)
# 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15)
ads: list[dict[str, Any]] = []
try:
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER)
except Exception: # noqa: BLE001 — 스레드가 죽지 않게
logger.exception("auto ad sync failed")
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, "from": start.isoformat(), "to": end.isoformat(), "ok": 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]}
class Scheduler:
"""종류마다 다음 회차(due)를 들고 있다가 시각이 되면 그 종류만 따로 스레드로 돌린다.
tick(now) 이 1분마다 불리며 일정이 바뀐 종류는 지금부터 다시 계산(서버 시작·저장 직후 회차는 안 돌림)."""
def __init__(self, fire: Any):
self.fire = fire # fire(kind, due)
self.schedules: dict[str, dict[str, Any]] = {}
self.due: dict[str, datetime | None] = {}
def update(self, schedules: dict[str, dict[str, Any]], now: datetime) -> None:
for k in KINDS:
s = schedules.get(k) or default_schedule()
if self.schedules.get(k) != s:
self.schedules[k] = s
self.due[k] = next_slot(now, s)
def tick(self, now: datetime) -> None:
for k in KINDS:
due = self.due.get(k)
if due is not None and due <= now:
self.fire(k, due)
self.due[k] = next_slot(max(now, due), self.schedules[k])
def wait_seconds(self, now: datetime) -> float:
dues = [d for d in self.due.values() if d is not None]
if not dues:
return 60.0
return max(0.0, min(60.0, min((d - now).total_seconds() for d in dues)))
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()
days = sync_days()
def _fire(kind: str, due: datetime) -> None:
def _run() -> None:
try:
res = run_once(store, app_state, today=due.date(), days=days, kinds=(kind,))
logger.info("%s 자동 업데이트 %s: %s", KIND_NAMES[kind], due.strftime("%H:%M"), res)
except Exception: # noqa: BLE001
logger.exception("%s 자동 업데이트 실패 — 다음 회차에 다시", KIND_NAMES[kind])
threading.Thread(target=_run, name=f"performance-auto-{kind}", daemon=True).start()
sched = Scheduler(_fire)
def _reload(now: datetime) -> None:
try:
schedules, _ = load_schedules(store)
except Exception: # noqa: BLE001 — DB 가 잠시 끊기면 직전 일정 그대로(처음이면 기본 일정)
logger.warning("자동 업데이트 일정 읽기 실패 — 직전 일정 사용", exc_info=True)
schedules = sched.schedules or normalize(None)
sched.update(schedules, now)
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"))
_reload(now_kst())
logger.info("실적 자동 업데이트 시작 — 최근 %d일, %s", days, ", ".join(
f"{KIND_NAMES[k]} {describe(sched.schedules[k])} 다음 "
f"{sched.due[k].strftime('%m-%d %H:%M') if sched.due[k] else '없음'}" for k in KINDS))
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)
time.sleep(max(1.0, sched.wait_seconds(now_kst()))) # 시계 변경·절전·일정 저장에도 1분 안에 다시 확인
now = now_kst()
_reload(now)
sched.tick(now)
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
+2 -2
View File
@@ -85,11 +85,11 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
def guard(request: Request, *, admin: bool = False):
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return RedirectResponse(url="/login", status_code=303)
return login_redirect(request)
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
return render_template(request, "denied.html",
+212 -52
View File
@@ -11,13 +11,90 @@ from typing import Any, Mapping, Sequence
from . import calc
from .adapters.base import STATUS_LABELS
from .adapters.registry import all_adapters, get_adapter
from .adapters.registry import get_adapter
def _sales_marketplaces(store: Any) -> list[dict[str, Any]]:
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서)."""
known = {a.code for a in all_adapters()}
return [m for m in store.list_marketplaces() if m["enabled"] and m["include_in_sales"] and m["code"] in known]
def ordered_marketplaces(markets: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
"""화면 순서(설정 드래그 = sort_order) — 그룹(009) 바로 뒤에 그 하위 쇼핑몰(하위끼리도 sort_order).
목록에 그룹이 없는 하위 쇼핑몰은 그룹 없음처럼 제자리. markets 는 sort_order 순(list_marketplaces)."""
groups = {m["code"] for m in markets if m.get("is_group")}
children: dict[str, list[Mapping[str, Any]]] = {}
for m in markets:
if m.get("parent_code") in groups and not m.get("is_group"):
children.setdefault(m["parent_code"], []).append(m)
out: list[Mapping[str, Any]] = []
for m in markets:
if m.get("parent_code") in groups and not m.get("is_group"):
continue
out.append(m)
out.extend(children.get(m["code"], ()))
return out
def _sales_marketplaces(store: Any, rows: Sequence[Mapping[str, Any]] | None = None) -> list[dict[str, Any]]:
"""대시보드 열 = 사용 ON + 매출 집계 ON 인 쇼핑몰(설정 순서 — 그룹 하위는 그룹 자리). 그룹 행은 빠진다(매출 없음)."""
rows = ordered_marketplaces(store.list_marketplaces() if rows is None else rows)
return [m for m in rows if m["enabled"] and m["include_in_sales"] and get_adapter(m["code"]) is not None]
def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str]) -> tuple[list[dict[str, Any]], dict[str, list[str]]]:
"""일자별 표 열 — 그룹(009)은 보이는 하위 쇼핑몰이 하나라도 있을 때 하위 열 바로 앞에 그룹 합계 열.
[{code, kind: shop|group|child, group}], 그룹 → 보이는 하위 코드."""
groups = {m["code"]: m for m in store_rows if m.get("is_group")}
parent = {m["code"]: m.get("parent_code") for m in store_rows if m.get("parent_code") in groups}
members: dict[str, list[str]] = {}
cols: list[dict[str, Any]] = []
for c in codes:
g = parent.get(c)
if g is None:
cols.append({"code": c, "kind": "shop", "group": ""})
continue
if g not in members:
members[g] = []
cols.append({"code": g, "kind": "group", "group": g})
members[g].append(c)
cols.append({"code": c, "kind": "child", "group": g})
return cols, members
# 카페24(실적) 열(2026-11-02, 예전 "공구 제외") — 카페24(전체) 바로 오른쪽, 카페24 − 공동구매. 표 열만(일 합계·그래프·누적엔 안 더함).
# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 다른 이름으로 바꾸면 빼지 않아 실적 = 전체가 된다, 자주 바뀌면 설정 값으로.
CAFE24_GB_NAMES = ("자사몰(공동구매)", "카페24공동구매")
CAFE24_EX_GB = "cafe24_ex_gb"
CAFE24_REAL_NAME = "카페24(실적)"
def groupbuy_code(markets: Sequence[Mapping[str, Any]]) -> str:
"""공동구매 쇼핑몰 코드, 없으면 빈 값."""
return next((m["code"] for m in markets if m["name"].replace(" ", "") in CAFE24_GB_NAMES), "")
def total_sales_codes(markets: Sequence[Mapping[str, Any]]) -> list[str]:
"""전체 매출에 더할 쇼핑몰 — 카페24(전체)에 공동구매가 들어 있어 카페24 가 있으면 공동구매는 뺀다(광고비 탭 매출 대비 광고비·합계 ROAS)."""
codes = [m["code"] for m in markets]
gb = groupbuy_code(markets)
return [c for c in codes if c != gb] if "cafe24" in codes else codes
def _summary_cells(cells: Mapping[tuple[date, str], calc.Money], gb: str) -> dict[tuple[date, str], calc.Money]:
"""합계용 칸(2026-11-02) — 카페24 칸 = 카페24(실적)(카페24 − 공동구매). 일 합계·KPI·그래프·누적은 이 값으로 더해 공동구매가 두 번 안 들어간다."""
out = dict(cells)
for (d, c), m in cells.items():
if c == gb:
a = cells.get((d, "cafe24"), calc.Money())
out[(d, "cafe24")] = calc.Money(gross=a.gross - m.gross, commission=a.commission - m.commission)
return out
def _cafe24_real_column(cols: list[dict[str, Any]], names: dict[str, str], short: dict[str, str], gb: str) -> None:
"""카페24(실적) 열 머리 — 공동구매가 없으면(gb 빈 값) 전체와 같은 값이고 화면 즉시 계산도 없다."""
col = next((c for c in cols if c["code"] == CAFE24_EX_GB), None)
if col is None:
return
# base·minus = 화면이 공동구매 칸 저장 때 이 줄 칸을 바로 다시 계산할 때 씀(performance.js saveManual)
col.update(kind="diff", base="cafe24", minus=gb)
names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" if gb else CAFE24_REAL_NAME
short[CAFE24_EX_GB] = CAFE24_REAL_NAME
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
@@ -32,15 +109,46 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
return (status_row or {}).get("status") or "unknown"
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
# 매출 단위(2026-10-19, 11-02 실적 설정 "공통 보기 설정" — 모든 사용자 같음, 마이그레이션 011 perf_settings) — (나누는 수, 소수 자리, 단위 이름)
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
UNIT_COOKIE = "perf_unit"
UNIT_SETTING = "display_unit"
def normalize_unit(value: Any) -> str:
return value if value in UNITS else "won"
# 일자별 표 열 너비(2026-10-27, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_colw) — auto = 글자 길이에 맞춤, manual = 머리글 경계 드래그
COLW_COOKIE = "perf_colw"
def normalize_colw(value: Any) -> str:
return "manual" if value == "manual" else "auto"
# 매출 실적 표 열 숨기기(2026-11-02, 실적 설정 "공통 보기 설정" — 관리자가 정하면 모든 사용자에게 적용, 마이그레이션 011 perf_settings) — 코드 목록, 열만 숨김
HIDDEN_SETTING = "hidden_marketplaces"
def _shared_setting(store: Any, key: str) -> Any:
"""모든 사용자 공통 설정 값. 저장 값 없음·011 미적용이면 None(화면은 그대로 열린다)."""
from .db import SettingsMigrationNeeded # noqa: WPS433
reader = getattr(store, "get_setting", None)
try:
return reader(key) if reader else None
except SettingsMigrationNeeded:
return None
def load_hidden(store: Any) -> set[str]:
return set(_shared_setting(store, HIDDEN_SETTING) or ())
def load_unit(store: Any) -> str:
return normalize_unit(_shared_setting(store, UNIT_SETTING))
def amount_text(value: Any, unit: str = "won") -> str:
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
div, places, _ = UNITS[normalize_unit(unit)]
@@ -53,7 +161,9 @@ def amount_text(value: Any, unit: str = "won") -> str:
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 = 매출 합 ÷ 광고비 합).
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
from . import ad_spend # noqa: WPS433
@@ -87,7 +197,7 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
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 = tot_sales = 0
tot_spend = 0
for c in codes:
lines = []
for ch, label in by_code.get(c, ()):
@@ -100,9 +210,10 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
tot_spend += amt
if lines:
r["ads"][c] = lines
tot_sales += sales(c, s, e)
if tot_spend:
r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, 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], ...]]:
@@ -120,11 +231,20 @@ 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,
configured: Mapping[str, bool] | None = None) -> dict[str, Any]:
markets = _sales_marketplaces(store)
store_rows = store.list_marketplaces()
markets = _sales_marketplaces(store, store_rows)
all_codes = [m["code"] for m in markets]
codes = [c for c in all_codes if c in set(selected)] or all_codes
names = {m["code"]: m["name"] for m in markets}
short = {c: _short_name(names[c]) for c in all_codes}
# 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
# 표에 그릴 열 = 고른 쇼핑몰 + 카페24 바로 뒤 카페24(실적) − 숨긴 열(합계·그래프·누적은 codes 그대로)
hidden = load_hidden(store)
shown = [x for c in codes for x in ((c, CAFE24_EX_GB) if c == "cafe24" else (c,)) if x not in hidden]
cols, group_members = _group_columns(store_rows, shown)
for m in store_rows:
if m["code"] in group_members:
names[m["code"]] = short[m["code"]] = m["name"]
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
@@ -143,40 +263,39 @@ 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())
gb = groupbuy_code(markets)
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes if not gb or gb in codes else [*codes, gb]),
store.rate_table())
summary = _summary_cells(cells, gb)
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(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
cur = calc.sum_range(summary, codes, period.start, period.end)
prev = calc.sum_range(summary, codes, cmp_start, cmp_end)
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)
share = calc.by_code(summary, codes, period.start, period.end)
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
summary_names = {**names, "cafe24": CAFE24_REAL_NAME}
statuses = store.statuses()
configured = configured or {}
problems = []
@@ -190,7 +309,18 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
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)
# 일 합계 = 카페24(실적) + 공동구매 + 나머지(2026-11-02) — 공동구매를 필터로 뺐으면 실적 + 나머지.
# 일 합계 ROAS 도 이 값 기준이라 _ad_lines 앞에서.
for r, s in zip(table, calc.main_table(period, codes, summary, today=today, holidays=holidays)):
r["total"] = s["total"]
if "cafe24" in codes:
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
_ad_lines(store, table, codes, cells, period, q_start, q_end)
for r in table:
for g, members in group_members.items():
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
for c in members).as_dict()
_cafe24_real_column(cols, names, short, gb)
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
if kind == "custom":
@@ -206,11 +336,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
next_url = url(period.kind, period.next_anchor)
nav = {
"prev": prev_url, "next": next_url,
# 빠른 선택은 이번달·올해만(2026-10-26 — 오늘·이번주 버튼 삭제, 기본 = 이번달)
"quick": [
{"key": "day", "label": "오늘", "url": url("day", today),
"active": period.kind == "day" and period.start == today},
{"key": "week", "label": "이번주", "url": url("week", today),
"active": period.kind == "week" and period.start <= today <= period.end},
{"key": "month", "label": "이번달", "url": url("month", today),
"active": period.kind == "month" and period.start <= today <= period.end},
{"key": "year", "label": "올해", "url": url("year", today),
@@ -225,19 +352,26 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"period_kind": period.kind,
"today": today.isoformat(),
"codes": codes,
"cols": cols,
"group_members": group_members,
"all_codes": all_codes,
"names": names,
"short_names": short,
"selected_all": len(codes) == len(all_codes),
"kpis": kpis,
"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],
"summary_names": summary_names,
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, summary),
"year": calc.year_months(year_period.start.year, codes, summary, today=today),
"chart_daily": calc.daily_series(period, codes, summary),
"chart_share": [{"code": c, "name": summary_names[c], **share[c].as_dict()} for c in codes],
"problems": problems,
"manual_codes": manual_codes,
"manual_cells": manual_cells,
"formula_cells": formula_cells,
# 날짜 칸 메모(마이그레이션 010) — "날짜|쇼핑몰" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
(store.cell_memos("sales", period.start, period.end) if hasattr(store, "cell_memos") else {}).items()},
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
"last_update_at": store.last_update_at(),
@@ -247,7 +381,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
def _short_name(name: str) -> str:
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name)
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스", "카페24": "카페24(전체)"}.get(name, name)
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
@@ -261,32 +395,58 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
today = today_kst()
via_cafe24 = set(MARKET_MAP.values()) # 카페24 마켓 통합관리 경유로 매출이 들어오는 쇼핑몰
rows = []
by_code = {m["code"]: m for m in store.list_marketplaces()}
for adapter in all_adapters():
m = by_code.get(adapter.code)
if m is None:
store_rows = store.list_marketplaces()
groups = [{"code": m["code"], "name": m["name"]} for m in store_rows if m.get("is_group")]
group_codes = {g["code"] for g in groups}
for m in ordered_marketplaces(store_rows):
code = m["code"]
parent = m.get("parent_code") if m.get("parent_code") in group_codes else ""
if m.get("is_group"):
# 그룹(009) — 매출·수수료·연결 없음, 하위 쇼핑몰 합계는 매출 실적 화면에서
rows.append({"code": code, "name": m["name"], "is_group": True, "is_custom": True, "parent": "",
"children": sum(1 for x in store_rows if x.get("parent_code") == code)})
continue
st_row = statuses.get(adapter.code) or {}
st = display_status(m, st_row, configured.get(adapter.code, False))
cur_rate = calc.rate_on(rates, adapter.code, today)
has_rate = bool(rates.get(adapter.code))
adapter = get_adapter(code)
if adapter is None:
continue
st_row = statuses.get(code) or {}
st = display_status(m, st_row, configured.get(code, False))
cur_rate = calc.rate_on(rates, code, today)
has_rate = bool(rates.get(code))
rows.append({
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
"code": code, "name": m["name"], "enabled": m["enabled"],
"is_group": False, "is_custom": bool(m.get("is_custom")), "parent": parent,
"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, ())),
"rate_history": len(rates.get(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,
"configured": configured.get(code, False),
"via_cafe24": code in via_cafe24,
"status": st, "status_label": STATUS_LABELS.get(st, st),
"last_test_at": st_row.get("last_test_at"), "last_test_ok": st_row.get("last_test_ok"),
"last_sync_at": st_row.get("last_sync_at"), "last_success_sync_at": st_row.get("last_success_sync_at"),
"last_error": st_row.get("last_error") or "", "last_error_at": st_row.get("last_error_at"),
})
# 드래그 단위 — 그룹 없는 행 하나 또는 그룹 + 하위 쇼핑몰(하위는 그 안에서만 순서 변경)
blocks: list[dict[str, Any]] = []
for r in rows:
if r["parent"] and blocks and blocks[-1]["row"]["code"] == r["parent"]:
blocks[-1]["children"].append(r)
else:
blocks.append({"row": r, "children": []})
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
return {"rows": rows, "key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
# "매출 실적 표 열 숨기기" 목록 = 매출 실적 표에 나오는 열(그룹 열은 하위를 다 숨기면 사라진다)
hide_options: list[dict[str, str]] = []
for r in rows:
if not r["is_group"] and r["enabled"] and r["include_in_sales"]:
hide_options.append({"code": r["code"], "name": _short_name(r["name"])})
if r["code"] == "cafe24":
hide_options.append({"code": CAFE24_EX_GB, "name": CAFE24_REAL_NAME})
return {"rows": rows, "blocks": blocks, "groups": groups, "hide_options": hide_options, "hidden_codes": load_hidden(store),
"custom_ready": bool(store_rows) and "is_custom" in store_rows[0],
"key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
"default_sample_from": today.replace(month=1, day=1).isoformat(),
"default_sample_to": today.isoformat()}
+230 -14
View File
@@ -26,10 +26,40 @@ from app.timezone import to_kst_iso
STALE_RUN_AFTER = timedelta(minutes=30)
class MemoMigrationNeeded(Exception):
"""날짜 칸 메모(마이그레이션 010: perf_cell_memos)가 아직 적용되지 않음."""
class SettingsMigrationNeeded(Exception):
"""설정 값 저장(마이그레이션 011: perf_settings — 자동 업데이트 일정)이 아직 적용되지 않음."""
class ManualMigrationNeeded(Exception):
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
class CustomMigrationNeeded(Exception):
"""직접 추가 쇼핑몰·그룹(마이그레이션 009: perf_marketplaces.is_custom · is_group · parent_code)이 아직 적용되지 않음."""
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)
@@ -85,6 +115,72 @@ class PerformanceDBStore:
raise ManualMigrationNeeded() from None
return {k: _iso(v) for k, v in row.items()} if row else None
# ── 직접 추가 쇼핑몰·그룹(마이그레이션 009) ──
def add_custom_marketplace(self, code: str, name: str, *, is_group: bool) -> dict[str, Any]:
"""맨 뒤 순서로 추가. 쇼핑몰 = 수동 입력 전용(manual_input), 그룹 = 매출 없음(include_in_sales 꺼 둠)."""
try:
with self._pool.connection() as conn:
row = conn.execute(
"INSERT INTO perf_marketplaces (code, name, sort_order, manual_input, include_in_sales, is_custom, is_group) "
"SELECT %s, %s, COALESCE(MAX(sort_order), 0) + 10, %s, %s, TRUE, %s FROM perf_marketplaces RETURNING *",
(code, name, not is_group, not is_group, is_group),
).fetchone()
except pg_errors.UndefinedColumn:
raise CustomMigrationNeeded() from None
return {k: _iso(v) for k, v in row.items()}
def rename_marketplace(self, code: str, name: str) -> dict[str, Any] | None:
with self._pool.connection() as conn:
row = conn.execute("UPDATE perf_marketplaces SET name = %s WHERE code = %s RETURNING *", (name, code)).fetchone()
return {k: _iso(v) for k, v in row.items()} if row else None
def set_marketplace_parent(self, code: str, parent_code: str | None) -> dict[str, Any] | None:
try:
with self._pool.connection() as conn:
row = conn.execute("UPDATE perf_marketplaces SET parent_code = %s WHERE code = %s RETURNING *",
(parent_code, code)).fetchone()
except pg_errors.UndefinedColumn:
raise CustomMigrationNeeded() from None
return {k: _iso(v) for k, v in row.items()} if row else None
def delete_custom_marketplace(self, code: str) -> bool:
"""직접 추가 행 삭제 — 그 쇼핑몰 수동 입력·수수료·상태·(테스트) 매출 행도 함께, 그룹이면 하위 쇼핑몰은 그룹 없음으로.
기본 쇼핑몰(is_custom = FALSE)은 지우지 않는다."""
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute("SELECT is_custom FROM perf_marketplaces WHERE code = %s FOR UPDATE", (code,)).fetchone()
if not row or not row.get("is_custom"):
return False
conn.execute("UPDATE perf_marketplaces SET parent_code = NULL WHERE parent_code = %s", (code,))
for table in ("perf_manual_sales", "perf_commission_rates", "perf_credentials",
"perf_connection_status", "perf_sales_events", "perf_sync_runs"):
conn.execute(f"DELETE FROM {table} WHERE marketplace_code = %s", (code,))
conn.execute("DELETE FROM perf_marketplaces WHERE code = %s", (code,))
return True
def manual_day_count(self, code: str) -> int:
"""수동 입력해 둔 날 수 — 직접 추가 쇼핑몰 삭제 확인 문구용."""
try:
with self._pool.connection() as conn:
row = conn.execute("SELECT COUNT(*) AS n FROM perf_manual_sales WHERE marketplace_code = %s",
(code,)).fetchone()
except pg_errors.UndefinedTable:
return 0
return int(row["n"] or 0)
def reorder_marketplaces(self, codes: list[str]) -> None:
"""설정 화면 드래그 순서 — 받은 순서대로 sort_order 10, 20, … (목록에 없는 행은 그 뒤 예전 순서)."""
with self._pool.connection() as conn:
with conn.transaction():
rest = [r["code"] for r in conn.execute(
"SELECT code FROM perf_marketplaces WHERE NOT (code = ANY(%s)) ORDER BY sort_order, code", (codes,)
).fetchall()]
with conn.cursor() as cur:
cur.executemany(
"UPDATE perf_marketplaces SET sort_order = %s WHERE code = %s AND sort_order IS DISTINCT FROM %s",
[((i + 1) * 10, c, (i + 1) * 10) for i, c in enumerate([*codes, *rest])],
)
# ════════════════════════════════════════════════════════════
# 수수료율 이력
# ════════════════════════════════════════════════════════════
@@ -338,8 +434,9 @@ class PerformanceDBStore:
).fetchone()
return int(row["amount"] or 0)
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None:
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값)."""
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:
@@ -352,6 +449,7 @@ class PerformanceDBStore:
"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
@@ -369,10 +467,78 @@ class PerformanceDBStore:
"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}
# ════════════════════════════════════════════════════════════
# 날짜 칸 메모(마이그레이션 010) — kind 'sales'(쇼핑몰)·'ad'(광고 채널). 금액과 따로(금액을 지워도 남음).
# ════════════════════════════════════════════════════════════
def cell_memos(self, kind: str, start: date, end: date) -> dict[tuple[date, str], str]:
"""(날짜, 코드) → 메모. 010 미적용이면 비어 있음."""
try:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT memo_date, code, memo FROM perf_cell_memos WHERE kind = %s AND memo_date BETWEEN %s AND %s",
(kind, start, end)).fetchall()
except pg_errors.UndefinedTable:
return {}
return {(r["memo_date"], r["code"]): r["memo"] for r in rows}
def set_cell_memo(self, kind: str, code: str, day: date, memo: str | None, *, user: str = "") -> None:
"""메모 저장(빈 값·None = 지움). 010 미적용이면 MemoMigrationNeeded."""
try:
with self._pool.connection() as conn:
if not memo:
conn.execute("DELETE FROM perf_cell_memos WHERE kind = %s AND code = %s AND memo_date = %s", (kind, code, day))
else:
conn.execute(
"INSERT INTO perf_cell_memos (kind, code, memo_date, memo, updated_by) VALUES (%s, %s, %s, %s, %s) "
"ON CONFLICT (kind, code, memo_date) DO UPDATE SET memo = EXCLUDED.memo, updated_by = EXCLUDED.updated_by, "
"updated_at = now()", (kind, code, day, memo, user))
except pg_errors.UndefinedTable:
raise MemoMigrationNeeded() from None
# ════════════════════════════════════════════════════════════
# 설정 값(마이그레이션 011) — 키 하나 = JSONB. 'auto_sync' = 자동 업데이트 일정(auto_sync.py)
# ════════════════════════════════════════════════════════════
def get_setting(self, key: str) -> Any:
"""값(없으면 None). 011 미적용이면 SettingsMigrationNeeded."""
try:
with self._pool.connection() as conn:
row = conn.execute("SELECT value FROM perf_settings WHERE key = %s", (key,)).fetchone()
except pg_errors.UndefinedTable:
raise SettingsMigrationNeeded() from None
return row["value"] if row else None
def set_setting(self, key: str, value: Any, *, user: str = "") -> None:
try:
with self._pool.connection() as conn:
conn.execute(
"INSERT INTO perf_settings (key, value, updated_by) VALUES (%s, %s, %s) "
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, "
"updated_at = now()", (key, Jsonb(value), user))
except pg_errors.UndefinedTable:
raise SettingsMigrationNeeded() from None
# ════════════════════════════════════════════════════════════
# 광고비(마이그레이션 005)
# ════════════════════════════════════════════════════════════
@@ -391,15 +557,19 @@ class PerformanceDBStore:
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None:
"""광고비 한 칸 저장(amount None = 지움)."""
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
def set_ad_spend(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) -> int:
metrics: dict[date, dict[str, Any]] | None = None,
formulas: dict[date, str] | None = None) -> int:
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다."""
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다.
formulas = 날짜 칸 계산식(008) — 저장하는 날 중 없는 날은 계산식을 지운다(업로드·API·숫자 입력)."""
from .ad_spend import AdMigrationNeeded # noqa: WPS433
if not entries:
@@ -433,23 +603,46 @@ class PerformanceDBStore:
"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_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
"""(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이)."""
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, roas FROM perf_ad_spend "
"WHERE spend_date BETWEEN %s AND %s AND roas IS NOT NULL", (start, end),
"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["roas"] for r in rows}
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."""
@@ -494,12 +687,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:
@@ -552,6 +757,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(
@@ -696,6 +910,8 @@ class PerformanceDBStore:
"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:
+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)
+21 -7
View File
@@ -153,9 +153,15 @@ class ShopProgress(Progress):
}
# 작업 종류 — 매출 업데이트(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
@@ -199,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),
@@ -214,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: # 오래된 끝난 작업부터 정리
@@ -232,8 +238,16 @@ def get_job(job_id: str) -> SyncJob | None:
return _JOBS.get(job_id)
def running_job() -> SyncJob | None:
"""지금 돌고 있는 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
def last_finished(kind: str = "sales", *, exclude_user: str = "") -> SyncJob | None:
"""가장 최근에 끝난 그 종류의 작업(exclude_user 가 시작한 것은 뺌). 화면이 자동 업데이트(다른 사람 업데이트 포함)가 끝난 것을
알아채 새로 그리려고(2026-10-26) — 보는 사람이 직접 누른 업데이트는 진행 창이 알아서 새로 그린다."""
with _LOCK:
live = [j for j in _JOBS.values() if not j.finished]
done = [j for j in _JOBS.values() if j.finished and j.kind == kind and not (exclude_user and j.user == exclude_user)]
return max(done, key=lambda j: j.finished_at) if done else None
def running_job(kind: str = "sales") -> SyncJob | None:
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
with _LOCK:
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
+1 -4
View File
@@ -4,7 +4,7 @@
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨.
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜도 됨(2026-10-21).
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
@@ -185,9 +185,6 @@ def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: d
data_rows += 1
if data_rows > MAX_DATA_ROWS:
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
if day > today:
res.errors.append(f"{_cell_ref(r, 1)}: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
continue
for i, amt in amounts.items():
code = col_code[i]
where = _cell_ref(r, i + 1)
+403 -61
View File
@@ -18,11 +18,20 @@ JSON API — 모듈 권한
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-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
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 — 관리자
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부, 직접 추가 행 이름·그룹(009)
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
PUT /performance/api/hidden-marketplaces 매출 실적 표 열 숨기기(모든 사용자에게 적용)
PUT /performance/api/display-unit 매출 단위(모든 사용자에게 적용)
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
DELETE /performance/api/marketplaces/{code}/rates/{id}
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
@@ -47,7 +56,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from app.timezone import today_kst
from . import common
from . import calc, common
from .adapters.registry import all_adapters, get_adapter
router = APIRouter(prefix="/performance", tags=["performance"])
@@ -69,6 +78,9 @@ AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저
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
CUSTOM_MIGRATION_HELP = ("쇼핑몰 직접 추가·그룹을 쓰려면 performance_db 마이그레이션 009"
"(scripts/sql/performance_db_009_custom_marketplaces.sql)를 먼저 적용해야 합니다.")
MAX_MARKET_NAME = 30
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
"먼저 적용해야 합니다.")
@@ -111,12 +123,12 @@ def health(request: Request) -> JSONResponse:
@router.get("/", response_class=HTMLResponse)
def dashboard_page(
request: Request,
period: str = "week",
period: str = "month",
d: str | None = None,
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
@@ -134,21 +146,78 @@ 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"
_unit_ctx(request, ctx)
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
ctx["update_watch"] = _update_watch("sales", user)
_unit_ctx(store, ctx)
_colw_ctx(request, ctx)
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
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
def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
"""다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. kind = sales(매출 실적) / ads(광고비),
일정은 실적 설정 "자동 업데이트"(2026-10-26, auto_sync.load_schedules). 회차가 지나면 화면이 같은 규칙
(schedule: 간격·요일·시작/끝, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정.
자동 업데이트가 꺼져 있거나(env·일정) 회차가 없으면 None."""
from app.timezone import now_kst # noqa: WPS433
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
from . import auto_sync # noqa: WPS433
if not auto_sync.enabled():
return None
try:
sched = auto_sync.load_schedules(store)[0][kind]
except Exception: # noqa: BLE001 — DB 오류: 카운트다운만 숨김
return None
now = now_kst()
nxt = auto_sync.next_slot(now, sched)
if nxt is None:
return None
return {"next_at": nxt.isoformat(), "now": now.isoformat(timespec="milliseconds"), "schedule": sched,
"label": auto_sync.describe(sched)}
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
from . import jobs # noqa: WPS433
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
return {"kind": kind, "seen": job.id if job else ""}
@router.get("/api/update-status")
def api_update_status(request: Request, kind: str = "sales") -> JSONResponse:
"""지금 그 종류 업데이트가 도는지 · 마지막으로 끝난 업데이트(보는 사람이 시작한 것 제외) — 화면이 20초마다 본다.
메모리의 진행 작업만 보고 DB 는 안 읽는다."""
from . import jobs # noqa: WPS433
_, user = common.require_store(request)
if kind not in jobs.KINDS:
raise HTTPException(status_code=404, detail="알 수 없는 업데이트 종류입니다.")
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
return JSONResponse({"kind": kind, "running": jobs.running_job(kind) is not None, "done": job.id if job else "",
"user": job.user if job else ""})
def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
"""매출 단위(원·천원·백만원) — 관리자가 실적 설정 "공통 보기 설정"에서 정하면 모든 사용자에게 같게. 템플릿은 amt(v) 로 그린다."""
from .dashboard import UNITS, amount_text, load_unit # noqa: WPS433
unit = load_unit(store)
ctx["unit"] = unit
ctx["unit_label"] = UNITS[unit][2]
ctx["amt"] = lambda v: amount_text(v, unit)
def _colw_ctx(request: Request, ctx: dict[str, Any]) -> None:
"""일자별 표 열 너비(2026-10-27) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_colw)에 둔다.
manual 이면 표에 perf-colw-manual — performance.js initColWidths 가 머리글 경계 드래그 + 너비 기억(localStorage)."""
from .dashboard import COLW_COOKIE, normalize_colw # noqa: WPS433
ctx["colw"] = normalize_colw(request.cookies.get(COLW_COOKIE))
@router.get("/ads", response_class=HTMLResponse)
def ads_page(
request: Request,
@@ -164,19 +233,31 @@ def ads_page(
return g
store, user = g
from .ad_spend import build_ad_dashboard # noqa: WPS433
from .dashboard import _sales_marketplaces # noqa: WPS433
from .dashboard import _sales_marketplaces, total_sales_codes # 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)],
sales_codes=total_sales_codes(_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)
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in ad_sync.configured().items() if ok]
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(store, "ads")
ctx["update_watch"] = _update_watch("ads", user)
_colw_ctx(request, ctx)
return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
@@ -203,11 +284,63 @@ def settings_page(request: Request):
)
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
ctx["ad_api_ready"] = store.ad_api_ready()
_unit_ctx(request, ctx)
ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿)
_unit_ctx(store, ctx)
_colw_ctx(request, ctx)
return render_template(request, "performance/settings.html",
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
def _auto_sync_settings_ctx(store: Any) -> dict[str, Any]:
"""실적 설정 "자동 업데이트" 카드(2026-10-26) — 종류마다 일정·다음 회차, 011 적용 여부, env 로 꺼졌는지."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
try:
schedules, ready = auto_sync.load_schedules(store)
error = ""
except Exception as exc: # noqa: BLE001 — DB 오류여도 설정 화면은 뜬다
schedules, ready, error = auto_sync.normalize(None), True, f"일정을 읽지 못했습니다({type(exc).__name__}) — 기본 일정을 보여 줍니다."
now = now_kst()
kinds = []
for k in auto_sync.KINDS:
nxt = auto_sync.next_slot(now, schedules[k])
kinds.append({"kind": k, "name": auto_sync.KIND_NAMES[k], "schedule": schedules[k],
"label": auto_sync.describe(schedules[k]), "next_at": nxt.isoformat() if nxt else ""})
return {"kinds": kinds, "ready": ready, "env_on": auto_sync.enabled(), "days": auto_sync.sync_days(),
"error": error, "weekdays": auto_sync.WEEKDAYS, "step": auto_sync.INTERVAL_STEP,
"max": auto_sync.INTERVAL_MAX}
@router.put("/api/auto-sync-schedule")
def api_auto_sync_schedule(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""자동 업데이트 일정 저장(2026-10-26, 관리자, 마이그레이션 011) — {sales: 일정, ads: 일정}. 스레드가 1분 안에 반영."""
from app.timezone import now_kst # noqa: WPS433
from . import auto_sync # noqa: WPS433
from .db import SettingsMigrationNeeded # noqa: WPS433
store, user = common.require_store(request, admin=True)
value = {}
for k in auto_sync.KINDS:
try:
value[k] = auto_sync.validate_schedule(payload.get(k))
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"{auto_sync.KIND_NAMES[k]}: {exc}") from None
try:
store.set_setting(auto_sync.SETTING_KEY, value, user=user.get("email", ""))
except SettingsMigrationNeeded:
raise HTTPException(status_code=503, detail="일정을 저장하려면 performance_db 마이그레이션 011"
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
now = now_kst()
out = {}
for k, sched in value.items():
nxt = auto_sync.next_slot(now, sched)
out[k] = {"schedule": sched, "label": auto_sync.describe(sched), "next_at": nxt.isoformat() if nxt else ""}
return JSONResponse({"ok": True, "env_on": auto_sync.enabled(), **out})
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
from .ad_sources.registry import all_sources # noqa: WPS433
@@ -364,37 +497,44 @@ 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:
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞으로의 날도 가능(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)
if d > today_kst():
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
if not m.get("manual_input"):
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
raw = payload.get("amount")
amount: int | None
if raw in (None, ""):
amount = None
else:
try:
amount = int(Decimal(str(raw).replace(",", "").strip()))
except (InvalidOperation, ValueError):
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
if abs(amount) > MAX_MANUAL_AMOUNT:
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
amount, formula = _cell_amount(payload.get("amount"))
try:
store.set_manual_sale(code, d, amount, user=user.get("email", ""))
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,
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
shown = api_amount if amount is None else amount
# 그날 수수료·수수료 차감 매출도 돌려준다 — 화면이 새로고침 전에도 보고 있는 기준(기본 = 차감 매출) 숫자를 바로 바꾸게
rate_table = getattr(store, "rate_table", None)
money = calc.build_cells({(d, code): shown}, rate_table() if rate_table else {})[(d, code)].as_dict()
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount, "formula": formula,
"amount": shown, "api_amount": api_amount,
"commission": money["commission"], "net": money["net"]})
@router.get("/api/manual-sales/sample.xlsx")
@@ -415,9 +555,9 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
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}
# 직접 추가 쇼핑몰(009)도 대상 — 어댑터 = 수동 입력 전용(이름은 DB), 그룹 행은 어댑터가 없어 빠진다
markets = [m for m in store.list_marketplaces() if get_adapter(m["code"]) is not None and m["enabled"]]
extra = {m["code"]: tuple(n for n in (get_adapter(m["code"]).name, _short_name(m["name"])) if n) 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:
@@ -455,6 +595,38 @@ def _ad_channel(channel: str) -> str:
return channel
MEMO_MAX = 1000
@router.put("/api/cell-memos/{kind}/{code}/{day}")
def api_cell_memo(request: Request, kind: str, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — kind = sales(매출 실적, 쇼핑몰) / ad(광고비, 광고 채널).
memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다."""
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
from .db import MemoMigrationNeeded # noqa: WPS433
store, user = common.require_store(request)
if kind == "sales":
_code_or_404(store, code)
elif kind == "ad":
if code not in CHANNEL_NAMES:
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
else:
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
d = _parse_date(day)
if d is None:
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
memo = str(payload.get("memo") or "").replace("\r\n", "\n").strip()
if len(memo) > MEMO_MAX:
raise HTTPException(status_code=400, detail=f"메모는 {MEMO_MAX:,}자까지 쓸 수 있습니다.")
try:
store.set_cell_memo(kind, code, d, memo or None, user=user.get("email", ""))
except MemoMigrationNeeded:
raise HTTPException(status_code=503, detail="메모를 쓰려면 performance_db 마이그레이션 010"
"(scripts/sql/performance_db_010_cell_memos.sql)을 먼저 적용해야 합니다.") from None
return JSONResponse({"ok": True, "kind": kind, "code": code, "date": d.isoformat(), "memo": memo})
@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
@@ -464,24 +636,12 @@ def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, An
d = _parse_date(day)
if d is None:
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
if d > today_kst():
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
raw = payload.get("amount")
amount: int | None
if raw in (None, ""):
amount = None
else:
try:
amount = int(Decimal(str(raw).replace(",", "").strip()))
except (InvalidOperation, ValueError):
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
if abs(amount) > MAX_MANUAL_AMOUNT:
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
amount, formula = _cell_amount(payload.get("amount"))
try:
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
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,
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount, "formula": formula,
"amount": amount or 0})
@@ -625,18 +785,12 @@ def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Bo
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
@router.post("/api/ad-sources/{code}/sync")
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""광고비 탭 [구글 광고 불러오기] — 기간(from·to, 없으면 최근 N일)을 가져와 저장. 오늘 뒤는 잘라낸다.
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
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 .ad_spend import AdMigrationNeeded # noqa: WPS433
from .ad_sync import AdSyncBusy # noqa: WPS433
from .auto_sync import sync_days # noqa: WPS433
store, user = common.require_store(request)
src = _ad_source_or_404(code)
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))
@@ -650,6 +804,51 @@ def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Bo
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 연동에서 입력해야 합니다.")
@@ -667,15 +866,158 @@ def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Bo
# ════════════════════════════════════════════════════════════
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
# ════════════════════════════════════════════════════════════
def _market_or_404(store: Any, code: str) -> dict[str, Any]:
"""DB 행(그룹 포함)."""
m = next((x for x in store.list_marketplaces() if x["code"] == code), None)
if m is None or (get_adapter(code) is None and not m.get("is_group")):
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
return m
def _clean_market_name(store: Any, raw: Any, *, code: str = "") -> str:
"""직접 추가 행 이름 — 엑셀 업로드 머리글로도 쓰여 다른 쇼핑몰·그룹과 겹치면 안 된다."""
name = " ".join(str(raw or "").split())
if not name:
raise HTTPException(status_code=400, detail="이름을 입력하세요.")
if len(name) > MAX_MARKET_NAME:
raise HTTPException(status_code=400, detail=f"이름은 {MAX_MARKET_NAME}자까지입니다.")
if any(m["code"] != code and m["name"].strip().lower() == name.lower() for m in store.list_marketplaces()):
raise HTTPException(status_code=400, detail=f"같은 이름({name})이 이미 있습니다.")
return name
def _set_parent(store: Any, code: str, parent: str | None) -> dict[str, Any] | None:
from .db import CustomMigrationNeeded # noqa: WPS433
if parent:
g = next((x for x in store.list_marketplaces() if x["code"] == parent), None)
if g is None or not g.get("is_group"):
raise HTTPException(status_code=400, detail="그룹을 찾지 못했습니다.")
try:
return store.set_marketplace_parent(code, parent or None)
except CustomMigrationNeeded:
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
@router.post("/api/marketplaces")
def api_add_marketplace(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""직접 추가(009) — kind="shop" 수동 입력 전용 쇼핑몰(맨 뒤, 사용·매출 집계·수동 입력 켬), kind="group" 그룹."""
import secrets # noqa: WPS433
from .adapters.registry import CUSTOM_PREFIX, GROUP_PREFIX # noqa: WPS433
from .db import CustomMigrationNeeded # noqa: WPS433
store, _ = common.require_store(request, admin=True)
kind = payload.get("kind") or "shop"
if kind not in ("shop", "group"):
raise HTTPException(status_code=400, detail="kind 는 shop 또는 group 입니다.")
name = _clean_market_name(store, payload.get("name"))
code = (GROUP_PREFIX if kind == "group" else CUSTOM_PREFIX) + secrets.token_hex(4)
try:
row = store.add_custom_marketplace(code, name, is_group=kind == "group")
except CustomMigrationNeeded:
raise HTTPException(status_code=503, detail=CUSTOM_MIGRATION_HELP) from None
if kind == "shop" and payload.get("parent_code"):
row = _set_parent(store, code, str(payload["parent_code"])) or row
return JSONResponse({"marketplace": row})
@router.delete("/api/marketplaces/{code}")
def api_delete_marketplace(request: Request, code: str) -> JSONResponse:
"""직접 추가한 쇼핑몰·그룹만 — 쇼핑몰이면 수동 입력 매출·수수료율도 지운다, 그룹이면 하위 쇼핑몰은 그룹 없음."""
store, _ = common.require_store(request, admin=True)
m = _market_or_404(store, code)
if not m.get("is_custom"):
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요).")
if not store.delete_custom_marketplace(code):
raise HTTPException(status_code=404, detail="알 수 없는 쇼핑몰입니다.")
return JSONResponse({"ok": True})
@router.get("/api/marketplaces/{code}/manual-days")
def api_manual_days(request: Request, code: str) -> JSONResponse:
"""수동 입력해 둔 날 수 — 직접 추가 쇼핑몰 삭제 확인 문구용."""
store, _ = common.require_store(request, admin=True)
_market_or_404(store, code)
return JSONResponse({"days": store.manual_day_count(code)})
@router.put("/api/marketplace-order")
def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""설정 드래그 순서 — 화면에 보이는 순서(그룹 뒤에 하위) 그대로 codes. 매출 실적 열 순서가 된다."""
store, _ = common.require_store(request, admin=True)
known = {m["code"] for m in store.list_marketplaces()}
codes = [str(c) for c in (payload.get("codes") or []) if str(c) in known]
if len(set(codes)) != len(codes):
raise HTTPException(status_code=400, detail="순서 목록에 같은 쇼핑몰이 두 번 있습니다.")
if not codes:
raise HTTPException(status_code=400, detail="순서 목록이 비었습니다.")
store.reorder_marketplaces(codes)
return JSONResponse({"ok": True})
@router.put("/api/hidden-marketplaces")
def api_hidden_marketplaces(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""매출 실적 표 열 숨기기(2026-11-02, 관리자, 마이그레이션 011) — 체크한 코드 전부. 모든 사용자의 표에 적용."""
from .dashboard import CAFE24_EX_GB, HIDDEN_SETTING # noqa: WPS433
store, user = common.require_store(request, admin=True)
raw = payload.get("codes")
if not isinstance(raw, list):
raise HTTPException(status_code=400, detail="숨길 쇼핑몰 목록이 필요합니다.")
known = {m["code"] for m in store.list_marketplaces()} | {CAFE24_EX_GB}
codes = sorted({str(c) for c in raw} & known)
_save_shared_setting(store, HIDDEN_SETTING, codes, user)
return JSONResponse({"ok": True, "codes": codes})
@router.put("/api/display-unit")
def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""매출 단위(2026-11-02, 관리자, 마이그레이션 011) — won·thousand·million. 모든 사용자의 매출 실적 화면에 적용."""
from .dashboard import UNIT_SETTING, UNITS # noqa: WPS433
store, user = common.require_store(request, admin=True)
unit = payload.get("unit")
if not isinstance(unit, str) or unit not in UNITS:
raise HTTPException(status_code=400, detail="알 수 없는 매출 단위입니다.")
_save_shared_setting(store, UNIT_SETTING, unit, user)
return JSONResponse({"ok": True, "unit": unit})
def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None:
from .db import SettingsMigrationNeeded # noqa: WPS433
try:
store.set_setting(key, value, user=user.get("email", ""))
except SettingsMigrationNeeded:
raise HTTPException(status_code=503, detail="저장하려면 performance_db 마이그레이션 011"
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
@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)
m = _market_or_404(store, code)
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="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
# 직접 추가 행(009) — 이름·그룹. 그룹으로 묶을 수 있는 건 직접 추가한 쇼핑몰만(그룹 안에 그룹 없음)
if "name" in payload or "parent_code" in payload:
if not m.get("is_custom"):
raise HTTPException(status_code=400, detail="기본 쇼핑몰은 이름·그룹을 바꿀 수 없습니다.")
if "parent_code" in payload and m.get("is_group"):
raise HTTPException(status_code=400, detail="그룹은 다른 그룹에 넣을 수 없습니다.")
row = None
if "name" in payload:
row = store.rename_marketplace(code, _clean_market_name(store, payload.get("name"), code=code))
if "parent_code" in payload:
row = _set_parent(store, code, str(payload.get("parent_code") or "") or None)
if not any(k in payload for k in ("enabled", "include_in_sales", "manual_input")):
return JSONResponse({"marketplace": row})
if m.get("is_group"):
raise HTTPException(status_code=400, detail="그룹은 이름만 바꿀 수 있습니다.")
try:
row = store.update_marketplace(
@@ -828,7 +1170,7 @@ def api_sample_data(request: Request, payload: dict[str, Any] = Body(...)) -> JS
start, end = end, start
if (end - start).days > 400:
raise HTTPException(status_code=400, detail="테스트 데이터는 한 번에 400일까지 만들 수 있습니다.")
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"]]
codes = [m["code"] for m in store.list_marketplaces() if m["enabled"] and get_adapter(m["code"]) is not None]
_, sync = common.services(request, store)
n = sync.generate_samples(start, end, codes)
return JSONResponse({"generated": n, "sample_count": store.sample_count()})
+2 -1
View File
@@ -164,7 +164,8 @@ 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"]}
# 설정에서 수동 입력을 켠 쇼핑몰은 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)]
@@ -0,0 +1,6 @@
{# 기간 이동(2026-11-02, 매출 실적·광고비 공통) — 날짜 바로 좌우에 화살표 이미지(SVG, 글자 높이), 글자 버튼 없음 #}
<div class="perf-nav">
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}" aria-label="{{ period.prev_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M8 1.5 2 8l6 6.5"/></svg></a>
<span class="perf-nav-label">{{ period.label }}</span>
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}" aria-label="{{ period.next_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M2 1.5 8 8l-6 6.5"/></svg></a>
</div>
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -24,11 +24,7 @@
<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>
{% include "performance/_period_nav.html" %}
<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" />
@@ -37,34 +33,49 @@
<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.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <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">
<!-- ── KPI — 한 줄(2026-10-30, 매출 실적처럼): 광고비 · 매출 대비 광고비 · 연 누적 ── -->
<div class="perf-kpi-line">
{% for k in kpis %}
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
<div class="perf-kpi-label">{{ k.label }}</div>
<span class="perf-kpi-item">
<span class="perf-muted">{{ k.label }}</span>
{% 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>
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</b>
<span class="perf-muted">{{ k.note }}</span>
{% 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>
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
{% 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 %}
</span>
{% endfor %}
</div>
@@ -73,45 +84,44 @@
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
<div class="perf-ad-actions">
{% for s in ad_sync_sources %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-ad-sync-btn" data-ad-sync="{{ s.code }}"
title="{{ s.name }} API 로 지금 보는 기간(오늘까지)의 광고비·ROAS 를 가져옵니다 — 같은 날은 덮어씀">
<span class="material-symbols-outlined" aria-hidden="true">sync</span>{{ s.name }} 불러오기</button>
{% endfor %}
{% 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">
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads">
<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>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" data-col="{{ c }}" 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 data-col="{{ c }}" 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 %}
</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 %}>
<th class="perf-td-label" scope="row">
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
{% for c in codes %}
{% set v = r.cells[c].gross %}
{% if r.kind == 'day' and not r.future and not migration_needed %}
{% if r.kind == 'day' and not migration_needed %}
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% 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 '' }}" tabindex="0"
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %}
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) -#}
<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 %}{% if memo %} has-memo{% endif %}"
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}" data-manual-value="{{ v if v else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0"><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>
@@ -121,7 +131,7 @@
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% endif %}
</div>
@@ -203,7 +213,7 @@
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
메타는 지금은 직접 입력합니다.
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
</p>
</section>
@@ -213,6 +223,7 @@
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind,
"memo_kind": "ad",
"today": today,
"manual_api": "/performance/api/ad-spend/",
"manual_word": "광고비",
@@ -220,8 +231,10 @@
"period_end": period.end.isoformat(),
"period_label": period.label,
"empty_text": "기간 내 광고비가 없습니다.",
"upload_channels": upload_channels
"upload_channels": upload_channels,
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
@@ -13,7 +13,15 @@
{%- 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 -%}
{%- for a in lines or [] -%}<span class="perf-adl">{% 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 }}">{{ amt(a.amount) }}{% if rs is not none %}<em>({{ "{:,}".format(rs) }}%)</em>{% endif %}</span>
{%- endfor -%}
{%- endmacro -%}
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
@@ -34,11 +42,7 @@
<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>
{% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" />
@@ -72,9 +76,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.label }} (실적 설정에서 바꿈)">다음 업데이트까지 <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>
@@ -92,24 +101,18 @@
{% 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">{{ money(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">
@@ -127,34 +130,55 @@
<button type="button" class="perf-seg" data-metric="net">수수료 차감 매출</button>
</div>
</div>
<div class="erp-table-wrap perf-table-wrap">
<table class="perf-table perf-main">
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales">
<thead>
<tr>
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
{% 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>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
{#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션).
하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#}
{% for col in cols %}{% set c = col.code %}
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
{% if col.kind == 'group' %}<th class="perf-th-group" data-col="{{ c }}" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><span class="perf-gh"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" aria-label="{{ short_names[c] }} 하위 쇼핑몰 접기" title="하위 쇼핑몰 접기/펴기"><svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true"><rect class="g-box" x="1" y="1" width="16" height="16" rx="4"/><path class="g-h" d="M5 9h8"/><path class="g-v" d="M9 5v8"/></svg></button><span>{{ short_names[c] }}</span></span></th>
{% else %}<th data-col="{{ c }}"{% if sub %} class="perf-th-child{% if glast %} is-glast{% endif %}" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{% if sub %}<div class="perf-gc">{% endif %}{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}{% if sub %}</div>{% endif %}</th>{% endif %}
{% endfor %}
</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 %}>
<th class="perf-td-label" scope="row">
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
{% for c in codes %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
{% for col in cols %}
{% set c = col.code %}
{% set m = r.cells[c] %}
{% if r.kind == 'day' and c in manual_codes and not r.future %}
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
{% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
{% set gc0 %}{% if sub %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if sub %}</div>{% endif %}{% endset %}
{% if col.kind == 'group' %}
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td>
{% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#}
{%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페24 총매출,수수료,차감) − 새 값으로 바로 바꿈 -#}
<td class="perf-num{% if glast %} is-glast{% endif %}"{{ gattr }}{% if r.kind == 'day' and col.minus %} data-diff-minus="{{ col.minus }}" data-base="{{ b.gross }},{{ b.commission }},{{ b.net }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[col.base]) }}{{ gc1 }}</td>
{% elif r.kind == 'day' and c in manual_codes %}
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
data-manual-value="{{ m.gross if is_manual else '' }}" tabindex="0"
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) — 우클릭 메모 삽입·수정·삭제, 있으면 칸 오른쪽 위 빨간 삼각형 -#}
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}{% if fx %} is-formula{% endif %}{% if glast %} is-glast{% endif %}{% if memo %} has-memo{% endif %}"{{ gattr }} data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}"
data-manual-value="{{ m.gross if is_manual else '' }}"{% if fx %} data-formula="{{ fx }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %} tabindex="0">{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</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) }}{{ adl(r.ads[c]) }}</td>
{#- 메모(2026-10-22) — API 쇼핑몰 날짜 칸도 우클릭 메모(data-memo-code). 왼쪽 클릭은 그대로 주문 내역 -#}
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) if r.kind == 'day' else none %}
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}{% if glast %} is-glast{% endif %}{% if memo %} has-memo{% endif %}"{{ gattr }}
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}{% if r.kind == 'day' %} data-memo-code="{{ c }}" data-date="{{ r.date }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
{% endif %}
{% endfor %}
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
@@ -162,7 +186,7 @@
</div>
{% if manual_codes and period_kind != 'year' %}
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
비우고 저장하면 다시 API 수집값. <b>1000+2000</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
{% endif %}
</div>
@@ -190,7 +214,7 @@
<tbody>
{% for r in month.rows %}
<tr>
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
<th class="perf-td-label" scope="row">{{ summary_names[r.code] }}</th>
<td class="perf-num">{{ won(r.gross) }}</td>
<td class="perf-num">{{ won(r.commission) }}</td>
<td class="perf-num">{{ won(r.net) }}</td>
@@ -249,6 +273,7 @@
<p class="perf-foot perf-muted">
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
</p>
</section>
@@ -258,12 +283,15 @@
"daily": chart_daily,
"share": chart_share,
"period_kind": period_kind,
"memo_kind": "sales",
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"today": today,
"unit": unit,
"manual_upload_names": manual_upload_names
"manual_upload_names": manual_upload_names,
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
@@ -21,7 +21,7 @@
<h2 class="perf-h">쇼핑몰 설정</h2>
{% if is_admin %}
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다.</span>
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span>
{% else %}
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
{% endif %}
@@ -41,10 +41,30 @@
{% 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>
{# 드래그 단위(2026-10-22) = tbody 하나 — 그룹 없는 행 하나 또는 그룹 + 하위 쇼핑몰(하위는 그 안에서만 순서 변경) #}
{% for b in blocks %}
<tbody class="perf-sort-block{% if b.row.is_group %} is-group-block{% endif %}">
{% for r in [b.row] + b.children %}
{% if r.is_group %}
<tr class="perf-group-row" data-code="{{ r.code }}" data-name="{{ r.name }}" data-group="1">
<th class="perf-td-label" scope="row">
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)" aria-hidden="true">⠿</span>{% endif %}
<span class="perf-group-name">{{ r.name }}</span> <span class="perf-pill">그룹</span>
</th>
<td colspan="{{ 7 if is_admin else 2 }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td>
{% if is_admin %}
<td class="perf-nowrap">
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rename">이름 변경</button>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm perf-del-btn" data-act="delete">삭제</button>
</td>
{% endif %}
</tr>
{% else %}
<tr data-code="{{ r.code }}" data-name="{{ r.name }}"{% if r.parent %} class="perf-child-row" data-parent="{{ r.parent }}"{% endif %}{% if r.is_custom %} data-custom="1"{% endif %}>
<th class="perf-td-label" scope="row">
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경" aria-hidden="true">⠿</span>{% endif %}
{% if r.parent %}<span class="perf-child-mark" aria-hidden="true">└</span>{% endif %}{{ r.name }}{% if r.is_custom %} <span class="perf-pill" title="실적 설정에서 직접 추가한 쇼핑몰">직접 추가</span>{% endif %}
</th>
{% if is_admin %}
<td class="perf-center">
<label class="perf-switch" title="사용 여부">
@@ -57,7 +77,7 @@
</label>
</td>
<td class="perf-center">
<label class="perf-switch" title="{% if r.manual_only %}수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다{% else %}수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신){% endif %}">
<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>
@@ -85,28 +105,69 @@
<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 %}
{% if r.is_custom %}
<select class="erp-input perf-group-sel" data-act-group title="그룹 — 그룹으로 묶으면 매출 실적에서 그룹 열이 하위 쇼핑몰 매출 합계">
<option value="">그룹 없음</option>
{% for g in groups %}<option value="{{ g.code }}"{% if r.parent == g.code %} selected{% endif %}>{{ g.name }}</option>{% endfor %}
</select>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rename">이름 변경</button>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm perf-del-btn" data-act="delete">삭제</button>
{% elif 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>
{% endif %}
{% endfor %}
</tbody>
{% endfor %}
</table>
</div>
{% if is_admin %}
<div class="perf-add-row">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-add-shop"
title="API 연동 없이 실적 일자별 표에 매출을 직접 입력하는 쇼핑몰을 추가">+ 쇼핑몰 추가(수동 입력)</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-add-group"
title="직접 추가한 쇼핑몰을 묶는 그룹 — 그룹 매출 = 하위 쇼핑몰 매출 합계">+ 그룹 추가</button>
<span class="perf-muted">⠿ 를 끌어 순서를 바꾸면 매출 실적 열 순서에 그대로 반영됩니다. 그룹은 직접 추가한 쇼핑몰만 묶을 수 있습니다.</span>
{% if not custom_ready %}<span class="perf-notice is-warn">쇼핑몰 직접 추가·그룹은 performance_db 마이그레이션 009
(scripts/sql/performance_db_009_custom_marketplaces.sql)을 적용해야 쓸 수 있습니다.</span>{% endif %}
</div>
{% endif %}
<p class="perf-foot perf-muted">
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
</p>
</div>
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만 #}
<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>
<span class="perf-muted">매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
</div>
{# 표 열 너비(2026-10-27, 쿠키 perf_colw) — 매출 실적·광고비 일자별 표. 수동 = 머리글 오른쪽 경계 드래그, 너비는 이 브라우저 localStorage(perf_colw_sales/ads) #}
<div class="perf-opt-row">
<span class="perf-opt-label">표 열 너비</span>
<div class="perf-quick" role="radiogroup" aria-label="표 열 너비">
{% for k, label in [('auto', '자동(글자 길이)'), ('manual', '수동 조절')] %}
<button type="button" class="perf-seg{% if colw == k %} is-active{% endif %}" role="radio"
aria-checked="{{ 'true' if colw == k else 'false' }}" data-colw="{{ k }}">{{ label }}</button>
{% endfor %}
</div>
<span class="perf-muted" id="perf-colw-help">{% if colw == 'manual' %}매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.{% else %}열 너비가 글자 길이에 맞춰 자동으로 정해집니다.{% endif %}</span>
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" id="perf-colw-reset"{% if colw != 'manual' %} hidden{% endif %}>조절한 너비 초기화</button>
</div>
</div>
{% if is_admin %}
{# 공통 보기 설정(2026-11-02, 관리자, 마이그레이션 011 perf_settings) — 매출 단위·열 숨기기, 모든 사용자에게 적용 #}
<div class="erp-card perf-card" id="perf-shared-view">
<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>
@@ -119,7 +180,74 @@
<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 class="perf-opt-row">
<span class="perf-opt-label">숨길 쇼핑몰</span>
<div class="perf-hide-list">
{% for m in hide_options %}
<label class="perf-check"><input type="checkbox" data-hide="{{ m.code }}"{% if m.code in hidden_codes %} checked{% endif %} /> {{ m.name }}</label>
{% endfor %}
</div>
<span class="perf-muted">체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다.</span>
</div>
</div>
{% endif %}
{% if is_admin and auto_sync_settings %}
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #}
{% set au = auto_sync_settings %}
{% macro time_select(part, value, label) -%}
{%- set hh, mm = value.split(':') -%}
<select class="erp-input perf-auto-time" data-t="{{ part }}-h" aria-label="{{ label }} 시">
{%- for h in range(24) %}<option value="{{ '%02d' % h }}"{% if '%02d' % h == hh %} selected{% endif %}>{{ '%02d' % h }}시</option>{% endfor -%}
</select><select class="erp-input perf-auto-time" data-t="{{ part }}-m" aria-label="{{ label }} 분">
{%- for m in range(0, 60, au.step) %}<option value="{{ '%02d' % m }}"{% if '%02d' % m == mm %} selected{% endif %}>{{ '%02d' % m }}분</option>{% endfor -%}
</select>
{%- endmacro %}
<div class="erp-card perf-card" id="perf-auto-sync">
<div class="perf-card-head">
<h2 class="perf-h">자동 업데이트</h2>
<span class="perf-muted">매출 실적·광고비를 고른 요일의 시작 ~ 끝 시각 사이에 정한 간격으로 자동으로 가져옵니다(오늘 포함 최근 {{ au.days }}일).
시각·간격은 {{ au.step }}분 단위이며, 저장하면 1분 안에 적용됩니다.</span>
</div>
{% if not au.env_on %}<div class="perf-notice is-warn">서버 환경변수 PERFORMANCE_AUTO_SYNC=false 로 자동 업데이트가 꺼져 있습니다 — 일정은 저장되지만 돌지 않습니다.</div>{% endif %}
{% if not au.ready %}<div class="perf-notice is-warn">일정 저장 표가 아직 없습니다. performance_db 마이그레이션 011
(scripts/sql/performance_db_011_settings.sql)을 적용해야 저장할 수 있습니다. 지금은 기본 일정(아래)으로 돕니다.</div>{% endif %}
{% if au.error %}<div class="perf-notice is-warn">{{ au.error }}</div>{% endif %}
<div class="perf-auto-rows">
{% for k in au.kinds %}{% set sc = k.schedule %}
<div class="perf-auto-row{% if not sc.enabled %} is-off{% endif %}" data-kind="{{ k.kind }}">
<div class="perf-auto-name">
<b>{{ k.name }}</b>
<label class="perf-auto-on"><input type="checkbox" data-f="enabled"{% if sc.enabled %} checked{% endif %} /> 사용</label>
</div>
<div class="perf-auto-fields">
<div class="perf-auto-field"><span class="perf-opt-label">요일</span>
<span class="perf-auto-days">
{%- for w in au.weekdays %}<label class="perf-day{% if loop.index0 == 5 %} is-sat{% elif loop.index0 == 6 %} is-sun{% endif %}"><input type="checkbox" data-day="{{ loop.index0 }}"{% if loop.index0 in sc.days %} checked{% endif %} /><span>{{ w }}</span></label>{% endfor -%}
</span>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="all">매일</button>
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-days="weekday">평일</button>
</div>
<div class="perf-auto-field"><span class="perf-opt-label">시간</span>
{{ time_select('start', sc.start, k.name ~ ' 시작') }}<span class="perf-muted">부터</span>
{{ time_select('end', sc.end, k.name ~ ' 끝') }}<span class="perf-muted">까지</span>
</div>
<div class="perf-auto-field"><span class="perf-opt-label">간격</span>
<input class="erp-input perf-auto-interval" type="number" min="{{ au.step }}" max="{{ au.max }}" step="{{ au.step }}"
data-f="interval" value="{{ sc.interval }}" aria-label="{{ k.name }} 간격(분)" /><span class="perf-muted">분마다</span>
</div>
</div>
<div class="perf-muted perf-auto-next" data-next>{{ k.label }}{% if k.next_at %} · 다음 {{ k.next_at[5:16] | replace('T', ' ') }}{% endif %}</div>
</div>
{% endfor %}
</div>
<div class="perf-auto-actions">
<button type="button" class="erp-btn erp-btn-primary" id="perf-auto-save">저장</button>
<span class="perf-muted" id="perf-auto-msg" role="status"></span>
</div>
</div>
{% endif %}
{% if is_admin %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
@@ -128,7 +256,7 @@
<div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
</div>
{% if not ad_api_ready %}
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
@@ -219,4 +347,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
+47 -13
View File
@@ -51,11 +51,12 @@ def test_rocket_report_reads_date_and_col19(content, name):
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" # 앞으로의 날짜
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) == 3, res.errors
assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" in joined
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():
@@ -120,22 +121,23 @@ 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"]
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
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 k["ytd"]["value"] == 370000 and "mtd" not in k # 월 누적 카드 뺌(2026-10-30)
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"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
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"][-1]
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"]}
@@ -144,7 +146,7 @@ def test_ad_dashboard_month():
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"] # 이번달
assert ctx["nav"]["quick"][0]["active"] # 이번달
def test_ad_dashboard_year_and_missing_table():
@@ -158,7 +160,7 @@ def test_ad_dashboard_year_and_missing_table():
def test_ad_spend_endpoints(monkeypatch):
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503."""
칸 저장(source=manual)·지우기·계산식, 모르는 채널 404, 앞으로의 날도 됨, 005 미적용 503."""
import importlib
from fastapi import FastAPI
@@ -179,7 +181,8 @@ def test_ad_spend_endpoints(monkeypatch):
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=""):
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()
@@ -208,7 +211,10 @@ def test_ad_spend_endpoints(monkeypatch):
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 == 400
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})
@@ -237,7 +243,33 @@ def test_naver_report_reads_date_cost_roas_and_metrics():
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n"
errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors)
assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs
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():
@@ -276,7 +308,9 @@ def test_naver_detail_table_totals():
{"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0,
"클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}]
t = ads.detail_table(rows)
assert t["columns"] == ["총비용", "노출수", "클릭수", "클릭률(%)", "구매완료 광고수익률(%)"]
# 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
+194 -16
View File
@@ -1,4 +1,4 @@
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
"""매출·광고비 자동 업데이트 — 일정(간격·요일·시작/끝)·회차 시각 계산·종류별 실행·건너뛰기."""
from __future__ import annotations
@@ -7,26 +7,122 @@ from datetime import date, datetime, timedelta, timezone
from app.modules.performance import auto_sync as au
KST = timezone(timedelta(hours=9))
H = (9, 19)
D = au.default_schedule() # 매일 09:00 ~ 19:00, 30분마다 (env 없을 때)
def _t(h, m, d=13):
def _t(h, m, d=13): # 2026-10-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)]
def _s(**kw):
return {**D, **kw}
def test_default_schedule_every_half_hour_9_to_19(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
assert au.default_schedule() == {"enabled": True, "interval": 30, "days": [0, 1, 2, 3, 4, 5, 6],
"start": "09:00", "end": "19:00"}
slots = [t for t in (_t(0, 0) + timedelta(minutes=5 * i) for i in range(288)) if au.is_slot(t, D)]
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)
assert not au.is_slot(_t(19, 30), D) and not au.is_slot(_t(8, 30), D) and not au.is_slot(_t(10, 15), D)
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20") # 일정 저장 전 기본 시간대 = env
assert au.default_schedule()["start"] == "08:00" and au.default_schedule()["end"] == "20:00"
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)
assert au.next_slot(_t(8, 10), D) == _t(9, 0)
assert au.next_slot(_t(9, 0), D) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), D) == _t(9, 30)
assert au.next_slot(_t(18, 45), D) == _t(19, 0)
assert au.next_slot(_t(19, 0), D) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
assert au.next_slot(_t(23, 59), D) == _t(9, 0, d=14)
def test_next_slot_custom_interval_window_weekdays():
s = _s(interval=25, start="08:35", end="10:00")
assert au.next_slot(_t(8, 0), s) == _t(8, 35)
assert au.next_slot(_t(8, 35), s) == _t(9, 0)
assert au.next_slot(_t(9, 40), s) == _t(9, 50) # 08:35 · 09:00 · 09:25 · 09:50 (10:15 는 끝 뒤)
assert au.next_slot(_t(9, 50), s) == _t(8, 35, d=14)
assert au.is_slot(_t(9, 25), s) and not au.is_slot(_t(10, 0), s)
assert au.is_slot(_t(10, 0), _s(interval=5, start="08:35", end="10:00")) # 끝 시각과 딱 맞으면 끝도 회차
weekdays = _s(days=[0, 1, 2, 3, 4])
assert au.next_slot(datetime(2026, 10, 16, 19, 0, tzinfo=KST), weekdays) == _t(9, 0, d=19) # 금 저녁 → 월 9시
assert not au.is_slot(datetime(2026, 10, 17, 10, 0, tzinfo=KST), weekdays) # 토요일
once = _s(start="07:05", end="07:05", days=[2]) # 수요일 07:05 한 번
assert au.next_slot(_t(7, 5), once) == datetime(2026, 10, 14, 7, 5, tzinfo=KST)
assert au.next_slot(datetime(2026, 10, 14, 7, 5, tzinfo=KST), once) == datetime(2026, 10, 21, 7, 5, tzinfo=KST)
assert au.next_slot(_t(9, 0), _s(enabled=False)) is None and au.next_slot(_t(9, 0), _s(days=[])) is None
assert au.next_slot(_t(9, 0), _s(interval=720, start="00:00", end="23:55")) == _t(12, 0)
def test_validate_schedule():
ok = au.validate_schedule({"enabled": True, "interval": "45", "days": [4, 0, 0], "start": "7:05", "end": "21:30"})
assert ok == {"enabled": True, "interval": 45, "days": [0, 4], "start": "07:05", "end": "21:30"}
assert au.validate_schedule({**D, "enabled": False, "days": []})["days"] == [] # 끈 일정은 요일 없어도 됨
import pytest
for bad, word in [({**D, "interval": 7}, "5분 단위"), ({**D, "interval": 0}, "간격"), ({**D, "interval": 725}, "간격"),
({**D, "interval": "x"}, "숫자"), ({**D, "days": []}, "요일을 하나"), ({**D, "days": [7]}, "요일"),
({**D, "days": [True]}, "요일"), ({**D, "start": "09:03"}, "5분 단위"), ({**D, "end": "24:00"}, "HH:MM"),
({**D, "start": "19:00", "end": "09:00"}, "끝 시각"), (None, "형식")]:
with pytest.raises(ValueError, match=word):
au.validate_schedule(bad)
def test_normalize_and_load_schedules():
from app.modules.performance.db import SettingsMigrationNeeded
saved = {"sales": _s(interval=10), "ads": {"interval": 3}} # 광고비 값이 깨짐 → 그 종류만 기본
n = au.normalize(saved)
assert n["sales"]["interval"] == 10 and n["ads"] == D
assert au.normalize(None) == {"sales": D, "ads": D}
class Store:
def __init__(self, value=None, missing=False):
self.value, self.missing = value, missing
def get_setting(self, key):
assert key == "auto_sync"
if self.missing:
raise SettingsMigrationNeeded()
return self.value
assert au.load_schedules(Store(saved)) == (n, True)
assert au.load_schedules(Store(missing=True)) == ({"sales": D, "ads": D}, False)
assert au.load_schedules(object()) == ({"sales": D, "ads": D}, True) # get_setting 없는 저장소
def test_describe():
assert au.describe(D) == "매일 09:00~19:00 · 30분마다"
assert au.describe(_s(days=[0, 1, 2, 3, 4], interval=90)) == "평일 09:00~19:00 · 1시간 30분마다"
assert au.describe(_s(days=[5, 6], interval=120)) == "주말 09:00~19:00 · 2시간마다"
assert au.describe(_s(days=[0, 2, 4], start="10:00", end="10:00")) == "월·수·금 10:00"
assert au.describe(_s(enabled=False)) == "꺼짐"
def test_scheduler_runs_each_kind_on_its_own_schedule():
fired = []
sch = au.Scheduler(lambda kind, due: fired.append((kind, due)))
schedules = {"sales": D, "ads": _s(interval=60, days=[0, 1, 2, 3, 4])}
sch.update(schedules, _t(9, 10)) # 시작 시각 회차는 안 돌림 — 다음부터
assert sch.due == {"sales": _t(9, 30), "ads": _t(10, 0)}
assert sch.wait_seconds(_t(9, 10)) == 60.0 and sch.wait_seconds(datetime(2026, 10, 13, 9, 29, 30, tzinfo=KST)) == 30.0
sch.tick(_t(9, 29))
assert fired == []
sch.tick(_t(9, 30))
assert fired == [("sales", _t(9, 30))] and sch.due["sales"] == _t(10, 0)
sch.tick(datetime(2026, 10, 13, 10, 0, 20, tzinfo=KST)) # 둘 다 10:00 → 둘 다(따로)
assert fired[1:] == [("sales", _t(10, 0)), ("ads", _t(10, 0))]
sch.tick(_t(11, 40)) # 밀린 회차(10:30·11:00·11:30)는 한 번만, 다음은 지금 뒤
assert fired[3:] == [("sales", _t(10, 30)), ("ads", _t(11, 0))]
assert sch.due == {"sales": _t(12, 0), "ads": _t(12, 0)}
sch.update(schedules, _t(11, 41)) # 일정 그대로 → due 그대로
assert sch.due["sales"] == _t(12, 0)
sch.update({**schedules, "sales": _s(interval=5)}, _t(11, 41)) # 매출 일정만 바뀜 → 매출만 지금부터 다시
assert sch.due == {"sales": _t(11, 45), "ads": _t(12, 0)}
sch.update({"sales": _s(interval=5), "ads": _s(enabled=False)}, _t(11, 41))
assert sch.due["ads"] is None and sch.due["sales"] == _t(11, 45)
def test_env_parsing(monkeypatch):
@@ -42,6 +138,30 @@ def test_env_parsing(monkeypatch):
assert au.hour_window() == (8, 20)
def test_run_once_only_given_kinds(monkeypatch):
"""종류마다 따로 회차(2026-10-26) — kinds=("ads",) 면 매출은 건드리지 않는다."""
from app.modules.performance import ad_sync, jobs
from app.modules.performance.sync import SyncService
sales = []
monkeypatch.setattr(SyncService, "sync_all", lambda self, **kw: sales.append(1) or [])
monkeypatch.setattr(ad_sync.AdSyncService, "sync_all", lambda self, start, end, *, user="", job=None: [])
monkeypatch.setattr(ad_sync, "ad_credentials", lambda store, ring: None)
monkeypatch.setattr(jobs, "running_job", lambda kind="sales": None)
class Store:
def last_update_at(self):
return None
def ad_source_statuses(self):
return {}
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("ads",))
assert sales == [] and res["sales_skipped"] and not res["ads_skipped"] and res["from"] == "2026-10-11"
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=3, kinds=("sales",))
assert sales == [1] and res["ads_skipped"] and not res["sales_skipped"]
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
from app.modules.performance import jobs
from app.modules.performance.sync import SyncService
@@ -57,13 +177,71 @@ def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
return "2026-10-13T09:00:05+09:00"
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
monkeypatch.setattr(jobs, "running_job", lambda: None)
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, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
"ads": []}
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: object())
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,108 @@
"""자동 업데이트 일정 설정(2026-10-26, 마이그레이션 011) — 저장 API(관리자·검증·011 미적용 503), 화면 카운트다운 값(종류별 일정)."""
from __future__ import annotations
import importlib
from datetime import datetime, timedelta, timezone
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import auto_sync, common
from app.modules.performance.db import SettingsMigrationNeeded
perf_router = importlib.import_module("app.modules.performance.router")
KST = timezone(timedelta(hours=9))
D = auto_sync.default_schedule()
class Store:
def __init__(self, value=None, missing=False):
self.value, self.missing, self.saved = value, missing, []
def get_setting(self, key):
if self.missing:
raise SettingsMigrationNeeded()
return self.value
def set_setting(self, key, value, *, user=""):
if self.missing:
raise SettingsMigrationNeeded()
self.saved.append((key, value, user))
self.value = value
@pytest.fixture
def client_store(monkeypatch):
st, calls = Store(), []
def fake_require(request, admin=False):
calls.append(admin)
return st, {"email": "admin@x"}
monkeypatch.setattr(common, "require_store", fake_require)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST)) # 금요일
app = FastAPI()
app.include_router(perf_router.router)
return TestClient(app), st, calls
def test_save_schedule(client_store):
c, st, calls = client_store
body = {"sales": {"enabled": True, "interval": 15, "days": [0, 1, 2, 3, 4], "start": "08:30", "end": "20:00"},
"ads": {"enabled": False, "interval": 60, "days": [], "start": "09:00", "end": "18:00"}}
r = c.put("/performance/api/auto-sync-schedule", json=body)
assert r.status_code == 200 and calls == [True] # 관리자만
j = r.json()
assert st.saved == [("auto_sync", body, "admin@x")]
assert j["sales"]["next_at"] == "2026-10-16T19:00:00+09:00" and j["sales"]["label"] == "평일 08:30~20:00 · 15분마다"
assert j["ads"]["next_at"] == "" and j["ads"]["label"] == "꺼짐" and j["env_on"]
def test_save_schedule_rejects_bad_values(client_store):
c, st, _ = client_store
bad = {"sales": {**D, "interval": 12}, "ads": D}
r = c.put("/performance/api/auto-sync-schedule", json=bad)
assert r.status_code == 400 and r.json()["detail"].startswith("매출 실적:") and "5분 단위" in r.json()["detail"]
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": {**D, "start": "20:00", "end": "08:00"}})
assert r.status_code == 400 and r.json()["detail"].startswith("광고비:")
assert c.put("/performance/api/auto-sync-schedule", json={"sales": D}).status_code == 400 # 광고비 일정 없음
assert st.saved == []
st.missing = True
r = c.put("/performance/api/auto-sync-schedule", json={"sales": D, "ads": D})
assert r.status_code == 503 and "011" in r.json()["detail"]
def test_countdown_ctx_per_kind(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
monkeypatch.setattr("app.timezone.now_kst", lambda: datetime(2026, 10, 16, 18, 50, tzinfo=KST))
st = Store({"sales": {**D, "interval": 5}, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00"}})
sales = perf_router._auto_sync_ctx(st, "sales")
assert sales["next_at"] == "2026-10-16T18:55:00+09:00" and sales["schedule"]["interval"] == 5
assert sales["label"] == "매일 09:00~19:00 · 5분마다" and sales["now"].startswith("2026-10-16T18:50:00")
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-16T19:00:00+09:00"
st.value = {"sales": D, "ads": {**D, "days": [0, 1, 2, 3, 4], "start": "10:00", "end": "10:00"}}
assert perf_router._auto_sync_ctx(st, "ads")["next_at"] == "2026-10-19T10:00:00+09:00" # 금 저녁 → 월 10시
st.value = {"sales": {**D, "enabled": False}, "ads": D}
assert perf_router._auto_sync_ctx(st, "sales") is None # 끈 종류는 카운트다운 숨김
st.missing = True
assert perf_router._auto_sync_ctx(st, "sales")["next_at"] == "2026-10-16T19:00:00+09:00" # 011 전 = 기본 일정
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
assert perf_router._auto_sync_ctx(st, "sales") is None
def test_settings_card_ctx(monkeypatch):
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
ctx = perf_router._auto_sync_settings_ctx(Store(missing=True))
assert not ctx["ready"] and ctx["env_on"] and [k["kind"] for k in ctx["kinds"]] == ["sales", "ads"]
assert ctx["kinds"][0]["schedule"] == D and ctx["step"] == 5
class Broken:
def get_setting(self, key):
raise RuntimeError("db down")
ctx = perf_router._auto_sync_settings_ctx(Broken())
assert ctx["ready"] and "RuntimeError" in ctx["error"] and ctx["kinds"][1]["schedule"] == D
@@ -0,0 +1,63 @@
"""날짜 칸 메모(2026-10-22, 마이그레이션 010) — API 규칙(종류·코드·길이·지우기·010 미적용 503), 매출·광고비 화면의 메모 표시, 기타광고비 채널."""
from __future__ import annotations
import importlib
from datetime import date
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import ad_spend, common
from app.modules.performance.db import MemoMigrationNeeded
perf_router = importlib.import_module("app.modules.performance.router")
class Store:
def __init__(self, missing=False):
self.saved, self.missing = [], missing
def list_marketplaces(self):
return [{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True, "manual_input": True}]
def set_cell_memo(self, kind, code, day, memo, *, user=""):
if self.missing:
raise MemoMigrationNeeded()
self.saved.append((kind, code, day, memo, user))
@pytest.fixture
def client_store(monkeypatch):
st = Store()
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (st, {"email": "me@x"}))
app = FastAPI()
app.include_router(perf_router.router)
return TestClient(app), st
def test_cell_memo_api(client_store):
c, st = client_store
r = c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": " 행사 매출 포함\r\n2차 정산 예정 "})
assert r.status_code == 200 and r.json()["memo"] == "행사 매출 포함\n2차 정산 예정"
assert st.saved[-1] == ("sales", "coupang", date(2026, 10, 5), "행사 매출 포함\n2차 정산 예정", "me@x")
r = c.put("/performance/api/cell-memos/ad/etc/2026-10-30", json={"memo": "전단지"}) # 기타광고비·앞날도 됨
assert r.status_code == 200 and st.saved[-1][:2] == ("ad", "etc")
assert c.put("/performance/api/cell-memos/ad/etc/2026-10-30", json={"memo": " "}).status_code == 200
assert st.saved[-1][3] is None # 빈 메모 = 지움
assert c.put("/performance/api/cell-memos/sales/nope/2026-10-05", json={"memo": "x"}).status_code == 404
assert c.put("/performance/api/cell-memos/ad/cafe24/2026-10-05", json={"memo": "x"}).status_code == 404 # 광고 채널 아님
assert c.put("/performance/api/cell-memos/other/coupang/2026-10-05", json={"memo": "x"}).status_code == 404
assert c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": "가" * 1001}).status_code == 400
st.missing = True
r = c.put("/performance/api/cell-memos/sales/coupang/2026-10-05", json={"memo": "x"})
assert r.status_code == 503 and "010" in r.json()["detail"]
def test_etc_channel_has_no_roas():
assert ad_spend.CHANNEL_CODES[-2:] == ("atomy", "etc") and ad_spend.CHANNEL_NAMES["etc"] == "기타광고비"
assert ad_spend.channel_roas("etc", lambda m: 1_000_000, 50_000) is None
assert ad_spend.roas_basis("etc") == ""
from app.modules.performance.dashboard import sales_ad_channels
assert not any(ch == "etc" for lines in sales_ad_channels().values() for ch, _ in lines) # 매출 탭 광고비 줄에 안 나옴
@@ -0,0 +1,382 @@
"""직접 추가 쇼핑몰(수동 입력 전용)·쇼핑몰 그룹·드래그 순서 (2026-10-22, 마이그레이션 009)."""
from __future__ import annotations
import importlib
from datetime import date
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from app.modules.performance import common, dashboard
from app.modules.performance.adapters.registry import get_adapter
from app.modules.performance.db import SettingsMigrationNeeded
TODAY = date(2026, 10, 7)
def _row(code, name, sort, **kw):
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
"manual_input": False, "is_custom": False, "is_group": False, "parent_code": None, **kw}
class _Store:
"""카페24 + 그룹 '오프라인'(하위 custom_a·custom_b) + 네이버 — 그룹은 순서상 네이버 뒤, 하위는 맨 앞 sort_order 여도 그룹 자리."""
def __init__(self):
self.rows = [
_row("custom_b", "매장B", 5, manual_input=True, is_custom=True, parent_code="group_x"),
_row("cafe24", "카페24", 10),
_row("naver", "네이버", 20),
_row("group_x", "오프라인", 30, is_custom=True, is_group=True, include_in_sales=False),
_row("custom_a", "매장A", 40, manual_input=True, is_custom=True, parent_code="group_x"),
_row("custom_c", "행사", 50, manual_input=True, is_custom=True),
]
self.manual = {(date(2026, 10, 5), "custom_a"): 100_000, (date(2026, 10, 5), "custom_b"): 50_000,
(date(2026, 10, 6), "custom_a"): 7_000}
self.order = None
self.deleted = []
self.settings = {}
def get_setting(self, key):
return self.settings.get(key)
def set_setting(self, key, value, *, user=""):
self.settings[key] = value
def list_marketplaces(self):
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
def daily_amounts(self, start, end, codes):
base = {(date(2026, 10, 5), "cafe24"): 1_000_000, **self.manual}
return {k: v for k, v in base.items() if start <= k[0] <= end and k[1] in codes}
def manual_amounts(self, start, end, codes, *, active_only=True):
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
def rate_table(self):
return {"custom_a": [(date(2000, 1, 1), 10)]}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
return {}, {}
# ── 009 쓰기 ──
def add_custom_marketplace(self, code, name, *, is_group):
row = _row(code, name, max(r["sort_order"] for r in self.rows) + 10, manual_input=not is_group,
include_in_sales=not is_group, is_custom=True, is_group=is_group)
self.rows.append(row)
return dict(row)
def _find(self, code):
return next(r for r in self.rows if r["code"] == code)
def rename_marketplace(self, code, name):
self._find(code)["name"] = name
return dict(self._find(code))
def set_marketplace_parent(self, code, parent):
self._find(code)["parent_code"] = parent
return dict(self._find(code))
def delete_custom_marketplace(self, code):
self.deleted.append(code)
for r in self.rows:
if r.get("parent_code") == code:
r["parent_code"] = None
self.rows = [r for r in self.rows if r["code"] != code]
return True
def manual_day_count(self, code):
return sum(1 for (_, c) in self.manual if c == code)
def reorder_marketplaces(self, codes):
self.order = list(codes)
for i, c in enumerate(codes):
self._find(c)["sort_order"] = (i + 1) * 10
def test_custom_code_gets_manual_only_adapter_and_group_has_none():
a = get_adapter("custom_1234abcd")
assert a is not None and a.manual_only and a.code == "custom_1234abcd"
assert get_adapter("group_1234abcd") is None and get_adapter("nope") is None
assert get_adapter("cafe24").code == "cafe24"
def test_ordered_children_follow_group():
codes = [m["code"] for m in dashboard.ordered_marketplaces(_Store().list_marketplaces())]
assert codes == ["cafe24", "naver", "group_x", "custom_b", "custom_a", "custom_c"]
def test_dashboard_group_column_sums_children_without_double_count():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [
("cafe24", "shop"), (dashboard.CAFE24_EX_GB, "diff"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"),
("custom_a", "child"), ("custom_c", "shop")]
assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]}
assert ctx["names"]["group_x"] == "오프라인"
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
# 그룹 = 매장B 50,000 + 매장A 100,000(수수료 10% = 10,000)
assert day5["cells"]["group_x"] == {"gross": 150_000, "commission": 10_000, "net": 140_000}
assert day5["total"]["gross"] == 1_150_000 # 일 합계에 그룹을 또 더하지 않음
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert week["cells"]["group_x"]["gross"] == 157_000
def test_dashboard_filter_hides_group_when_no_child_selected():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"])
assert [c["code"] for c in ctx["cols"]] == ["cafe24", dashboard.CAFE24_EX_GB, "custom_c"] and ctx["group_members"] == {}
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"])
assert [c["kind"] for c in ctx["cols"]] == ["group", "child"]
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["cells"]["group_x"]["gross"] == 100_000 # 보이는 하위만 합침
def test_settings_blocks_group_children_together():
ctx = dashboard.build_settings(_Store(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
assert [(b["row"]["code"], [c["code"] for c in b["children"]]) for b in ctx["blocks"]] == [
("cafe24", []), ("naver", []), ("group_x", ["custom_b", "custom_a"]), ("custom_c", [])]
grp = ctx["blocks"][2]["row"]
assert grp["is_group"] and grp["children"] == 2
a = ctx["blocks"][2]["children"][1]
assert a["is_custom"] and a["manual_only"] and a["parent"] == "group_x" and a["status"] == "manual"
assert ctx["groups"] == [{"code": "group_x", "name": "오프라인"}] and ctx["custom_ready"]
@pytest.fixture()
def client(monkeypatch):
perf_router = importlib.import_module("app.modules.performance.router")
store = _Store()
class _Creds:
def configured_codes(self, adapters):
return {}
user = {"email": "king@x", "name": "King", "is_admin": True}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, user))
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)
c = TestClient(app)
c.store = store
return c
def test_api_add_rename_group_delete(client):
store = client.store
r = client.post("/performance/api/marketplaces", json={"kind": "shop", "name": " 새 매장 "})
assert r.status_code == 200, r.text
m = r.json()["marketplace"]
assert m["code"].startswith("custom_") and m["name"] == "새 매장" and m["manual_input"] and m["is_custom"]
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": "카페24"}).status_code == 400
assert client.post("/performance/api/marketplaces", json={"kind": "shop", "name": ""}).status_code == 400
g = client.post("/performance/api/marketplaces", json={"kind": "group", "name": "온라인B"}).json()["marketplace"]
assert g["code"].startswith("group_") and g["is_group"] and not g["include_in_sales"]
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": g["code"]}).status_code == 200
assert store._find(m["code"])["parent_code"] == g["code"]
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": "cafe24"}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"parent_code": "group_x"}).status_code == 400
assert client.put("/performance/api/marketplaces/cafe24", json={"name": "자사몰"}).status_code == 400
assert client.put("/performance/api/marketplaces/cafe24", json={"parent_code": "group_x"}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"name": "온라인C"}).json()["marketplace"]["name"] == "온라인C"
assert client.put(f"/performance/api/marketplaces/{g['code']}", json={"enabled": False}).status_code == 400
assert client.put(f"/performance/api/marketplaces/{m['code']}", json={"parent_code": ""}).status_code == 200
assert store._find(m["code"])["parent_code"] is None
assert client.get("/performance/api/marketplaces/custom_a/manual-days").json() == {"days": 2}
assert client.delete("/performance/api/marketplaces/cafe24").status_code == 400
assert client.delete("/performance/api/marketplaces/group_x").status_code == 200
assert store._find("custom_a")["parent_code"] is None and store.deleted == ["group_x"]
def test_api_manual_sale_accepts_custom_shop(client):
calls = []
client.store.set_manual_sale = lambda code, d, amount, user="", formula=None: calls.append((code, d, amount))
client.store.api_amount = lambda code, d: 0
r = client.put("/performance/api/manual-sales/custom_a/2026-10-07", json={"amount": "1000+2000"})
assert r.status_code == 200, r.text
assert calls == [("custom_a", date(2026, 10, 7), 3000)] and r.json()["commission"] == 300
assert client.put("/performance/api/manual-sales/group_x/2026-10-07", json={"amount": "1"}).status_code == 404
def test_api_order(client):
order = ["naver", "cafe24", "group_x", "custom_a", "custom_b", "custom_c"]
assert client.put("/performance/api/marketplace-order", json={"codes": order + ["ghost"]}).status_code == 200
assert client.store.order == order
assert client.put("/performance/api/marketplace-order", json={"codes": ["naver", "naver"]}).status_code == 400
ctx = dashboard.build_dashboard(client.store, kind="week", anchor=TODAY, today=TODAY)
assert ctx["codes"] == ["naver", "cafe24", "custom_a", "custom_b", "custom_c"]
def test_dashboard_page_renders_group_header_and_child_cells(client):
html = client.get("/performance/?period=week&d=2026-10-07").text
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert 'data-group-head="group_x"' in head and 'data-group-toggle="group_x"' in head and "오프라인" in head
assert head.index('data-group-head="group_x"') < head.index('data-group-child="group_x"')
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
assert 'data-group-cell="group_x"' in body and "150,000" in body
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
def _real(ctx, date_iso):
return next(r for r in ctx["table"] if r.get("date") == date_iso)["cells"][dashboard.CAFE24_EX_GB]
def test_cafe24_real_column():
"""카페24(실적) = 카페24(전체) 바로 오른쪽, 카페24 − 자사몰(공동구매). 표 열만 — 일 합계엔 안 더함."""
st = _Store()
# 공동구매 없음 = 전체 그대로
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000
assert ctx["short_names"]["cafe24"] == "카페24(전체)" and ctx["short_names"][dashboard.CAFE24_EX_GB] == "카페24(실적)"
st._find("custom_c")["name"] = "자사몰 (공동구매)"
st._find("custom_c")["parent_code"] = "group_x"
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
assert [c["code"] for c in ctx["cols"]][:2] == ["cafe24", dashboard.CAFE24_EX_GB]
assert ctx["cols"][1] == {"code": dashboard.CAFE24_EX_GB, "kind": "diff", "group": "", "base": "cafe24", "minus": "custom_c"}
assert _real(ctx, "2026-10-05") == {"gross": 700_000, "commission": 0, "net": 700_000}
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
# 일 합계 = 카페24(실적) 700,000 + 공동구매 300,000 + 매장 150,000 — 카페24(전체) 1,000,000 은 안 더함
assert day5["total"] == {"gross": 1_150_000, "commission": 10_000, "net": 1_140_000}
week = next(r for r in ctx["table"] if r["kind"] == "week")
assert week["cells"][dashboard.CAFE24_EX_GB]["gross"] == 700_000
assert week["total"]["gross"] == 1_157_000 # 주간합계도 같은 규칙(매장 157,000)
# 공동구매를 필터로 빼도 실적에서는 뺀다 — 일 합계 = 실적 + 나머지
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["cafe24"])
assert _real(ctx, "2026-10-05")["gross"] == 700_000
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 700_000
# 카페24 를 고르지 않으면 열 없음, 일 합계에 공동구매 그대로
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["custom_c"])
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 300_000
def test_summaries_match_day_total():
"""KPI·추이·비중·월/연 누적도 일 합계와 같은 기준 — 공동구매가 두 번 안 들어감, 카페24 줄 = 카페24(실적)."""
st = _Store()
st._find("custom_c")["name"] = "자사몰(공동구매)"
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
week_total = next(r for r in ctx["table"] if r["kind"] == "week")["total"]
assert week_total["gross"] == 1_157_000 # 카페24(전체) 1,000,000 + 매장 157,000
assert ctx["kpis"][0]["value"] == week_total["net"]
assert next(p for p in ctx["chart_daily"] if p["date"] == "2026-10-05")["gross"] == 1_150_000
assert sum(s["gross"] for s in ctx["chart_share"]) == 1_157_000
assert next(s for s in ctx["chart_share"] if s["code"] == "cafe24")["name"] == "카페24(실적)"
assert ctx["month"]["total"]["gross"] == 1_157_000 and ctx["year"]["total"]["gross"] == 1_157_000
assert next(r for r in ctx["month"]["rows"] if r["code"] == "cafe24")["gross"] == 700_000
assert ctx["year"]["rows"][9]["gross"] == 1_157_000
# 카페24(전체) 열은 원래 값 그대로, 공동구매 열도 그대로
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["cells"]["cafe24"]["gross"] == 1_000_000 and day5["cells"]["custom_c"]["gross"] == 300_000
def test_total_sales_codes_drops_groupbuy_only_with_cafe24():
m = lambda c, n: {"code": c, "name": n} # noqa: E731
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("x", "자사몰 (공동구매)"), m("y", "네이버")]) == ["cafe24", "y"]
assert dashboard.total_sales_codes([m("x", "자사몰(공동구매)"), m("y", "네이버")]) == ["x", "y"]
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("y", "네이버")]) == ["cafe24", "y"]
def test_day_total_roas_uses_real_total():
"""일 합계 ROAS = 일 합계 금액(공동구매 중복 없음) ÷ 일 합계 광고비."""
st = _Store()
st._find("custom_c")["name"] = "자사몰(공동구매)"
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
st.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 115_000}, {})
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["ads_total"]["amount"] == 115_000 and day5["ads_total"]["roas"] == 1000 # 1,150,000 ÷ 115,000
def test_hidden_columns_only_hide_table_columns():
"""열 숨기기(모든 사용자 공통 설정) — 열만 숨김, 일 합계·그래프 그대로. 하위를 다 숨기면 그룹 열도 없음."""
st = _Store()
st.settings[dashboard.HIDDEN_SETTING] = ["cafe24", "custom_a", "custom_b"]
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
assert [c["code"] for c in ctx["cols"]] == [dashboard.CAFE24_EX_GB, "naver", "custom_c"]
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000 # 전체를 숨겨도 실적은 계산됨
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 1_150_000
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
st.settings[dashboard.HIDDEN_SETTING] = [dashboard.CAFE24_EX_GB]
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
def test_hidden_setting_missing_migration_shows_everything():
st = _Store()
def raises(key):
raise SettingsMigrationNeeded()
st.get_setting = raises
assert dashboard.load_hidden(st) == set()
assert "naver" in [c["code"] for c in dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)["cols"]]
def test_api_hidden_marketplaces(client):
"""저장값이 그대로 다른 사용자 화면에도 — 쿠키가 아니라 서버 설정(모르는 코드는 버림)."""
r = client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver", "ghost", dashboard.CAFE24_EX_GB, "naver"]})
assert r.status_code == 200 and r.json()["codes"] == [dashboard.CAFE24_EX_GB, "naver"]
assert client.store.settings[dashboard.HIDDEN_SETTING] == [dashboard.CAFE24_EX_GB, "naver"]
head = TestClient(client.app).get("/performance/?period=week&d=2026-10-07").text.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert 'data-col="naver"' not in head and 'data-col="cafe24"' in head
assert client.put("/performance/api/hidden-marketplaces", json={"codes": "naver"}).status_code == 400
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).json()["codes"] == []
def raises(key, value, *, user=""):
raise SettingsMigrationNeeded()
client.store.set_setting = raises
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).status_code == 503
def test_api_hidden_marketplaces_admin_only(client, monkeypatch):
def require_store(request, admin=False):
if admin:
raise HTTPException(status_code=403)
return client.store, {"email": "u@x"}
monkeypatch.setattr(common, "require_store", require_store)
assert client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver"]}).status_code == 403
assert dashboard.HIDDEN_SETTING not in client.store.settings
def test_dashboard_page_renders_cafe24_real(client):
client.store._find("custom_c")["name"] = "자사몰(공동구매)"
client.store.manual[(date(2026, 10, 5), "custom_c")] = 300_000
client.store.settings[dashboard.HIDDEN_SETTING] = ["naver"]
html = client.get("/performance/?period=week&d=2026-10-07").text
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
# 날짜 → 일 합계 → 카페24(전체) → 카페24(실적)
assert head.index('data-col="label"') < head.index('data-col="total"') < head.index('data-col="cafe24"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"')
assert "카페24(전체)" in head and "카페24(실적)" in head and 'data-col="naver"' not in head
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
assert "700,000" in body
# 일 행만 화면 즉시 계산용 값(카페24 총매출,수수료,차감) — performance.js saveManual
assert 'data-diff-minus="custom_c" data-base="1000000,0,1000000"' in body
def test_cafe24_real_shows_same_ad_lines(client):
"""카페24(전체)의 구글·메타 광고비 줄이 카페24(실적) 칸에도 그대로."""
client.store.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 11_000, (date(2026, 10, 5), "meta"): 22_000}, {})
body = client.get("/performance/?period=week&d=2026-10-07").text.split("<tbody>", 1)[1]
row = next(tr for tr in body.split("<tr ") if 'data-date="2026-10-05"' in tr)
assert row.count("<i>구글</i>11,000") == 2 and row.count("<i>메타</i>22,000") == 2
assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"")
@@ -65,8 +65,8 @@ def test_ad_lines_under_sales_cells():
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합
assert day5["ads_total"] == {"amount": 350_000, "roas": 743} # 2,600,000 ÷ 350,000
# 일 합계 = 보이는 쇼핑몰 광고비 합, 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")
@@ -78,7 +78,7 @@ def test_ad_lines_under_sales_cells():
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}
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"]) # 광고비 표 없어도 매출 화면은 그대로
@@ -121,10 +121,116 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
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")
# 매출 단위 = 서버 공통 설정(2026-11-02) — 예전 브라우저 쿠키는 안 봄
client.cookies.set("perf_unit", "million")
assert "단위:" not in client.get("/performance/?period=week&d=2026-10-07").text
client.cookies.delete("perf_unit")
store.get_setting = lambda key: "thousand" if key == dashboard.UNIT_SETTING else None
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")
store.get_setting = lambda key: "million" if key == dashboard.UNIT_SETTING else None
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_api_display_unit(monkeypatch):
import importlib
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router")
saved = {}
store = _Store()
store.set_setting = lambda key, value, *, user="": saved.__setitem__(key, (value, user))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
assert client.put("/performance/api/display-unit", json={"unit": "thousand"}).json()["unit"] == "thousand"
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
assert client.put("/performance/api/display-unit", json={"unit": "nope"}).status_code == 400
assert client.put("/performance/api/display-unit", json={"unit": ["won"]}).status_code == 400
def not_admin(request, admin=False):
if admin:
raise HTTPException(status_code=403)
return store, {"email": "u@x"}
monkeypatch.setattr(common, "require_store", not_admin)
assert client.put("/performance/api/display-unit", json={"unit": "won"}).status_code == 403
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
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) 뒤 날짜도 입력 칸
@@ -0,0 +1,28 @@
"""날짜 칸 계산식(formula.parse_amount) — = 없이 1000+2000 을 바로 계산(2026-10-21)."""
from __future__ import annotations
import pytest
from app.modules.performance.formula import FormulaError, parse_amount
@pytest.mark.parametrize("raw, expected", [
("", (None, None)), (None, (None, None)), (" ", (None, None)),
("12,000", (12000, None)), (87000, (87000, None)), ("-5000", (-5000, None)), ("1,234원", (1234, None)),
("1000+2000", (3000, "1000+2000")),
("1,000 + 2,000 * 2", (5000, "1000+2000*2")),
("(10000+5000)×2", (30000, "(10000+5000)*2")),
("10000÷3", (3333, "10000/3")),
("10001/2", (5001, "10001/2")), # 반올림
("=500-200", (300, "500-200")), # 엑셀 버릇 = 도 됨
("-100+50", (-50, "-100+50")),
("1.5*1000", (1500, "1.5*1000")),
])
def test_parse_amount(raw, expected):
assert parse_amount(raw) == expected
@pytest.mark.parametrize("raw", ["abc", "1000+", "*5", "(1+2", "1+2)", "5/0", "1e5", "1000+2000a", "1" * 201])
def test_parse_amount_errors(raw):
with pytest.raises(FormulaError):
parse_amount(raw)
@@ -315,3 +315,93 @@ def test_sync_endpoint(monkeypatch):
svc.conf = {"google": False}
r = client.post("/performance/api/ad-sources/google/sync", json={})
assert r.status_code == 400 and "설정" in r.json()["detail"]
def test_sync_all_with_job_reports_channel_progress(monkeypatch):
"""[광고비 업데이트](2026-10-20) — 채널별 진행 막대: 완료(일·광고비)·실패·중지(저장 안 함)."""
from app.modules.performance import jobs
from app.modules.performance.ad_sources.base import AdDay
store = FakeStore()
src = ga.GoogleAdsSource()
monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, None, {}),
AdDay(date(2026, 10, 2), 2000, None, {})])
monkeypatch.setattr(ad_sync, "get_source", lambda code: src)
svc = _service(store, src)
job = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 2), user="king@x", job=job)
assert res[0]["ok"] and job.kind == "ads"
shop = job.snapshot()["shops"][0]
assert shop["state"] == "done" and shop["upserted"] == 2 and shop["message"] == "광고비 ₩3,000" and shop["fraction"] == 1.0
# 수집 뒤 저장 직전에 [중지] → 저장하지 않음
job2 = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
def fetch_then_stop(ctx, s, e):
job2.stop_shop("google")
return [AdDay(date(2026, 10, 1), 1000, None, {})]
monkeypatch.setattr(src, "fetch_days", fetch_then_stop)
before = len(store.replaced)
res = svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job2)
assert res[0].get("cancelled") and len(store.replaced) == before
assert job2.snapshot()["shops"][0]["state"] == "cancelled"
# 실패 → 막대에 오류(상태·문구)
def boom(ctx, s, e):
raise AuthFailed("거부")
monkeypatch.setattr(src, "fetch_days", boom)
job3 = jobs.create_job(user="king@x", start=None, end=None, kind="ads")
svc.sync_all(date(2026, 10, 1), date(2026, 10, 1), job=job3)
s3 = job3.snapshot()["shops"][0]
assert s3["state"] == "error" and s3["status"] == "auth_failed"
for j in (job, job2, job3):
j.finish()
def test_ad_sync_job_endpoint(monkeypatch):
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common, jobs
perf_router = importlib.import_module("app.modules.performance.router")
ran = []
class Svc:
conf = {"google": True, "meta": False}
def configured(self):
return self.conf
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"}))
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15))
monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, Svc()))
monkeypatch.setattr(ad_sync, "run_ad_job", lambda store, ring, job, s, e, user="": ran.append((job.id, s, e, user)))
app = FastAPI()
app.include_router(perf_router.router)
client = TestClient(app)
assert client.get("/performance/api/ad-sync/current").json() == {"job": None}
r = client.post("/performance/api/ad-sync", json={"from": "2026-10-01", "to": "2026-10-31"})
body = r.json()
assert r.status_code == 200 and not body["joined"] and body["job"]["kind"] == "ads"
assert body["job"]["to"] == "2026-10-15" # 오늘 뒤는 잘라냄
import time
for _ in range(50):
if ran:
break
time.sleep(0.02)
assert ran and ran[0][1:] == (date(2026, 10, 1), date(2026, 10, 15), "king@x")
# 진행 중이면 새로 시작하지 않고 합류(매출 업데이트와 별개)
r = client.post("/performance/api/ad-sync", json={})
assert r.json()["joined"] and r.json()["job"]["id"] == body["job"]["id"]
assert client.get("/performance/api/ad-sync/current").json()["job"]["id"] == body["job"]["id"]
assert jobs.running_job("sales") is None or jobs.running_job("sales").kind == "sales"
jobs.get_job(body["job"]["id"]).finish()
Svc.conf = {"google": False}
r = client.post("/performance/api/ad-sync", json={})
assert r.status_code == 400 and "광고 API" in r.json()["detail"]
@@ -64,14 +64,14 @@ def test_errors_reject_everything_with_cell_refs():
("날짜", "쿠팡(로켓)", "오늘의집"),
("2026-10-10", "abc", 100),
("엉터리", 1, None),
("2026-10-14", 1, None), # 앞으로의 날짜
("2026-10-14", 1, None), # 앞으로의 날짜 — 됨(2026-10-21)
(None, 5, None), # 날짜 없음
("2026-10-11", 7, None),
("2026-10-11", 8, None), # 같은 날 두 번
])
joined = "\n".join(res.errors)
assert "B2" in joined and "A3" in joined and "A4" in joined and "5행" in joined and "B7" in joined
assert len(res.errors) == 5
assert "B2" in joined and "A3" in joined and "A4" not in joined and "5행" in joined and "B7" in joined
assert len(res.errors) == 4
def test_header_problems():
@@ -499,3 +499,36 @@ def test_connection_mentions_conversion(monkeypatch):
"account_status": 1}))
msg = ma.MetaAdsSource().test_connection(_ctx(account_ids="333333"))
assert "그날 환율로 원화로 바꿔 넣습니다" in msg and "가져올 수 없습니다" not in msg
def test_period_zero_spend_refetches_single_days(monkeypatch):
"""2026-10-21 운영 — 기간으로 물으면 메타가 지출·노출·클릭을 0 으로(링크 클릭·구매는 정상) 주고, 하루만 물으면 정상.
그런 날만 하루씩 다시 물어 바꾼다. 집행 없는 계정(행 없음)·진짜 0 인 날(링크 클릭·구매도 0)은 다시 묻지 않는다."""
real = {"2026-10-19": ("700000", "25000", "900"), "2026-10-20": ("817212", "29103", "983")}
def handler(request: httpx.Request) -> httpx.Response:
tr = json.loads(request.url.params["time_range"])
if "1111111111" not in str(request.url):
return httpx.Response(200, json={"data": []}) # 집행 없는 계정
if tr["since"] == tr["until"]: # 하루 조회 = 정상 값
spend, impr, clicks = real[tr["since"]]
return httpx.Response(200, json={"data": [_row(tr["since"], spend, impressions=impr, clicks=clicks,
inline_link_clicks="941",
actions=[{"action_type": "omni_purchase", "value": "50"}],
action_values=[{"action_type": "omni_purchase", "value": "2713820"}])]})
rows = [_row(d, "0", impressions="0", clicks="0", inline_link_clicks="941", # 기간 조회 = 핵심 칸 0
actions=[{"action_type": "omni_purchase", "value": "50"}],
action_values=[{"action_type": "omni_purchase", "value": "2713820"}]) for d in real]
rows.append(_row("2026-10-21", "0", impressions="0", clicks="0", inline_link_clicks="0")) # 진짜 0 인 날
return httpx.Response(200, json={"data": rows})
seen = _install(monkeypatch, handler)
days = {d.day.isoformat(): d for d in ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 19), date(2026, 10, 21))}
assert days["2026-10-20"].amount == 817212 and days["2026-10-20"].metrics["노출수"] == 29103
assert days["2026-10-20"].metrics["클릭수"] == 983 and days["2026-10-20"].roas == Decimal("332.08")
assert days["2026-10-19"].amount == 700000
assert days["2026-10-21"].amount == 0
singles = [json.loads(r.url.params["time_range"]) for r in seen]
singles = [t["since"] for t in singles if t["since"] == t["until"]]
assert sorted(singles) == ["2026-10-19", "2026-10-20"] # 이상한 날만, 계정 1 에만
assert len(seen) == 2 + 2 # 기간 2(계정 2개) + 하루 2
@@ -187,7 +187,8 @@ def test_main_table_month_and_year():
cells = _cells_for(list(calc.daterange(p.start, p.end)), ["a"])
rows = calc.main_table(p, ["a"], cells, today=date(2026, 9, 30))
weeks = [r for r in rows if r["kind"] == "week"]
assert rows[-1]["kind"] == "total" and rows[-1]["total"]["gross"] == 300_000
assert rows[0]["kind"] == "total" and rows[0]["total"]["gross"] == 300_000 # 기간 합계 = 맨 위(2026-10-21)
assert rows[1]["kind"] == "day" and rows[-1]["kind"] == "week"
assert sum(w["total"]["gross"] for w in weeks) == 300_000
assert weeks[0]["from"] == "2026-09-01" and weeks[0]["to"] == "2026-09-06" # 첫 주는 월 시작부터
y = calc.resolve_period("year", date(2026, 9, 10))
@@ -909,7 +910,7 @@ def test_cafe24_refund_total_includes_points_and_naverpay_cancels():
finally:
_tz.today_kst = orig
by = {e.external_event_id: e for e in events if e.event_type != "SALE"}
assert by["c24:C20260926-01"].amount == -(63_720 + 1_080) # 적립금 환불 포함
assert by["c24:C20260926-01"].amount == -63_720 # 적립금 환불(1,080)은 뺀다(2026-10-19 — 매출도 적립금 제외)
assert by["c24:NP1-01-CL"].amount == -55_800 and by["c24:NP1-01-CL"].event_type == "CANCEL"
assert by["c24:NP1-01-CL"].event_date == date(2026, 9, 26) and by["c24:NP1-01-CL"].marketplace_code == "cafe24"
assert by["c24:NP2-01-CL"].amount == -(40_000 - 1_000 + 3_000) # 판매가×수량 − 품목 쿠폰 + 전체취소 배송비
@@ -975,7 +976,8 @@ def test_cafe24_paid_total_matches_daily_report():
o["initial_order_amount"].update(payment_amount="42938.00", points_spent_amount="1000.00")
assert order_total(o) == 42_938 + 1_000 + 3_000 == 46_938
ev = _FakeCafe24([]).normalize_order(o)[0]
assert ev.amount == 46_938 and ev.discount_amount == 1_000 + 5_000
assert ev.amount == 46_938 - 1_000 and ev.discount_amount == 1_000 + 5_000 # 매출 = 결제합계 − 적립금(2026-10-19)
assert ev.raw["points"] == 1_000 and ev.raw["points_excluded"]
o["actual_order_amount"] = {**o["initial_order_amount"], "payment_amount": "20000.00"}
assert order_total_now(o) == 20_000 + 1_000 + 3_000
z = _c24_order("Z")
@@ -1509,7 +1511,16 @@ def test_naver_collect_sales():
}
calls = []
refunds = { # 클레임 완료일 기준 조회 — 9/10 에 B1(9/9 결제) 취소 완료·C2 반품 완료, 교환은 환불 아님
"2026-09-10": [_naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED"),
_naver_item("C", "C2", "2026-09-10", 7000, status="RETURNED"),
_naver_item("E", "E1", "2026-08-30", 3000, status="EXCHANGED")]}
def get(url, params=None, headers=None, timeout=None):
if params["rangeType"] == "CLAIM_COMPLETED_DATETIME":
calls.append(("claim", params["from"][:10]))
return httpx.Response(200, json={"data": {"contents": refunds.get(params["from"][:10], []),
"pagination": {"page": params["page"], "hasNext": False}}})
key = (params["from"][:10], params["page"])
calls.append(key)
rows, more = pages.get(key, ([], False))
@@ -1530,12 +1541,18 @@ def test_naver_collect_sales():
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "naver"}
assert set(ev_) == {"naver:A", "naver:B", "naver:C"} # D 미입금취소만 제외
assert ev_["naver:A"]["amount"] == 20000 + 5000 # 배송비 제외
assert set(ev_) == {"naver:A", "naver:B", "naver:C", "naver:B1-RF", "naver:C2-RF"} # D 미입금취소만 제외, 교환은 환불 아님
# 판매금액 + 배송비(2026-10-19) — 배송비는 배송 묶음(여기선 주문)마다 한 번(상품주문마다 반복돼 와도), 할인은 빼지 않음
assert ev_["naver:A"]["amount"] == 20000 + 5000 + 3000
assert ev_["naver:A"]["raw"] == {"goods": 25000, "ship": 3000}
assert ev_["naver:B"]["amount"] == 9900 # 결제 뒤 취소도 결제일 매출(판매금액(총))
# 환불은 환불된 날(클레임 완료일)에 뺀다 — 결제일(9/9)이 아니라 9/10
assert (ev_["naver:B1-RF"]["amount"], ev_["naver:B1-RF"]["sales_date"], ev_["naver:B1-RF"]["event_type"]) == (-9900, date(2026, 9, 10), "CANCEL")
assert (ev_["naver:C2-RF"]["amount"], ev_["naver:C2-RF"]["event_type"], ev_["naver:C2-RF"]["raw"]["refund"]) == (-7000, "RETURN", 7000)
assert ("claim", "2026-09-09") in calls and ("claim", "2026-09-10") in calls
assert ev_["naver:A"]["quantity"] == 3 and ev_["naver:A"]["discount_amount"] == 1000
assert ev_["naver:A"]["sales_date"] == date(2026, 9, 9) and ev_["naver:A"]["product_name"] == "밀폐용기 외 1건"
assert ev_["naver:C"]["amount"] == 15000 + 7000 # 반품 줄도 포함
assert ev_["naver:C"]["amount"] == 15000 + 7000 + 3000 # 반품 줄도 포함, 배송비 할인(조건부 무료)도 판매분석처럼 배송비에 넣음
assert ev_["naver:C"]["order_status"] == "구매확정/반품"
assert ("2026-09-09", 2) in calls and ("2026-09-10", 2) not in calls # hasNext 일 때만 다음 쪽
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
@@ -1598,6 +1615,8 @@ def test_sync_job_progress():
def get(url, params=None, headers=None, timeout=None):
day = params["from"][:10]
if params["rangeType"] != "PAYED_DATETIME": # 환불(클레임 완료일) 조회 — 이 테스트엔 없음
return httpx.Response(200, json={"data": {"contents": [], "pagination": {"hasNext": False}}})
if day == "2026-09-10": # 둘째 날을 받는 중 — 진행 상황 중간 모습
mid.update(job.snapshot())
rows = [_naver_item("A" + day, "P" + day, day, 10000), _naver_item("B" + day, "Q" + day, day, 5000)]
@@ -1618,14 +1637,15 @@ def test_sync_job_progress():
job.finish(last_update_at="2026-09-30T10:00:00")
m = {s["code"]: s for s in mid["shops"]}
assert m["naver"]["state"] == "running" and (m["naver"]["done"], m["naver"]["total"], m["naver"]["unit"]) == (1, 2, "일")
assert m["naver"]["items"] == 2 and m["naver"]["fraction"] == 0.5
assert mid["overall"]["shops"] == 1 and mid["overall"]["fraction"] == 0.5 and not mid["finished"]
# 네이버 = 하루에 결제·환불 두 번 조회(2026-10-19) — 2일 = 4단계
assert m["naver"]["state"] == "running" and (m["naver"]["done"], m["naver"]["total"], m["naver"]["unit"]) == (1, 4, "일 조회")
assert m["naver"]["items"] == 2 and m["naver"]["fraction"] == 0.25
assert mid["overall"]["shops"] == 1 and mid["overall"]["fraction"] == 0.25 and not mid["finished"]
snap = job.snapshot()
s = {x["code"]: x for x in snap["shops"]}
assert s["naver"]["state"] == "done" and s["naver"]["upserted"] == 4 and s["naver"]["items"] == 4
assert s["naver"]["done"] == s["naver"]["total"] == 2 and s["naver"]["fraction"] == 1.0
assert s["naver"]["done"] == s["naver"]["total"] == 4 and s["naver"]["fraction"] == 1.0
assert s["ohouse"]["state"] == "error" and s["ohouse"]["status"] in ("not_implemented", "not_configured")
assert not s["ohouse"]["active"]
assert s["elevenst"]["state"] == "error" and s["elevenst"]["status"] == "not_configured" and not s["elevenst"]["active"]
@@ -2061,8 +2081,22 @@ if __name__ == "__main__":
print(f"{n} tests passed")
def test_manual_input_marketplaces_skip_sync_even_with_api():
"""설정에서 수동 입력을 켠 쇼핑몰은 API 가 설정돼 있어도 매출 업데이트(수동·자동·과거 매출)에서 빠진다."""
st = FakeStore()
for m in st.markets:
m["manual_input"] = m["code"] == "naver"
svc = SyncService(st, CredentialService(st, lambda: ring()))
called = []
svc.sync_marketplace = lambda code, *a, **kw: called.append(code) or {"code": code}
svc.sync_all(start=date(2026, 10, 1), end=date(2026, 10, 2), user="king@x")
assert "naver" not in called and "cafe24" in called
svc.sync_all(start=date(2026, 10, 1), end=date(2026, 10, 2), codes=["naver"], trigger="schedule")
assert called.count("naver") == 0
def test_manual_sale_api_rules():
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503.
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 앞날도 됨, 숫자(쉼표 허용)·계산식, 비우면 지움, 002 미적용이면 503.
켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다."""
from fastapi import HTTPException
@@ -2080,14 +2114,18 @@ def test_manual_sale_api_rules():
def list_marketplaces(self):
return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}]
def set_manual_sale(self, code, day, amount, *, user=""):
def set_manual_sale(self, code, day, amount, *, user="", formula=None):
if self.missing:
raise ManualMigrationNeeded()
self.saved.append((code, day, amount, user))
self.formula = formula
def api_amount(self, code, day):
return 50000
def rate_table(self):
return {"coupang": [(date(2026, 1, 1), Decimal("10"))]}
def update_marketplace(self, code, **kw):
if self.missing and kw.get("manual_input") is not None:
raise ManualMigrationNeeded()
@@ -2117,7 +2155,12 @@ def test_manual_sale_api_rules():
assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body)
assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 200 # 앞날도 됨
assert st.formula is None
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "1,000+2000*2"}).body)
assert st.saved[-1][2] == 5000 and st.formula == "1000+2000*2" and body["formula"] == "1000+2000*2"
assert body["commission"] == 500 and body["net"] == 4500 # 화면이 새로고침 전에도 차감 매출을 바로 보이게
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "1/0"}))[0] == 400
code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1}))
assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400
@@ -2168,3 +2211,46 @@ def test_dashboard_manual_cells_and_order():
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700
def test_naver_ship_check_candidates():
"""배송비 진단(2026-10-19) — 같은 주문·배송 묶음에 반복되는 배송비·할인을 주문/묶음 단위로 센 후보를 함께 돌려준다."""
from app.modules.performance.adapters import naver as nv
def it(order, po, fee, dc, pkg, status="DELIVERING", pay=10000):
x = _naver_item(order, po, "2026-10-18", pay, status=status, ship=fee, ship_dc=dc)
x["content"]["productOrder"]["packageNumber"] = pkg
return x
items = [it("A", "A1", 3500, 0, "P1"), it("A", "A2", 3500, 3500, "P1"), # 묶음 2개 — 두 번째는 묶음 할인
it("B", "B1", 3500, 3500, "P2"), # 조건부 무료
it("C", "C1", 0, 0, "P3"), # 무료배송 상품
it("D", "D1", 3500, 0, "P4", status="CANCELED"),
it("E", "E1", 3500, 0, "P5", status="CANCELED_BY_NOPAYMENT")] # 미입금 — 제외
got = nv.ship_check([{"content": i["content"]} | {"productOrder": i["content"]["productOrder"], "order": i["content"]["order"]}
for i in items], date(2026, 10, 18), date(2026, 10, 18))
assert got["product_orders"] == 5
assert got["per_product_order"] == {"fee": 14000, "discount": 7000, "fee_minus_discount": 7000, "section": 0}
assert got["per_order"] == {"groups": 4, "max_fee": 10500, "max_fee_minus_max_discount": 3500,
"sum_fee_minus_sum_discount": 7000, "with_fee": 3}
assert got["per_package"]["groups"] == 4 and got["per_package"]["max_fee"] == 10500
assert [o["order"] for o in got["orders"]] == ["A", "B", "C", "D"] and len(got["orders"][0]["lines"]) == 2
assert "홍길동" not in repr(got) and "010-1234-5678" not in repr(got)
def test_naver_ship_once_per_package_like_sales_analysis():
"""10/18 실데이터 모양(2026-10-19): 상품주문마다 배송비 3,500·할인이 반복 — 묶음마다 배송비 한 번(할인 안 뺌) = 판매분석 배송비."""
from app.modules.performance.adapters import naver as nv
def it(order, po, fee, dc, pkg):
x = _naver_item(order, po, "2026-10-18", 10000, status="DELIVERING", ship=fee, ship_dc=dc)
x["content"]["productOrder"]["packageNumber"] = pkg
return x["content"]
items = [it("A", "A1", 3500, 3500, "P1"), it("A", "A2", 3500, 3500, "P1"), # 조건부 무료 묶음 — 그래도 3,500
it("B", "B1", 3500, 0, "P2"), it("B", "B2", 3500, 0, "P2"), it("B", "B3", 3500, 0, "P2"),
it("C", "C1", 0, 0, "P3"), # 무료배송 상품
it("D", "D1", 3500, 0, "P4"), it("D", "D2", 3500, 0, "P5")] # 한 주문 두 묶음 = 두 번
o = nv.group_orders(items, date(2026, 10, 18), date(2026, 10, 18))
assert {k: v["ship"] for k, v in o.items()} == {"A": 3500, "B": 3500, "C": 0, "D": 7000}
assert sum(v["ship"] for v in o.values()) == nv.ship_check(items, date(2026, 10, 18), date(2026, 10, 18))["per_package"]["max_fee"]
@@ -0,0 +1,60 @@
"""화면 자동 새로 고침(2026-10-26) — 자동 업데이트가 끝나면 매출 실적·광고비 화면이 알아채도록:
jobs.last_finished(종류별·보는 사람 것 제외) · GET /api/update-status · 화면 데이터 update_watch."""
from __future__ import annotations
import importlib
import time
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import auto_sync, common, jobs
perf_router = importlib.import_module("app.modules.performance.router")
@pytest.fixture(autouse=True)
def clean_jobs(monkeypatch):
monkeypatch.setattr(jobs, "_JOBS", {})
def _job(kind="sales", user=auto_sync.AUTO_USER, finished=True, at=None):
j = jobs.create_job(user=user, start=None, end=None, kind=kind)
if finished:
j.finish()
if at is not None:
j.finished_at = at
return j
def test_last_finished_by_kind_and_excludes_viewer():
assert jobs.last_finished("sales") is None
a = _job(at=time.time() - 100)
b = _job(user="me@x", at=time.time() - 10) # 보는 사람이 누른 것 — 진행 창이 알아서 새로 그림
ad = _job(kind="ads", at=time.time())
_job(finished=False) # 도는 중인 작업은 아님
assert jobs.last_finished("sales") is b
assert jobs.last_finished("sales", exclude_user="me@x") is a
assert jobs.last_finished("ads", exclude_user="me@x") is ad
assert perf_router._update_watch("sales", {"email": "me@x"}) == {"kind": "sales", "seen": a.id}
assert perf_router._update_watch("ads", {"email": "other@x"}) == {"kind": "ads", "seen": ad.id}
def test_update_status_api(monkeypatch):
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "me@x"}))
app = FastAPI()
app.include_router(perf_router.router)
c = TestClient(app)
assert c.get("/performance/api/update-status?kind=sales").json() == {"kind": "sales", "running": False, "done": "", "user": ""}
run = _job(finished=False)
r = c.get("/performance/api/update-status?kind=sales").json()
assert r["running"] and r["done"] == ""
run.finish()
r = c.get("/performance/api/update-status?kind=sales").json()
assert r == {"kind": "sales", "running": False, "done": run.id, "user": auto_sync.AUTO_USER}
_job(user="me@x") # 내 업데이트는 done 을 바꾸지 않는다
assert c.get("/performance/api/update-status?kind=sales").json()["done"] == run.id
assert c.get("/performance/api/update-status?kind=ads").json()["done"] == "" # 광고비는 따로
assert c.get("/performance/api/update-status?kind=nope").status_code == 404

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