46 Commits

Author SHA1 Message Date
king c86879b037 Merge branch 'feat/perf-lang-toggle' 2026-11-20 16:48:38 +09:00
king f9b087157b feat(말레이시아 실적): 한글·영문 전환 + OS 언어 기본값
- 말레이시아 실적 탭 줄에 [한글|EN] 토글(쿠키 mperf_lang), 고른 적 없으면
  브라우저·OS 첫 언어(Accept-Language) ko → 한글, 그 밖 → 영어(app/lang.py)
- 영문이면 performance-en.js(사전·패턴·낱말 치환, 창·알림까지) — 한국 실적 화면은 그대로
- 말레이시아 실적 공휴일 = 말레이시아 공휴일(live/holidays.py, 화면 언어로)
- 라이브 커머스·말레이시아 재고도 같은 기본 언어 규칙

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:48:37 +09:00
king a1dc52bec8 Merge branch 'feat/malaysia-performance' 2026-11-20 16:03:20 +09:00
king 62cc5e2778 feat(실적): 틱톡 탭 삭제 + [말레이시아 실적] 모듈 추가
- 실적 틱톡 탭·tiktok_ads 광고 API·테스트 삭제, 틱톡 데이터 삭제 SQL(performance_db 012)
- 말레이시아 실적: 실적 라우터·화면을 /malaysia/performance 에 한 번 더 마운트,
  차이는 performance/variant.py(KR·MY) 한 곳 — 저장소·권한키·주소·광고 채널·통화
- 틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위, 그룹 열 = 합계), 광고비 채널 3개
- 금액 RM 소수 2자리 = 센 정수 저장(입력·엑셀 scale, 화면 num/money, JS money)
- malaysia_performance_db = performance_db 구조 복사 + seed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:03:18 +09:00
king e9f57b6ff6 Merge branch 'fix/cafe24-variant-toggle-center' 2026-11-17 10:36:24 +09:00
king 262ae7fdf8 fix(카페24): 옵션/품목 팝업 토글 버튼 가운데 정렬
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:36:24 +09:00
king 083eebfd95 Merge branch 'feat/cafe24-variant-th-center' 2026-11-17 10:29:58 +09:00
king 0f4608cb43 style(카페24): 옵션/품목 팝업 표 헤더 굵게·가운데 정렬
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:29:57 +09:00
king 8e5a682f0d Merge branch 'feat/cafe24-variant-inventory' 2026-11-17 10:08:54 +09:00
king b0e816cbdc feat(카페24): 옵션/품목 팝업에 재고관리·재고 수량·품절표시 설정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:07:53 +09:00
king c39139a605 Merge branch 'feat/performance-yoy-kakao-pf' 2026-11-16 11:34:57 +09:00
king 91fd454b2c feat(실적): 매출 KPI 전년 같은 기간 대비 · 광고비 카톡 플친 열
- 매출 실적 KPI 줄에 전월 대비 옆 "전년 같은 기간 대비" % (연 보기 제외)
- 광고비 탭 카톡 플친(kakao_pf) 열 — 직접 입력, ROAS 없음
- 매출 탭 카페24 칸 광고비 줄에 구글·메타 다음 카톡 플친

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:34:56 +09:00
king 78d2e665ee Merge branch 'chore/malaysia-add-my1007' 2026-11-15 03:29:50 +09:00
king 4af44f2f7a chore(말레이시아재고): 신규 세트 MY-1007 malaysia_items 등록 SQL
BOM·구성 낱개는 이미 등록돼 있고 malaysia_items 에만 MY-1007 이 빠져
재고 화면 세트 목록에 안 보이던 것을 채운다. 이름은 itemcode_db 에서 psql 변수로 받는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:29:48 +09:00
king 60d5ca417d Merge branch 'feat/cafe24-keep-variant-price' 2026-11-15 03:15:32 +09:00
king 2465874198 feat(카페24): 판매가 변경 시 품목 판매 가격 유지 — 추가금액 자동 조정
기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 옵션 품목 추가금액을
(옛 판매가 - 새 판매가)만큼 옮겨 품목 판매 가격(판매가+추가금액)을 그대로 둔다.
품목 조정 실패는 판매가 저장을 되돌리지 않고 화면 메시지로 알린다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:15:26 +09:00
king f982a5fa9c Merge branch 'feat/project-timepicker-all' 2026-11-11 15:22:01 +09:00
king aa701ed611 feat(프로젝트): 시각 고르기를 공용 시각 팝업으로 — 옵션 알림 시각·긴급 공지 띄울 시각
- project.js openTimePopover·enhanceTimeInput(PJLib): 날짜 팝업 모양, 시 00~23·분 5분 단위, 끝에서 멈춤
- 모달 dialog 안이면 그 창 안 popover, 아니면 body

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:22:00 +09:00
king 8bcf9b4b20 Merge branch 'feat/project-daily-on-create' 2026-11-11 15:03:14 +09:00
king dd648d4752 feat(프로젝트): 메인 업무·세부 업무 추가 칸 날짜 팝업에도 [매일]
- POST tasks 의 repeat_daily: true = 만든 뒤 켬(033 미적용 503), 화면은 data-daily-ready(db.daily_ready)일 때만 버튼

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:03:12 +09:00
king 37df7be461 Merge branch 'fix/project-timepop-inert' 2026-11-11 14:50:56 +09:00
king 6e69abcfa3 fix(프로젝트): 옵션 시각 팝업 휠·마우스 오버·클릭 안 먹던 문제 — 모달 창 안에 붙임, 지우기·확인 동작·색
모달 dialog 가 열려 있으면 창 밖(body) 요소는 inert 라 popover 를 body 에 붙이면 마우스가 통과했다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:50:55 +09:00
king 0e6bb53c9c Merge branch 'feat/project-options-timepicker' 2026-11-11 14:46:54 +09:00
king 117f40c96f feat(프로젝트): Project 옵션 알림 시각 고르기를 날짜 팝업 모양으로 — 시 00~23·분 5분 단위, 끝에서 멈춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:46:53 +09:00
king ec0eb0a295 Merge branch 'feat/project-daily-tasks' 2026-11-11 14:36:00 +09:00
king 7f94e5efe7 feat(프로젝트): 매일 하는 업무 — 날짜 팝업 [매일]·반복 아이콘·시각별 알림
- 마이그레이션 033 tasks.repeat_daily — [매일]이면 마감일·시각 비움, 마감일을 고르면 꺼짐(미적용이면 버튼 숨김·PUT 503)
- 마감 칸(카드·목록·내 업무·세부 업무·업무 창)에 반복 아이콘 + "매일"
- reminders.run_daily_alerts: 영업일, Project 옵션 daily_alert_times 중 지난 가장 늦은 시각마다 담당자(없으면 협업자)에게 type=daily 알림(task_reminders 로 중복 방지, 데몬 1분 주기)
- 큰 알림 팝업·PC 알림 프로그램에서 매일 업무 줄은 노란 배경
- Project 옵션 "알림" 분류: 알림 시각 여러 개 추가·삭제(최대 12)
- 도움말·모듈 CLAUDE.md·DEPLOYMENT(033) 갱신, 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:35:59 +09:00
king 3045bc6f99 Merge branch 'feat/project-options-size' 2026-11-11 10:32:40 +09:00
king 1678f00c1b feat(프로젝트): Project 옵션 창 크기 800×750 고정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:32:39 +09:00
king 7a7e19636f Merge branch 'feat/project-allview-users' 2026-11-11 10:25:31 +09:00
king 34b8e2fb6b feat(프로젝트): 왼쪽 "전체 보기" 메뉴를 볼 사람을 Project 옵션에서 지정
- 옵션 창 "프로젝트 화면" 분류에 처음 여는 탭과 묶어 대상자 선택(아이콘+이름 체크, 전체 선택/해제)
- 옵션 키 all_view_users(이메일 목록, DB 변경 없음) — 설정 전(null)은 예전처럼 Pro user 이상
- 사이드바 pj_all_view(access.can_all_view), project.js canAllView 로 메뉴 표시만 판단
- assignable-users 에 pro 표시(기본 체크용), 도움말·모듈 CLAUDE.md 갱신, 정적 파일 ?v= 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:25:29 +09:00
king 7c53b16566 Merge branch 'feat/cafe24-sync-shop-flags' 2026-11-10 15:31:37 +09:00
king 8043110197 feat(카페24): 품목 진열·판매 멀티쇼핑몰 일괄 맞춤 스크립트
- python -m app.modules.cafe24.sync_variant_flags --shops 3,4 [--apply]
- 옵션 상품 전체의 기본몰(1) 품목 진열·판매를 지정 쇼핑몰에 같은 값으로(다른 값만 PUT)
- 기본 미리보기, BEFORE 줄로 원래 값 출력(되돌리기용), 감사 actor SYNC_SHOPS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:31:33 +09:00
king 9f57f5d15e Merge branch 'feat/cafe24-variant-all-shops' 2026-11-10 15:15:39 +09:00
king 4cd349c3a1 feat(카페24): 품목 진열·판매를 모든 멀티쇼핑몰에 같이 반영
- 옵션/품목 팝업 저장 시 기본몰(1)에 반영된 행의 진열·판매만
  CAFE24_SHOP_NOS(예 1,2,3)의 다른 쇼핑몰에도 같은 값으로 PUT
- 추가금액(통화 다름)·자체코드·순서는 기본몰만
- 다른 쇼핑몰 실패는 응답 shop_failed·감사 기록·화면 경고(기본몰 반영 유지)
- 쇼핑몰 목록 API 는 mall.read_store 권한이 필요해 번호를 환경변수로 받음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:15:32 +09:00
king 5e9c1dac88 Merge branch 'feat/cafe24-option-key-nav' 2026-11-10 01:03:56 +09:00
king 282ee559e0 feat(카페24): 옵션 팝업 이름·코드·추가금액 칸에도 키 이동 적용
- 옵션값 이름, 자체 품목코드, 추가금액 칸에서 Enter/아래 화살표는 아래 행, 위 화살표는 위 행으로 이동
- 한글 조합 중에는 이동하지 않음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 01:03:55 +09:00
king 1096fd68ab Merge branch 'feat/cafe24-option-sale-price' 2026-11-10 00:59:45 +09:00
king 8bd62fbf6d feat(카페24): 옵션 팝업 판매 가격 열, 추가금액 자동 계산
- 추가금액과 진열 사이에 판매 가격 열 추가(판매가 + 추가금액)
- 판매 가격 입력 시 기본 정보 판매가와의 차액을 추가금액에 입력
- Enter/아래 화살표는 아래 행, 위 화살표는 위 행 판매 가격으로 이동

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 00:59:44 +09:00
king 9229d269c9 Merge branch 'feat/cafe24-list-thumb' 2026-11-10 00:46:54 +09:00
king 4286c45531 feat(카페24): 상품 목록 대표 이미지 열, 상단 탭 여백 10px
- 목록 번호와 상품명 사이에 64x64 대표 이미지 표시(tiny_image, 없으면 detail_image)
- 대표 이미지 교체 시 목록 썸네일도 즉시 갱신
- 상단 탭 위아래 여백 10px 고정
- 이미지 열만큼 목록 폭 72px 확대

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 00:46:48 +09:00
king f87641233b Merge branch 'feat/cafe24-schedule-image' 2026-11-09 16:38:11 +09:00
king 6822329ff2 feat(카페24): 대표 이미지(썸네일) 예약 교체
- 편집기 아래 「예약 적용」 폼에 대표 이미지 파일 칸 — 고르면 그 시각에 교체
  (상세페이지·진열·판매와 한 예약에 같이 걸 수 있음, 이미지만도 가능)
- 마이그레이션 006: 예약 image_type/image_name + cafe24_schedule_images(BYTEA, CASCADE),
  "할 일 없는 예약" CHECK 에 이미지 포함
- worker: 이미지 먼저 set_main_image(즉시 교체와 같은 A 타입) → 스냅샷 → 상세페이지·진열/판매
- 예약 목록 「적용 내용」에 대표이미지 표시 + 미리보기 썸네일(GET /cafe24/schedules/{id}/image)
- 이미지 없는 예약 INSERT 는 006 컬럼을 안 써서 마이그레이션 전에도 기존 예약 등록 유지
- 테스트(경로·검증·worker 순서)·문서 갱신, cafe24.css 캐시 버전 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:38:05 +09:00
king 36834c65b2 Merge branch 'feat/perf-col-fold' 2026-11-06 19:58:18 +09:00
king 359ff29e95 feat(실적): 열 접기 버튼에 커서 따라다니는 이름 말풍선
버튼 위에 올리면 커서 바로 위에 쇼핑몰(열) 이름 — 글자 크기는 열 제목과 같은 12px 굵게.
머리글 th 의 기본 title 말풍선은 버튼 title="" 로 막음.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:58:18 +09:00
king 548a163fc4 Merge branch 'feat/perf-col-fold' 2026-11-06 19:53:44 +09:00
king 8636498bc9 feat(실적): 일자별 표 열 접기 — 사람마다 저장
매출 실적·광고비 일자별 표 머리글 위 버튼으로 열 하나씩 접기/펴기(날짜 열 제외).
접은 열은 26px 띠, 로그인한 사람 본인에게만 적용 — PUT /api/my-col-fold →
perf_settings col_fold:<이메일 sha1> (마이그레이션 없음, 011 테이블 재사용).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:53:39 +09:00
102 changed files with 3290 additions and 1142 deletions
+9
View File
@@ -126,6 +126,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다. # 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
# CAFE24_SHOP_URL=https://www.miras.co.kr # CAFE24_SHOP_URL=https://www.miras.co.kr
# #
# 멀티쇼핑몰 번호(쉼표). 옵션/품목 팝업에서 바꾼 품목 진열·판매를 이 쇼핑몰 모두에 같은 값으로
# 보낸다(추가금액·자체코드는 기본몰 1 만). 번호는 카페24 관리자 → 멀티쇼핑몰 관리에서 확인.
# 미설정 시 1(기본몰)만.
# CAFE24_SHOP_NOS=1,2,3
#
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 # 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도 # 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다. # 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
@@ -180,6 +185,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 초기화: scripts/sql/performance_db_init.sql (docs/DATABASES.md 참고) # 초기화: scripts/sql/performance_db_init.sql (docs/DATABASES.md 참고)
# PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/performance_db # PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/performance_db
# #
# 말레이시아 실적(app/modules/malaysia_performance — 실적 코드 그대로, DB 만 따로). 미설정 시 "설정 필요" 안내.
# 만들기: scripts/sql/malaysia_performance_db_seed.sql 머리말(performance_db 구조 복사 + 쇼핑몰 seed), 역할은 performance_app 공유.
# MALAYSIA_PERFORMANCE_DB_URL=postgresql://performance_app:replace-me@postgres-db:5432/malaysia_performance_db
#
# 쇼핑몰 API 인증정보(ID·Key·Secret·Token)는 여기에 넣지 않는다 — # 쇼핑몰 API 인증정보(ID·Key·Secret·Token)는 여기에 넣지 않는다 —
# 실적 → 설정 화면에서 입력하면 아래 마스터 키로 AES-256-GCM 암호화해 DB 에 저장한다. # 실적 → 설정 화면에서 입력하면 아래 마스터 키로 AES-256-GCM 암호화해 DB 에 저장한다.
# 마스터 키는 DB 에 저장되지 않으며, 잃어버리면 저장된 인증정보를 복구할 수 없다(별도 안전 보관). # 마스터 키는 DB 에 저장되지 않으며, 잃어버리면 저장된 인증정보를 복구할 수 없다(별도 안전 보관).
+3
View File
@@ -37,6 +37,7 @@
| --- | --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- | --- |
| `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` | | `[프로젝트]` `[Project]` | `project/` | `project_db` | `project` | `docs/PROJECT_MODULE.md` (178KB, 절만) | `project*.js/css`, `erp-overdue.*` |
| `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` | | `[실적]` | `performance/` | `performance_db` | `performance` | `docs/PERFORMANCE_MODULE.md` (절만) | `performance.*` |
| `[말레이시아 실적]` | `malaysia_performance/`(얇은 마운트 — 코드는 `performance/` + `variant.py`) | `malaysia_performance_db` | `malaysia_performance` | (모듈 CLAUDE.md) | `performance.*` (실적과 공유) |
| `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` | | `[카페24]` | `cafe24/` | `cafe24_db` | `cafe24` | `docs/CAFE24_MODULE.md` (절만) | `cafe24.css`, `cafe24-options.js` |
| `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` | | `[쿠팡]` | `cupang/` | `cupang_db` | `cupang` | (모듈 CLAUDE.md 가 기준) | `cupang.*` |
| `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` | | `[입출고]` | `inout/` | `inout_db` | `inout` | `docs/INOUT_MODULE.md` | `inout.*` |
@@ -59,6 +60,7 @@
- `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한). - `itemcode_db` 읽기 전용 상품: 쿠팡·말레이시아재고·입출고 (`itemcode_ro` 권한).
- `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터). - `app/integrations/cafe24/` 토큰: 카페24 + 실적(카페24 어댑터).
- `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용). - `performance_store` 매출: 실적 → 프로젝트 주간 회의록 머리 카드(읽기 전용).
- 실적 코드·화면(`performance/`·`performance.js/css`): 실적 + 말레이시아 실적(`variant.py`) — 바꾸면 둘 다 확인.
- `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지. - `ProjectStore.pool`(`project_db`): 프로젝트 + 긴급 공지.
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰). - `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail. - 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
@@ -66,6 +68,7 @@
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스. - `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
- `app/mail.py`: 프로젝트 알림 메일. - `app/mail.py`: 프로젝트 알림 메일.
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림). - ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
- 한영 전환 기본 언어 `app/lang.py`(고른 값 없으면 브라우저·OS 언어 ko → 한글, 그 밖 → 영어): 말레이시아 실적 + 라이브 커머스(서버) + 말레이시아 재고(`malaysia.js` 같은 규칙). 말레이시아 공휴일 `live/holidays.py`: 라이브 + 말레이시아 실적.
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다. - 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸). - 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
+2 -2
View File
@@ -486,7 +486,7 @@ VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을
def update_variants( def update_variants(
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]] client: Cafe24Client, product_no: int, requests: list[dict[str, Any]], *, shop_no: int = 1
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로). """여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
@@ -506,7 +506,7 @@ def update_variants(
continue continue
try: try:
payload = client.put( payload = client.put(
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no f"/admin/products/{no}/variants", json={"shop_no": int(shop_no), "requests": chunk}, product_no=no
) )
except Cafe24Error as exc: except Cafe24Error as exc:
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
+19
View File
@@ -0,0 +1,19 @@
"""한글·영문 화면 언어 고르기(2026-11-20) — 한영 전환이 있는 모듈 공통(말레이시아 실적·라이브 커머스).
사용자가 토글로 고른 값(쿠키)이 있으면 그것, 없으면 접속한 브라우저의 첫 언어(Accept-Language — 보통 OS 기본 언어)가
한국어(ko…)면 한국어, 그 밖의 언어면 영어. 머리글이 없으면(스크립트·테스트) 한국어.
말레이시아 재고관리는 화면 스크립트(malaysia.js)가 같은 규칙을 navigator.language 로 쓴다.
"""
from __future__ import annotations
from typing import Any
def detect_lang(chosen: Any, accept_language: str | None) -> str:
if chosen in ("ko", "en"):
return chosen
first = (accept_language or "").split(",")[0].split(";")[0].strip().lower()
if not first or first == "*":
return "ko"
return "ko" if first.startswith("ko") else "en"
+17
View File
@@ -30,6 +30,8 @@ from .modules.live import build_live_store
from .modules.live import router as live_router from .modules.live import router as live_router
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
from .modules.malaysia import router as malaysia_router from .modules.malaysia import router as malaysia_router
from .modules.malaysia_performance import build_malaysia_performance_store
from .modules.malaysia_performance import router as malaysia_performance_router
from .modules.notice import build_notice_store from .modules.notice import build_notice_store
from .modules.notice import router as notice_router from .modules.notice import router as notice_router
from .modules.outreach import build_outreach_store from .modules.outreach import build_outreach_store
@@ -64,6 +66,7 @@ MODULE_LABELS: dict[str, str] = {
"project": "프로젝트 관리", "project": "프로젝트 관리",
"cafe24": "카페24 상품관리", "cafe24": "카페24 상품관리",
"performance": "실적", "performance": "실적",
"malaysia_performance": "말레이시아 실적",
"asset": "자산관리", "asset": "자산관리",
"inout": "입출고 관리", "inout": "입출고 관리",
"outreach": "안내문 발송", "outreach": "안내문 발송",
@@ -229,6 +232,8 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내). # 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장. # 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None) app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
# 말레이시아 실적(틱톡·쇼피·라자다 수동 입력): 실적 모듈 코드 그대로, DB 만 따로(MALAYSIA_PERFORMANCE_DB_URL 없으면 "설정 필요").
app.state.malaysia_performance_store = build_malaysia_performance_store(dsn=env("MALAYSIA_PERFORMANCE_DB_URL") or None)
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None) app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
# 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503). # 긴급 공지(ERP 전체 화면 가운데): project_db 024 — 프로젝트 저장소의 연결 풀을 같이 쓴다(없으면 None → 503).
app.state.notice_store = build_notice_store(app.state.project_store) app.state.notice_store = build_notice_store(app.state.project_store)
@@ -251,6 +256,7 @@ app.include_router(dispatch_router)
app.include_router(project_router) app.include_router(project_router)
app.include_router(cafe24_router) app.include_router(cafe24_router)
app.include_router(performance_router) app.include_router(performance_router)
app.include_router(malaysia_performance_router) # /malaysia/performance — 실적 라우터 두 번째 마운트(라우트 이름은 실적이 먼저)
app.include_router(asset_router) app.include_router(asset_router)
app.include_router(notice_router) app.include_router(notice_router)
app.include_router(inout_router) app.include_router(inout_router)
@@ -448,6 +454,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
"status": "ready", "status": "ready",
"category": "관리", "category": "관리",
}, },
{
"key": "malaysia_performance",
"title": "말레이시아 실적",
"subtitle": "Malaysia Sales",
"description": "틱톡·쇼피·라자다의 쇼핑몰·라이브커머스 매출(RM)과 광고비를 일자별로 입력하고 합계를 봅니다.",
"url": "/malaysia/performance/",
"health_url": "/malaysia/performance/health",
"status": "ready",
"category": "관리",
},
{ {
"key": "inout", "key": "inout",
"title": "입출고 관리", "title": "입출고 관리",
@@ -509,6 +525,7 @@ def _icon_svg(name: str) -> str:
"project": '<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="8" y1="13" x2="13" y2="13"/><line x1="8" y1="16" x2="11" y2="16"/>', "project": '<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="8" y1="13" x2="13" y2="13"/><line x1="8" y1="16" x2="11" y2="16"/>',
"cafe24": '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9h10"/><path d="M7 13h7"/><path d="M7 17h4"/>', "cafe24": '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9h10"/><path d="M7 13h7"/><path d="M7 17h4"/>',
"performance": '<path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/>', "performance": '<path d="M3 3v18h18"/><rect x="7" y="12" width="3" height="6"/><rect x="12" y="8" width="3" height="10"/><rect x="17" y="5" width="3" height="13"/>',
"malaysia_performance": '<path d="M3 3v18h18"/><path d="M7 15l4-4 3 3 6-6"/><path d="M16 8h4v4"/>',
"modules": '<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>', "modules": '<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
} }
body = paths.get(name, paths["modules"]) body = paths.get(name, paths["modules"])
+7 -1
View File
@@ -8,15 +8,21 @@
## 기능 ## 기능
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력. - 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). - 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널). 목록에 64x64 대표 이미지(`tiny_image`, 없으면 `detail_image`).
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작). - HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
- HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호. - HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정. - 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
품목 진열·판매는 `CAFE24_SHOP_NOS`(예 1,2,3)의 모든 멀티쇼핑몰에 같은 값으로 보냄(추가금액 등은 기본몰만).
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`. - 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨. NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
- 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 품목 추가금액을 (옛 판매가 − 새 판매가)만큼 옮겨 품목 판매 가격을 유지(`_keep_variant_sale_prices`, `store.shift_additional_amounts`). 공급가·소비자가는 품목과 무관. 판매가는 이미 반영됐으므로 품목 조정 실패는 화면 메시지(`variants_error`)로만.
- 옵션/품목 팝업 「재고관리」(use_inventory)·「재고」(quantity)·「품절표시」(display_soldout) 열: 같은 PUT variants 로 기본몰에만 보냄(재고는 쇼핑몰 공통).
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격·재고 칸: Enter·↓ 아래 행, ↑ 위 행 같은 열로 이동(한글 조합 중에는 이동 안 함).
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로 - 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터). (`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만). 「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
- 예약(편집기 아래 「예약 적용」): 대표 이미지(썸네일) · 상세페이지 · 진열 · 판매를 지정 시각에. 대표 이미지 파일은 `cafe24_schedule_images`(마이그레이션 006)에 보관, worker 가 이미지 먼저 교체.
- 권한키 `cafe24`(연결/해제는 admin 전용). - 권한키 `cafe24`(연결/해제는 admin 전용).
## 규칙 ## 규칙
+9
View File
@@ -42,6 +42,15 @@ def read_lag_grace_minutes() -> int:
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN")) return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
def shop_nos() -> list[int]:
"""품목 진열·판매를 함께 맞출 멀티쇼핑몰 번호. `CAFE24_SHOP_NOS`(예: 1,2,3), 기본 [1]."""
import os # noqa: WPS433
from . import store # noqa: WPS433
return store.parse_shop_nos(os.getenv("CAFE24_SHOP_NOS"))
def require_user(request: Request) -> dict[str, Any]: def require_user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433 from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433 from app.store import has_module # noqa: WPS433
+31 -17
View File
@@ -819,27 +819,41 @@ class Cafe24Store:
set_selling: bool | None, set_selling: bool | None,
memo: str = "", memo: str = "",
created_by: str = "", created_by: str = "",
image: bytes | None = None,
image_type: str = "",
image_name: str = "",
) -> int: ) -> int:
"""예약 등록. image 가 있으면 파일을 cafe24_schedule_images 에 같은 트랜잭션으로 남긴다(006).
이미지 없는 예약은 006 컬럼을 쓰지 않는다 — 마이그레이션 전에도 기존 예약 등록이 깨지지 않게.
"""
cols = ["product_no", "scheduled_at", "revision_id", "set_display", "set_selling", "memo", "created_by"]
vals: list[Any] = [int(product_no), scheduled_at, revision_id, set_display, set_selling,
(memo or "")[:500], created_by or ""]
if image:
cols += ["image_type", "image_name"]
vals += [image_type, (image_name or "")[:200]]
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
f"INSERT INTO cafe24_product_schedules ({', '.join(cols)}) " # noqa: S608 — 고정 컬럼명만
f"VALUES ({', '.join(['%s'] * len(cols))}) RETURNING id",
vals,
).fetchone()
if row and image:
conn.execute(
"INSERT INTO cafe24_schedule_images (schedule_id, data) VALUES (%s, %s)",
(row["id"], image),
)
return int(row["id"]) if row else 0
def get_schedule_image(self, schedule_id: int) -> bytes:
"""예약 대표 이미지 파일. 없으면 b""."""
with self._pool.connection() as conn: with self._pool.connection() as conn:
row = conn.execute( row = conn.execute(
""" "SELECT data FROM cafe24_schedule_images WHERE schedule_id = %s", (int(schedule_id),)
INSERT INTO cafe24_product_schedules
(product_no, scheduled_at, revision_id, set_display, set_selling,
memo, created_by)
VALUES (%s,%s,%s,%s,%s,%s,%s)
RETURNING id
""",
(
int(product_no),
scheduled_at,
revision_id,
set_display,
set_selling,
(memo or "")[:500],
created_by or "",
),
).fetchone() ).fetchone()
return int(row["id"]) if row else 0 return bytes(row["data"]) if row else b""
def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]: def list_schedules(self, *, limit: int = 200) -> list[dict[str, Any]]:
"""예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순.""" """예약 목록. 대기 중인 것을 먼저, 그다음 최근 처리 순."""
+59 -4
View File
@@ -37,7 +37,7 @@ from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
from app.timezone import now_kst from app.timezone import now_kst
from . import store, writes from . import store, writes
from .common import read_lag_grace_minutes, require_store from .common import read_lag_grace_minutes, require_store, shop_nos
from .routes_products import load_product, locked_json, remember_write from .routes_products import load_product, locked_json, remember_write
logger = logging.getLogger("cafe24.product_info") logger = logging.getLogger("cafe24.product_info")
@@ -145,12 +145,46 @@ def product_basic(
raise _http_from_cafe24(exc) from exc raise _http_from_cafe24(exc) from exc
remember_write(st, product_no, updated if isinstance(updated, dict) else {}) remember_write(st, product_no, updated if isinstance(updated, dict) else {})
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
if "price" in changes else {})
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes} merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items()) detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
if shifted.get("detail"):
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no, writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
result="SUCCESS", detail=detail) result="SUCCESS", detail=detail)
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail) logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)} return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged),
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
"""
try:
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
except (Cafe24Error, ValueError) as exc:
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
if not requests:
return {}
results = products.update_variants(api.client, product_no, requests)
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
bad = [r for r in results if r["status"] != products.VARIANT_OK]
if ok:
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
error = ""
if bad:
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
return {"count": len(ok), "error": error, "detail": detail}
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
@@ -223,6 +257,7 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
"selling": products._flag(v.get("selling")), # noqa: SLF001 "selling": products._flag(v.get("selling")), # noqa: SLF001
"quantity": v.get("quantity"), "quantity": v.get("quantity"),
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001 "use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
"display_soldout": products._flag(v.get("display_soldout"), default=False), # noqa: SLF001
"image": str(v.get("image") or ""), "image": str(v.get("image") or ""),
} }
@@ -630,12 +665,13 @@ def variants_update(
product_no: int, product_no: int,
payload: dict[str, Any] = Body(default_factory=dict), payload: dict[str, Any] = Body(default_factory=dict),
) -> dict[str, Any]: ) -> dict[str, Any]:
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**. """품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매 · 재고(사용·수량·품절표시)를 한 번에 바꾼다 — **행별 결과**.
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값}, 응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
"failed": {code: 사유}, "unknown": {code: 사유}} "failed": {code: 사유}, "unknown": {code: 사유}}
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을 100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
다시 보내지 않게). 하나도 반영되지 않았으면 502. 다시 보내지 않게). 하나도 반영되지 않았으면 502.
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
""" """
st, user = require_store(request) st, user = require_store(request)
actor = str(user.get("email") or "") actor = str(user.get("email") or "")
@@ -662,7 +698,8 @@ def variants_update(
code = result["variant_code"] code = result["variant_code"]
if result["status"] == products.VARIANT_OK: if result["status"] == products.VARIANT_OK:
patch = dict(sent.get(code) or {}) patch = dict(sent.get(code) or {})
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"): for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
"use_inventory", "display_soldout", "quantity"):
value = (result.get("variant") or {}).get(key) value = (result.get("variant") or {}).get(key)
if value is not None: if value is not None:
patch[key] = value patch[key] = value
@@ -673,9 +710,26 @@ def variants_update(
failed[code] = result["error"] failed[code] = result["error"]
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else "" record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
# 멀티쇼핑몰: 진열·판매는 쇼핑몰마다 따로라 기본몰(1)에 반영된 행의 진열·판매만
# 다른 쇼핑몰에도 똑같이 보낸다. 추가금액(통화가 다름)·자체코드·순서는 보내지 않는다.
flags = [
{"variant_code": code, **{k: sent[code][k] for k in ("display", "selling") if k in sent[code]}}
for code in by_code if {"display", "selling"} & set(sent.get(code) or {})
]
shop_failed: dict[str, str] = {}
for shop in (shop_nos()[1:] if flags else []):
bad = [r for r in products.update_variants(api.client, product_no, flags, shop_no=shop)
if r["status"] != products.VARIANT_OK]
if bad:
shop_failed[str(shop)] = f"{len(bad)}건 — {bad[0]['error']}"
detail = "; ".join( detail = "; ".join(
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items() f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
) )
if flags and len(shop_nos()) > 1:
detail = f"[진열·판매 쇼핑몰 {','.join(map(str, shop_nos()))}] " + detail
if shop_failed:
detail += " / 다른 쇼핑몰 실패: " + "; ".join(f"{s}번 {e}" for s, e in shop_failed.items())
if failed or unknown: if failed or unknown:
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail) detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
first = next(iter({**failed, **unknown}.values()), "") first = next(iter({**failed, **unknown}.values()), "")
@@ -696,5 +750,6 @@ def variants_update(
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()}, "updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
"failed": failed, "failed": failed,
"unknown": unknown, "unknown": unknown,
"shop_failed": shop_failed,
"record_warning": record_error, "record_warning": record_error,
} }
+2 -1
View File
@@ -133,10 +133,11 @@ def _iso(value: Any) -> str:
def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]: def _row_for_list(raw: dict[str, Any]) -> dict[str, Any]:
"""왼쪽 목록에 쓸 필드만 — 상품번호·상품명·진열·판매·최근수정.""" """왼쪽 목록에 쓸 필드만 — 상품번호·대표 이미지·상품명·진열·판매·최근수정."""
normalized = products.normalize_product(raw) normalized = products.normalize_product(raw)
return { return {
"product_no": normalized["product_no"], "product_no": normalized["product_no"],
"thumb": str(raw.get("tiny_image") or raw.get("detail_image") or ""),
"product_name": normalized["product_name"], "product_name": normalized["product_name"],
"display": normalized["display"], "display": normalized["display"],
"selling": normalized["selling"], "selling": normalized["selling"],
+37 -8
View File
@@ -1,8 +1,9 @@
"""카페24 예약관리 — 지정 시각에 상세페이지·진열/판매를 자동 적용. """카페24 예약관리 — 지정 시각에 대표 이미지·상세페이지·진열/판매를 자동 적용.
되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다. 되돌리기(자동 복원)는 쓰지 않는다. 예약은 "그 시각에 이 내용을 적용" 하나뿐이다.
한 예약에서 세 가지를 각각 고를 수 있다. 한 예약에서 네 가지를 각각 고를 수 있다.
대표 이미지 고른 파일로 그 시각에 교체 (파일은 DB 보관 — 마이그레이션 006)
상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로) 상세페이지 HTML 편집기에 있는 내용을 그 시각에 적용 (안 고르면 HTML 은 그대로)
진열 진열 / 미진열 / 변경 없음 진열 진열 / 미진열 / 변경 없음
판매 판매 / 중지 / 변경 없음 판매 판매 / 중지 / 변경 없음
@@ -19,13 +20,14 @@ from __future__ import annotations
import logging import logging
from fastapi import APIRouter, Form, Request from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, RedirectResponse, Response
from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, load_config, products
from . import store, writes from . import store, writes
from .common import base_ctx, guard from .common import base_ctx, guard
from .routes_product_info import _read_image
from .routes_products import _no_store, load_product from .routes_products import _no_store, load_product
logger = logging.getLogger("cafe24.schedules") logger = logging.getLogger("cafe24.schedules")
@@ -53,6 +55,7 @@ def schedules_page(request: Request) -> HTMLResponse:
has_html=bool(row.get("has_html")), has_html=bool(row.get("has_html")),
set_display=row.get("set_display"), set_display=row.get("set_display"),
set_selling=row.get("set_selling"), set_selling=row.get("set_selling"),
has_image=bool(row.get("image_type")),
), ),
"editable": store.is_editable(row.get("status") or ""), "editable": store.is_editable(row.get("status") or ""),
"needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW, "needs_review": row.get("status") == store.STATUS_NEEDS_REVIEW,
@@ -63,7 +66,7 @@ def schedules_page(request: Request) -> HTMLResponse:
ctx.update( ctx.update(
{ {
"page_title": "카페24 — 예약관리", "page_title": "카페24 — 예약관리",
"page_subtitle": "지정 시각에 상세페이지·진열/판매 자동 적용", "page_subtitle": "지정 시각에 대표 이미지·상세페이지·진열/판매 자동 적용",
"rows": rows, "rows": rows,
"pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING), "pending": sum(1 for r in rows if r["status"] == store.STATUS_PENDING),
"review": sum(1 for r in rows if r["needs_review"]), "review": sum(1 for r in rows if r["needs_review"]),
@@ -85,12 +88,14 @@ def schedule_create(
set_selling: str = Form(""), set_selling: str = Form(""),
memo: str = Form(""), memo: str = Form(""),
list_query: str = Form(""), list_query: str = Form(""),
image: UploadFile | None = File(None),
): ):
"""편집기에서 예약을 등록한다. """편집기에서 예약을 등록한다.
HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다. HTML 을 적용하는 예약이면 지금 편집기 내용을 DRAFT revision 으로 저장해 고정한다.
단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때 단건 적용과 같은 다듬기(URL 인코딩 → 소스 정리)를 거치므로, 예약이 실행됐을 때
저장되는 값이 화면에서 본 것과 같다. 저장되는 값이 화면에서 본 것과 같다.
대표 이미지 파일을 고르면 파일을 DB 에 보관했다가 그 시각에 교체한다(마이그레이션 006).
""" """
checked = guard(request) checked = guard(request)
if not isinstance(checked, tuple): if not isinstance(checked, tuple):
@@ -105,9 +110,16 @@ def schedule_create(
display_flag = store.parse_tristate(set_display) display_flag = store.parse_tristate(set_display)
selling_flag = store.parse_tristate(set_selling) selling_flag = store.parse_tristate(set_selling)
if not want_html and display_flag is None and selling_flag is None: image_data = b""
if image is not None and image.filename: # 파일을 안 고르면 브라우저가 이름 없는 빈 파트를 보낸다
try:
image_data = _read_image(image)
except HTTPException as exc:
return RedirectResponse(url=f"{back}&err={exc.detail}", status_code=303)
if not want_html and display_flag is None and selling_flag is None and not image_data:
return RedirectResponse( return RedirectResponse(
url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(상세페이지 / 진열 / 판매).", url=f"{back}&err=예약할 내용을 하나 이상 선택하세요(대표 이미지 / 상세페이지 / 진열 / 판매).",
status_code=303, status_code=303,
) )
@@ -146,9 +158,12 @@ def schedule_create(
set_selling=selling_flag, set_selling=selling_flag,
memo=memo, memo=memo,
created_by=actor, created_by=actor,
image=image_data or None,
image_type=(image.content_type or "").lower() if image_data and image else "",
image_name=(image.filename or "") if image_data and image else "",
) )
detail = store.describe_schedule_action( detail = store.describe_schedule_action(
has_html=want_html, set_display=display_flag, set_selling=selling_flag has_html=want_html, set_display=display_flag, set_selling=selling_flag, has_image=bool(image_data)
) )
st.log_audit( st.log_audit(
actor=actor, action="schedule_create", product_no=product_no, actor=actor, action="schedule_create", product_no=product_no,
@@ -179,6 +194,20 @@ def schedule_cancel(request: Request, schedule_id: int):
) )
@schedules_router.get("/schedules/{schedule_id}/image")
def schedule_image(request: Request, schedule_id: int):
"""예약해 둔 대표 이미지 미리보기(목록 썸네일)."""
checked = guard(request)
if not isinstance(checked, tuple):
return checked
st, _user = checked
row = st.get_schedule(schedule_id)
data = st.get_schedule_image(schedule_id) if row.get("image_type") else b""
if not data:
return Response(status_code=404)
return Response(content=data, media_type=str(row["image_type"]), headers={"Cache-Control": "private, max-age=3600"})
@schedules_router.get("/schedules/preview/{product_no}") @schedules_router.get("/schedules/preview/{product_no}")
def schedule_current_flags(request: Request, product_no: int) -> dict: def schedule_current_flags(request: Request, product_no: int) -> dict:
"""예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용).""" """예약 폼의 기본값을 위해 현재 진열/판매 상태를 알려준다(JSON, 읽기 전용)."""
+39 -2
View File
@@ -452,10 +452,12 @@ def parse_schedule_at(value: object, *, now: datetime | None = None) -> datetime
def describe_schedule_action( def describe_schedule_action(
*, has_html: bool, set_display: bool | None, set_selling: bool | None *, has_html: bool, set_display: bool | None, set_selling: bool | None, has_image: bool = False
) -> str: ) -> str:
"""예약 내용을 한 줄로 요약(목록·로그 표시용).""" """예약 내용을 한 줄로 요약(목록·로그 표시용)."""
parts: list[str] = [] parts: list[str] = []
if has_image:
parts.append("대표이미지")
if has_html: if has_html:
parts.append("상세페이지") parts.append("상세페이지")
if set_display is not None: if set_display is not None:
@@ -504,6 +506,15 @@ WRITE_REVISION_TYPES: tuple[str, ...] = (REVISION_MANUAL, REVISION_SCHEDULED, RE
DEFAULT_READ_LAG_GRACE_MIN = 360 DEFAULT_READ_LAG_GRACE_MIN = 360
def parse_shop_nos(value: object) -> list[int]:
"""`CAFE24_SHOP_NOS`("1,2,3") → [1, 2, 3]. 기본 쇼핑몰 1 은 항상 맨 앞, 잘못된 값은 버린다."""
out = [1]
for part in str(value or "").replace(" ", "").split(","):
if part.isdigit() and int(part) > 0 and int(part) not in out:
out.append(int(part))
return out
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int: def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
try: try:
minutes = int(str(value or "").strip()) minutes = int(str(value or "").strip())
@@ -1060,6 +1071,24 @@ def parse_additional_amount(value: object) -> str | None:
return f"{number}.00" return f"{number}.00"
def shift_additional_amounts(variants: list[dict], old_price: object, new_price: object) -> list[dict]:
"""판매가 old → new 일 때 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴 행들.
build_variant_updates 에 그대로 넣는 화면 행 모양. 판매가가 같거나 숫자가 아니면 [].
"""
try:
delta = int(round(float(old_price))) - int(round(float(new_price))) # type: ignore[arg-type]
except (TypeError, ValueError):
return []
if not delta:
return []
return [
{"variant_code": str(v["variant_code"]),
"additional_amount": str(int(round(float(v.get("additional_amount") or 0))) + delta)}
for v in variants if v.get("variant_code")
]
def build_variant_updates(rows: list[dict]) -> list[dict]: def build_variant_updates(rows: list[dict]) -> list[dict]:
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다.""" """화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
out: list[dict] = [] out: list[dict] = []
@@ -1077,9 +1106,17 @@ def build_variant_updates(rows: list[dict]) -> list[dict]:
amount = parse_additional_amount(row["additional_amount"]) amount = parse_additional_amount(row["additional_amount"])
if amount is not None: if amount is not None:
item["additional_amount"] = amount item["additional_amount"] = amount
for flag in ("display", "selling"): for flag in ("display", "selling", "use_inventory", "display_soldout"):
if row.get(flag) is not None: if row.get(flag) is not None:
item[flag] = "T" if parse_tristate(row[flag]) else "F" item[flag] = "T" if parse_tristate(row[flag]) else "F"
if row.get("quantity") is not None and str(row["quantity"]).strip() != "":
try:
qty = int(str(row["quantity"]).strip().replace(",", ""))
except ValueError:
raise ValueError("재고 수량은 숫자여야 합니다.") from None
if not 0 <= qty <= ADDITIONAL_AMOUNT_MAX:
raise ValueError("재고 수량은 0 이상이어야 합니다.")
item["quantity"] = qty
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다. # 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
if row.get("display_order") is not None: if row.get("display_order") is not None:
try: try:
+113
View File
@@ -0,0 +1,113 @@
"""일회성 — 모든 옵션 상품의 품목 진열·판매를 기본몰(1) 값으로 다른 멀티쇼핑몰에 맞춘다.
# 미리보기(쓰지 않음): 바뀔 품목만 출력
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4
# 실제 반영 — 출력(바꾸기 전 값 포함)을 파일로 남겨 둔다
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 --apply > sync.log
기본몰 값은 화면과 같은 기준(읽기 지연 보정)으로 읽는다. 다른 쇼핑몰에 없는 품목은 건너뛴다.
진열·판매만 보낸다(추가금액·자체코드는 건드리지 않음). 출력의 BEFORE 줄 = 되돌릴 때 쓸 원래 값.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any
def plan_flag_sync(base: list[dict[str, Any]], shop_variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""기본몰 품목(display/selling = bool) vs 다른 쇼핑몰 GET 품목('T'/'F') → 바꿀 PUT 요청."""
from app.integrations.cafe24 import products # noqa: WPS433
other = {str(v.get("variant_code") or ""): v for v in shop_variants}
out = []
for v in base:
o = other.get(v["variant_code"])
if o is None:
continue
req = {k: ("T" if v[k] else "F") for k in ("display", "selling")
if products._flag(o.get(k)) != v[k]} # noqa: SLF001
if req:
out.append({"variant_code": v["variant_code"], **req})
return out
def main(argv: list[str] | None = None) -> int:
from app.integrations.cafe24 import build_cafe24_api # noqa: WPS433
from . import build_cafe24_store # noqa: WPS433
ap =argparse.ArgumentParser()
ap.add_argument("--shops", required=True, help="맞출 쇼핑몰 번호(쉼표), 예: 3,4")
ap.add_argument("--apply", action="store_true", help="실제로 카페24에 쓴다(없으면 미리보기)")
args = ap.parse_args(argv)
shops = [int(s) for s in args.shops.split(",") if s.strip().isdigit() and int(s) > 1]
if not shops:
print("--shops 에 2 이상 쇼핑몰 번호가 필요합니다.", file=sys.stderr)
return 2
st = build_cafe24_store(dsn=os.environ["CAFE24_DB_URL"])
try:
return _run(st, build_cafe24_api(st), shops, args.apply)
finally:
st.close()
def _run(st: Any, api: Any, shops: list[int], apply: bool) -> int:
from app.integrations.cafe24 import products # noqa: WPS433
from . import writes # noqa: WPS433
from .routes_product_info import _load_options_and_variants # noqa: WPS433
items, truncated = products.list_all_products(api.client)
if truncated:
print("상품이 상한(1000)을 넘어 일부만 처리합니다.", file=sys.stderr)
mode = "APPLY" if apply else "DRY-RUN"
total = failed = 0
for item in items:
no = int(item["product_no"])
if str(item.get("has_option") or "T") == "F":
continue
try:
base = _load_options_and_variants(st, api, no)["variants"]
except Exception as exc: # noqa: BLE001 — 한 상품 실패가 나머지를 막지 않게
print(f"ERROR {no} 기본몰 조회 실패: {exc}")
failed += 1
continue
for shop in shops:
try:
got = api.client.get(f"/admin/products/{no}/variants", params={"shop_no": shop}, product_no=no)
except Exception as exc: # noqa: BLE001
print(f"ERROR {no} shop {shop} 조회 실패: {exc}")
failed += 1
continue
shop_vars = got.get("variants") if isinstance(got.get("variants"), list) else []
reqs = plan_flag_sync(base, shop_vars)
if not reqs:
continue
before = {str(v.get("variant_code")): {"display": v.get("display"), "selling": v.get("selling")}
for v in shop_vars if str(v.get("variant_code")) in {r["variant_code"] for r in reqs}}
print("BEFORE " + json.dumps({"product_no": no, "shop_no": shop, "variants": before}, ensure_ascii=False))
print(f"{mode} {no} shop {shop}: {len(reqs)}건 " + json.dumps(reqs, ensure_ascii=False))
total += len(reqs)
if not apply:
continue
bad = [r for r in products.update_variants(api.client, no, reqs, shop_no=shop)
if r["status"] != products.VARIANT_OK]
failed += len(bad)
writes.audit_safe(
st, actor="SYNC_SHOPS", action="update_variants", product_no=no,
result="FAIL" if bad else "SUCCESS",
detail=(f"[쇼핑몰 {shop} 진열·판매 = 기본몰] " + json.dumps(reqs, ensure_ascii=False)
+ (f" / 실패 {len(bad)}: {bad[0]['error']}" if bad else ""))[:900],
)
if bad:
print(f"ERROR {no} shop {shop}: 실패 {len(bad)}건 — {bad[0]['error']}")
print(f"{mode} 끝 — 상품 {len(items)}개 확인, 바꿀/바꾼 품목 {total}건, 오류 {failed}건")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -156,7 +156,7 @@
<details class="cf24-details"> <details class="cf24-details">
<summary>예약 적용 — 지정한 시각에 자동 반영</summary> <summary>예약 적용 — 지정한 시각에 자동 반영</summary>
<form class="cf24-schedule-form" id="cf24-schedule-form" method="post" <form class="cf24-schedule-form" id="cf24-schedule-form" method="post"
action="/cafe24/schedules" action="/cafe24/schedules" enctype="multipart/form-data"
data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?"> data-confirm="지정한 시각에 자동으로 반영됩니다. 예약을 등록할까요?">
<input type="hidden" name="product_no" value="{{ product_no }}" /> <input type="hidden" name="product_no" value="{{ product_no }}" />
<input type="hidden" name="list_query" value="{{ list_query }}" /> <input type="hidden" name="list_query" value="{{ list_query }}" />
@@ -205,6 +205,15 @@
<option value="off">중지</option> <option value="off">중지</option>
</select> </select>
</label> </label>
{# 대표 이미지(썸네일) — 고르면 그 시각에 교체. 파일은 DB 에 보관했다가 worker 가 올린다. #}
<div class="cf24-schedule-wide cf24-schedule-image">
<span>대표 이미지</span>
<label class="cf24-file-pick">
<input type="file" name="image" id="cf24-schedule-image" accept="image/jpeg,image/png,image/gif,image/webp" />
<span class="erp-btn erp-btn-outline">파일 선택</span>
<span class="cf24-file-name" id="cf24-schedule-image-name">변경 없음</span>
</label>
</div>
<label class="cf24-schedule-wide"> <label class="cf24-schedule-wide">
<span>메모</span> <span>메모</span>
<input class="cf24-schedule-input" type="text" name="memo" maxlength="200" <input class="cf24-schedule-input" type="text" name="memo" maxlength="200"
@@ -221,7 +230,8 @@
<a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a> <a class="erp-btn erp-btn-outline" href="/cafe24/schedules">예약 목록</a>
</div> </div>
<p class="cf24-muted" style="margin:8px 0 0;"> <p class="cf24-muted" style="margin:8px 0 0;">
진열·판매만 바꾸려면 위 체크를 해제하세요. 셋 중 하나 이상은 선택해야 합니다. 대표 이미지·진열·판매만 바꾸려면 위 체크를 해제하세요. 넷 중 하나 이상은 선택해야 합니다.
대표 이미지는 JPG·PNG·GIF·WEBP, 10MB 이하(목록/축소 이미지는 카페24가 자동 생성).
</p> </p>
</form> </form>
</details> </details>
@@ -1,5 +1,5 @@
{# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #} {# 카페24 모듈 공용 상단 탭. active_tab: products | design:pc_detail | design:mobile_detail | design:swiper | schedules | system #}
<div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;"> <div class="erp-page-actions" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:10px;">
<a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" <a class="erp-btn {% if active_tab=='products' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
href="/cafe24/">상품관리</a> href="/cafe24/">상품관리</a>
<a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" <a class="erp-btn {% if active_tab=='design:pc_detail' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}"
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" /> <link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
{% endblock %} {% endblock %}
{% block content %} {% block content %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261103c" /> <link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
{% endblock %} {% endblock %}
{% block content %} {% block content %}
@@ -45,6 +45,7 @@
<thead> <thead>
<tr> <tr>
<th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th> <th class="cf24-col-no" data-sort-key="no" data-sort-type="num">번호</th>
<th class="cf24-col-thumb"></th>
<th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th> <th class="cf24-col-name" data-sort-key="name" data-sort-type="text">상품명</th>
<th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th> <th class="cf24-col-flag" data-sort-key="display" data-sort-type="num">진열</th>
<th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th> <th class="cf24-col-flag" data-sort-key="selling" data-sort-type="num">판매</th>
@@ -60,6 +61,7 @@
data-selling="{{ 1 if r.selling else 0 }}" data-selling="{{ 1 if r.selling else 0 }}"
data-updated="{{ r.updated_date }}"> data-updated="{{ r.updated_date }}">
<td class="cf24-col-no">{{ r.product_no }}</td> <td class="cf24-col-no">{{ r.product_no }}</td>
<td class="cf24-col-thumb"><img class="cf24-thumb" {% if r.thumb %}src="{{ r.thumb }}"{% endif %} loading="lazy" alt="" /></td>
<td class="cf24-col-name" title="{{ r.product_name }}"> <td class="cf24-col-name" title="{{ r.product_name }}">
<a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a> <a href="/cafe24/?{{ qs }}selected={{ r.product_no }}">{{ r.product_name }}</a>
</td> </td>
@@ -128,7 +130,7 @@
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
<script src="/static/cafe24-options.js?v=20261106b"></script> <script src="/static/cafe24-options.js?v=20261110c"></script>
<script> <script>
(function () { (function () {
var pane = document.getElementById("cf24-editor-pane"); var pane = document.getElementById("cf24-editor-pane");
@@ -561,6 +563,17 @@
// 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다. // 날짜·시간도 두 개의 별도 input 값을 합쳐 서버가 기대하는 형식으로 만든다.
var schedForm = pane.querySelector("#cf24-schedule-form"); var schedForm = pane.querySelector("#cf24-schedule-form");
if (schedForm) { if (schedForm) {
var schedImg = schedForm.querySelector("#cf24-schedule-image");
var schedImgName = schedForm.querySelector("#cf24-schedule-image-name");
if (schedImg) schedImg.addEventListener("change", function () {
var f = schedImg.files && schedImg.files[0];
if (f && f.size > 10 * 1024 * 1024) {
window.erpAlert("10MB 를 넘는 파일은 올릴 수 없습니다.");
schedImg.value = "";
f = null;
}
schedImgName.textContent = f ? f.name + " (" + Math.round(f.size / 1024) + "KB) — 그 시각에 교체" : "변경 없음";
});
schedForm.addEventListener("submit", function (e) { schedForm.addEventListener("submit", function (e) {
var box = document.getElementById("cf24-html-pc"); var box = document.getElementById("cf24-html-pc");
var holder = document.getElementById("cf24-schedule-html"); var holder = document.getElementById("cf24-schedule-html");
@@ -576,7 +589,8 @@
// 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다. // 확인창이 비동기라 일단 제출을 멈추고, 확인을 받으면 다시 보낸다.
// (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다) // (required 검사는 이미 통과한 뒤라 form.submit() 으로 보내도 안전하다)
e.preventDefault(); e.preventDefault();
window.erpConfirm(schedForm.dataset.confirm).then(function (ok) { var imgFile = schedImg && schedImg.files && schedImg.files[0];
window.erpConfirm(schedForm.dataset.confirm + (imgFile ? "\n\n대표 이미지: 「" + imgFile.name + "」(으)로 교체" : "")).then(function (ok) {
if (!ok) return; if (!ok) return;
dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다. dirty = false; // 예약 등록으로 화면을 떠나므로 편집 중 경고를 끈다.
schedForm.submit(); schedForm.submit();
@@ -915,6 +929,7 @@
window.erpAlert("상품명은 비울 수 없습니다."); window.erpAlert("상품명은 비울 수 없습니다.");
return; return;
} }
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n")) window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
.then(function (ok) { .then(function (ok) {
if (!ok) return; if (!ok) return;
@@ -929,7 +944,10 @@
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : ""; form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
commitValues(form); commitValues(form);
if (p.product_name) paintTitle(p.product_name); if (p.product_name) paintTitle(p.product_name);
setMsg(msg, (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.", "is-ok"); var done = (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.";
if (data.variants_shifted) done += " 품목 " + data.variants_shifted + "건 추가금액 조정.";
if (data.variants_error) setMsg(msg, done + " " + data.variants_error, "is-err");
else setMsg(msg, done, "is-ok");
}) })
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); }) .catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
.then(function () { btn.disabled = false; }); .then(function () { btn.disabled = false; });
@@ -955,6 +973,8 @@
if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); } if (link) { link.href = p.detail_image; link.classList.remove("is-hidden"); }
if (empty) empty.classList.add("is-hidden"); if (empty) empty.classList.add("is-hidden");
} }
var thumb = document.querySelector('#cf24-list tr.cf24-row[data-no="' + no + '"] .cf24-thumb');
if (thumb && (p.tiny_image || p.detail_image)) thumb.src = bust(p.tiny_image || p.detail_image);
root.querySelectorAll("[data-image-key]").forEach(function (el) { root.querySelectorAll("[data-image-key]").forEach(function (el) {
var v = p[el.dataset.imageKey]; var v = p[el.dataset.imageKey];
if (!v) return; if (!v) return;
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" /> <link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
{% endblock %} {% endblock %}
{% block content %} {% block content %}
@@ -37,7 +37,7 @@
<th style="width:130px;">예정 시각</th> <th style="width:130px;">예정 시각</th>
<th style="width:66px;">상품</th> <th style="width:66px;">상품</th>
<th>상품명</th> <th>상품명</th>
<th style="width:150px;">적용 내용</th> <th style="width:170px;">적용 내용</th>
<th style="width:96px;">상태</th> <th style="width:96px;">상태</th>
<th>메모 / 오류</th> <th>메모 / 오류</th>
<th style="width:130px;">등록자</th> <th style="width:130px;">등록자</th>
@@ -53,7 +53,8 @@
<a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a> <a href="/cafe24/?selected={{ r.product_no }}">{{ r.product_no }}</a>
</td> </td>
<td>{{ r.product_name or '—' }}</td> <td>{{ r.product_name or '—' }}</td>
<td class="cf24-nowrap">{{ r.action_label }}</td> <td class="cf24-nowrap">{{ r.action_label }}
{% if r.image_type %}<a href="/cafe24/schedules/{{ r.id }}/image" target="_blank" rel="noopener" title="{{ r.image_name }}"><img class="cf24-sched-img" src="/cafe24/schedules/{{ r.id }}/image" alt="{{ r.image_name }}" loading="lazy" /></a>{% endif %}</td>
<td class="cf24-nowrap"> <td class="cf24-nowrap">
{% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span> {% if r.status == 'SUCCESS' %}<span class="erp-badge cf24-badge-ok">{{ r.status_label }}</span>
{% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span> {% elif r.status == 'FAILED' %}<span class="cf24-err">{{ r.status_label }}</span>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" /> <link rel="stylesheet" href="/static/cafe24.css?v=20261110a" />
{% endblock %} {% endblock %}
{% block content %} {% block content %}
+9
View File
@@ -396,6 +396,8 @@ class FakeCafe24:
self._variant_puts += 1 self._variant_puts += 1
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk: if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422) raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
if (json or {}).get("shop_no", 1) != 1: # 다른 쇼핑몰 — 기본몰 상태는 그대로
return {"variants": [dict(r) for r in (json or {}).get("requests") or []]}
out = [] out = []
for r in (json or {}).get("requests") or []: for r in (json or {}).get("requests") or []:
for var in self.variants: for var in self.variants:
@@ -411,6 +413,13 @@ class FakeCafe24:
def post(self, path, *, json=None, **kw): def post(self, path, *, json=None, **kw):
self.calls.append(("POST", path, json)) self.calls.append(("POST", path, json))
if path == f"/admin/products/{self.product_no}/images": # 대표이미지 등록(A 타입)
self._tick()
n = sum(1 for c in self.calls if c[1] == path)
image = {k: f"/web/product/{k.split('_')[0]}/{self.product_no}_{n}.png"
for k in ("detail_image", "list_image", "tiny_image", "small_image")}
self.state.update(image)
return {"image": image}
out = self._options_call("POST", path, json) out = self._options_call("POST", path, json)
return copy.deepcopy(out) if out is not None else {} return copy.deepcopy(out) if out is not None else {}
+63
View File
@@ -649,6 +649,9 @@ def test_describe_schedule_action():
assert store.describe_schedule_action( assert store.describe_schedule_action(
has_html=False, set_display=None, set_selling=None has_html=False, set_display=None, set_selling=None
) == "없음" ) == "없음"
assert store.describe_schedule_action(
has_html=True, set_display=None, set_selling=None, has_image=True
) == "대표이미지 · 상세페이지"
def test_normalize_schedule_status(): def test_normalize_schedule_status():
@@ -1083,6 +1086,22 @@ def test_resolve_description_accepts_iso_created_at():
assert (html, state) == ("NEW", store.SYNC_PENDING) assert (html, state) == ("NEW", store.SYNC_PENDING)
def test_parse_shop_nos():
assert store.parse_shop_nos(None) == [1]
assert store.parse_shop_nos("2, 3,1,x,0,3") == [1, 2, 3]
def test_plan_flag_sync():
from app.modules.cafe24.sync_variant_flags import plan_flag_sync
base = [{"variant_code": "A", "display": True, "selling": False},
{"variant_code": "B", "display": True, "selling": True},
{"variant_code": "C", "display": False, "selling": False}]
shop = [{"variant_code": "A", "display": "F", "selling": "F"},
{"variant_code": "B", "display": "T", "selling": "T"}] # C 는 그 쇼핑몰에 없음
assert plan_flag_sync(base, shop) == [{"variant_code": "A", "display": "T"}]
def test_parse_grace_minutes(): def test_parse_grace_minutes():
assert store.parse_grace_minutes("30") == 30 assert store.parse_grace_minutes("30") == 30
assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN
@@ -1285,6 +1304,38 @@ def test_delete_variant_wrapper():
assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A") assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A")
def test_shift_additional_amounts_keeps_sale_price():
"""판매가 7900 → 12700: 품목 판매 가격(판매가+추가금액)은 그대로, 추가금액만 -4800."""
variants = [{"variant_code": "P000000R000A", "additional_amount": "0.00"},
{"variant_code": "P000000R000B", "additional_amount": "18000.00"}]
assert store.shift_additional_amounts(variants, "7900.00", "12700.00") == [
{"variant_code": "P000000R000A", "additional_amount": "-4800"},
{"variant_code": "P000000R000B", "additional_amount": "13200"},
]
assert store.shift_additional_amounts(variants, "7900.00", "7900") == []
assert store.shift_additional_amounts(variants, "", "7900") == []
def test_keep_variant_sale_prices_puts_shifted_amounts():
from types import SimpleNamespace
from app.modules.cafe24 import routes_product_info as rpi
client = _RouteClient({
"GET /admin/products/7/options": {"option": {"has_option": "T", "options": []}},
"GET /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "6000.00"}]},
"PUT /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]},
})
st = fakes.MemoryStore()
out = rpi._keep_variant_sale_prices(st, SimpleNamespace(client=client), 7, "7900.00", "12900.00")
assert out["count"] == 1 and out["error"] == ""
put = [c for c in client.calls if c[0] == "PUT"][-1]
assert put[2]["requests"] == [{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]
assert st.get_write_snapshot(7)["variants"]["data"]["P000000R000A"]["additional_amount"] == "1000.00"
def test_build_variant_updates(): def test_build_variant_updates():
rows = [ rows = [
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"}, {"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},
@@ -1302,6 +1353,18 @@ def test_build_variant_updates():
pass pass
else: else:
raise AssertionError("bad code accepted") raise AssertionError("bad code accepted")
# 재고관리 사용 · 수량 · 품절표시
assert store.build_variant_updates([
{"variant_code": "P000000R000A", "use_inventory": "on", "quantity": "1,200", "display_soldout": "off"},
{"variant_code": "P000000R000B", "quantity": ""}, # 빈 수량 → 변경 없음
]) == [{"variant_code": "P000000R000A", "use_inventory": "T", "display_soldout": "F", "quantity": 1200}]
for bad in ("-1", "x"):
try:
store.build_variant_updates([{"variant_code": "P000000R000A", "quantity": bad}])
except ValueError:
pass
else:
raise AssertionError(bad)
# 드래그 정렬 → display_order (1~300) # 드래그 정렬 → display_order (1~300)
assert store.build_variant_updates([{"variant_code": "P000000R000A", "display_order": "3"}]) == [ assert store.build_variant_updates([{"variant_code": "P000000R000A", "display_order": "3"}]) == [
{"variant_code": "P000000R000A", "display_order": 3} {"variant_code": "P000000R000A", "display_order": 3}
+32
View File
@@ -50,6 +50,7 @@ from app.timezone import now_kst
from . import store, writes from . import store, writes
from .common import read_lag_grace_minutes from .common import read_lag_grace_minutes
from .routes_products import load_product
logger = logging.getLogger("cafe24.worker") logger = logging.getLogger("cafe24.worker")
@@ -77,9 +78,28 @@ def _summary(row: dict[str, Any]) -> str:
has_html=bool(row.get("revision_id")), has_html=bool(row.get("revision_id")),
set_display=row.get("set_display"), set_display=row.get("set_display"),
set_selling=row.get("set_selling"), set_selling=row.get("set_selling"),
has_image=bool(row.get("image_type")),
) )
def _apply_image(st: Any, api: Any, product_no: int, data: bytes, content_type: str) -> str:
"""예약 대표 이미지 교체(routes_product_info.product_image 와 같은 순서). 반환: 새 detail_image.
상세페이지·진열/판매보다 **먼저** 한다 — 뒤 단계가 실패해 재시도되면 같은 이미지를 한 번 더
올릴 뿐이라 안전하고, 앞 단계(시도 기록)가 SUCCESS 로 복구된 뒤 이미지가 빠지는 일이 없다.
"""
current, _ = load_product(st, api, product_no)
if not current:
raise Cafe24Error("카페24에서 상품을 찾지 못했습니다.")
images = products.set_main_image(api.client, product_no, data, content_type=content_type)
if not images.get("detail_image"):
raise Cafe24Error("카페24가 등록된 이미지 경로를 돌려주지 않았습니다.")
writes.remember_product_write(
st, product_no, {**current, **images, "updated_date": now_kst().isoformat(timespec="seconds")}
)
return str(images["detail_image"])
def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str: def _retry_or_fail(st: Any, row: dict[str, Any], token: str, error: str) -> str:
"""재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태.""" """재시도 예산 안이면 PENDING + 대기, 아니면 FAILED. 반환: 결과 상태."""
retry_count = int(row.get("retry_count") or 0) retry_count = int(row.get("retry_count") or 0)
@@ -113,6 +133,8 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
def fence() -> bool: def fence() -> bool:
return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease)) return bool(st.renew_schedule_lease(schedule_id, token, ttl_seconds=lease))
image_type = str(row.get("image_type") or "")
new_image = ""
try: try:
html: str | None = None html: str | None = None
if revision_id: if revision_id:
@@ -122,10 +144,19 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
html = str(revision.get("html_content") or "") html = str(revision.get("html_content") or "")
if not html.strip(): if not html.strip():
raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.") raise Cafe24Error(f"버전 {revision_id} 의 내용이 비어 있습니다.")
image = st.get_schedule_image(schedule_id) if image_type else b""
if image_type and not image:
raise Cafe24Error("예약해 둔 대표 이미지 파일을 찾을 수 없습니다.")
with writes.write_lock( with writes.write_lock(
st, writes.product_lock_key(product_no), actor=ACTOR, st, writes.product_lock_key(product_no), actor=ACTOR,
purpose=f"예약 #{schedule_id} 실행", wait_seconds=0, purpose=f"예약 #{schedule_id} 실행", wait_seconds=0,
) as lock: ) as lock:
if image:
if not fence():
raise writes.WriteBusy("예약 lease 를 잃었습니다 — 다른 worker 가 처리합니다.")
new_image = _apply_image(st, api, product_no, image, image_type)
outcome = writes.WriteOutcome()
if html is not None or set_display is not None or set_selling is not None:
outcome = writes.write_product( outcome = writes.write_product(
st, api, product_no, st, api, product_no,
lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html, lock=lock, origin=store.ORIGIN_SCHEDULED, actor=ACTOR, html=html,
@@ -171,6 +202,7 @@ def run_one(st: Any, api: Any, row: dict[str, Any]) -> str:
revision_id=outcome.revision_id or (int(revision_id) if revision_id else None), revision_id=outcome.revision_id or (int(revision_id) if revision_id else None),
schedule_id=schedule_id, result="SUCCESS", schedule_id=schedule_id, result="SUCCESS",
detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "") detail=summary + (f" (백업 {outcome.backup_id})" if outcome.backup_id else "")
+ (f" / 대표이미지 → '{new_image}'" if new_image else "")
+ (f" / {note}" if note else ""), + (f" / {note}" if note else ""),
) )
logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary) logger.info("예약 #%s 상품 %s 적용 완료 — %s", schedule_id, product_no, summary)
@@ -2,7 +2,7 @@
{% block head_extra %} {% block head_extra %}
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} {# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" /> <link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script> <script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
@@ -249,7 +249,7 @@
{% endblock %} {% endblock %}
{% block scripts %} {% block scripts %}
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
<script src="/static/cupang-outbound.js?v=20261023d" defer></script> <script src="/static/cupang-outbound.js?v=20261023d" defer></script>
<script> <script>
(function () { (function () {
+1 -1
View File
@@ -33,6 +33,6 @@
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것. `GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정). - 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON). - 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`). - **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live). 고른 적 없으면 브라우저·OS 첫 언어가 ko… → 한글, 그 밖 → 영어(2026-11-20, `app/lang.py detect_lang`, 말레이시아 실적과 같은 규칙). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다. **새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로. - 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
+3 -1
View File
@@ -35,7 +35,9 @@ def _store(request: Request) -> Any:
def _lang(request: Request) -> str: def _lang(request: Request) -> str:
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE)) from app.lang import detect_lang # noqa: WPS433 — 고른 값(쿠키) 없으면 브라우저·OS 언어(2026-11-20)
return detect_lang(request.cookies.get(i18n.LANG_COOKIE), request.headers.get("accept-language"))
def _t(request: Request, text: str) -> str: def _t(request: Request, text: str) -> str:
@@ -32,4 +32,4 @@
<div style="display:flex;justify-content:flex-end;margin-bottom:8px;"> <div style="display:flex;justify-content:flex-end;margin-bottom:8px;">
<button type="button" id="mys-lang-toggle" class="erp-btn erp-btn-outline">ENG</button> <button type="button" id="mys-lang-toggle" class="erp-btn erp-btn-outline">ENG</button>
</div> </div>
<script src="/static/malaysia.js?v=20260622a"></script> <script src="/static/malaysia.js?v=20261120a"></script>
@@ -0,0 +1,46 @@
# [말레이시아 실적] — `app/modules/malaysia_performance/`, `malaysia_performance_db` (2026-11-20)
> 이 폴더는 **얇은 마운트**(`__init__.py` 하나)다. 코드·템플릿·`performance.js/css` 는 전부 실적 모듈(`app/modules/performance/`) 것을 그대로 쓴다.
> 실적과 다른 점은 `app/modules/performance/variant.py` 의 `MY` 한 곳. 실적 화면·기능을 고치면 이 화면에도 그대로 들어간다 — 둘 다 확인.
## 구성
- 주소 `/malaysia/performance/`(매출 실적) · `/ads`(광고비) · `/settings`(톱니). 권한키 `malaysia_performance`. 메뉴 "말레이시아 실적"(관리).
- `main.py`: `app.state.malaysia_performance_store` = `MALAYSIA_PERFORMANCE_DB_URL`(없으면 "설정 필요"), `include_router` 는 실적 다음(라우트 이름은 실적이 먼저).
- 요청 → 마운트 의존성 `variant.use_malaysia`(async) → ContextVar `MY` → `common.get_store`·권한·`base_ctx`·`ad_spend.channel_names/roas_sales`·`dashboard.sales_ad_channels/load_unit`·금액 파싱이 이 값을 본다.
## 매출 실적
- 쇼핑몰 = 틱톡·쇼피·라자다 **그룹**(합계 열), 각 그룹 하위 **쇼핑몰**·**라이브커머스** 두 칸(직접 추가 쇼핑몰 = 수동 입력 전용). 그룹 열 = 두 칸 합계, 일 합계 = 6칸 합계.
코드 `group_<쇼핑몰>`·`custom_<쇼핑몰>_shop`·`custom_<쇼핑몰>_live` — `scripts/sql/malaysia_performance_db_seed.sql` 과 `variant.MY` 가 같아야 한다(이름은 설정에서 바꿔도 됨).
- 금액 = **RM 소수 2자리**. 저장은 **센(0.01 RM) 정수**(`variant.MY.scale = 100`) — 계산·수수료·ROAS 코드는 실적 그대로.
입력 `formula.parse_amount(raw, scale)`·엑셀 `manual_upload.parse_amount(v, scale)`(RM 글자 허용), 화면 `dashboard.amount_text(v, "rm")`·`variant.num_text/money_text/input_text`, JS `money()`(`.perf data-cents`).
- 매출 업데이트 버튼·다음 업데이트·화면 자동 새로 고침 없음(API 수집 없음 — `jobs` 는 한국 실적 것). 엑셀 업로드 샘플은 지금 쇼핑몰 이름으로 만든다(`router._manual_sample_from`).
- 그룹 칸 아래 주황 줄 = 그 쇼핑몰 광고비(ROAS%), ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비(`variant.MY.ad_lines`·`ad_roas_sales`).
## 광고비
- 채널 = 틱톡·쇼피·라자다(`tiktok`·`shopee`·`lazada`), 날짜 칸 직접 입력만(업로드·광고 API 없음). 금액 RM(센 저장).
## 설정
- 쇼핑몰 표(사용·매출 집계·수동 입력·수수료율·이름·그룹·순서·추가/삭제) + 보기 설정 + 공통 보기 설정(열 숨기기). API 인증·광고 API·자동 업데이트·암호화 키·과거 매출·테스트 데이터 카드 없음, 매출 단위 = RM 고정.
## 한글·영문 전환 (2026-11-20)
- 탭 줄 오른쪽(톱니 왼쪽) [한글|EN] — 쿠키 `mperf_lang`(path=/malaysia/performance). 고른 적 없으면 브라우저·OS 첫 언어(`Accept-Language`) ko… → 한글, 그 밖 → 영어(`app/lang.py`, 라이브·말레이시아 재고도 같은 규칙).
- 서버가 언어를 정한다: `variant.use_malaysia` 가 `variant.lang()` 설정 → 템플릿 `lang`, `.perf data-lang`, 머리 제목(`common.base_ctx`), 공휴일(말레이시아 — `live/holidays.py` 공유).
- 영문이면 `static/performance-en.js` 를 performance.js 앞에 싣는다 — 한국 실적과 같은 템플릿·JS 라 **한글을 그대로 그린 뒤 바꾼다**
(사전 `EN` · 패턴 `RULES` · 낱말 `PHRASES`, 나중에 생기는 창·메뉴·알림까지). 번역이 끝날 때까지 `.perf` 숨김(못 실으면 1.5초 뒤 보임).
굵은 글자 섞인 긴 안내 문단은 템플릿에 `{% if lang == 'en' %}` 로 따로 썼다.
- **실적 화면 문구를 새로 넣거나 바꾸면 `performance-en.js` 에도** — `tests/js/perf_malaysia_en.browser.test.js` 가 영문 화면·창·알림에 한글이 남았는지 찍어 준다.
- 쇼핑몰 이름(DB 값)은 낱말 치환(틱톡·쇼피·라자다·쇼핑몰·라이브커머스) — 다른 이름으로 바꾸면 그 이름은 한글 그대로일 수 있다.
## DB
- `malaysia_performance_db` = performance_db **구조만 복사**(`pg_dump --schema-only`) + seed. 역할 `performance_app` 공유. 만드는 순서는 seed 파일 머리말.
- performance_db 에 새 마이그레이션을 만들면 이 DB 에도 적용한다.
## 테스트
- `app/modules/performance/tests/test_malaysia_variant.py`(센 파싱·그룹 합계·광고비 줄·화면 주소·API 저장 단위·샘플), `tests/js/perf_malaysia.browser.test.js`(렌더 `perf_my_*.html`).
@@ -0,0 +1,22 @@
"""[말레이시아 실적] — 실적 모듈(app/modules/performance) 코드·화면을 그대로 쓰는 두 번째 인스턴스(2026-11-20).
주소 /malaysia/performance/…, 저장 malaysia_performance_db(실적과 같은 표 구조), 권한키 malaysia_performance.
다른 점은 performance/variant.py MY 한 곳 — 틱톡·쇼피·라자다(쇼핑몰·라이브커머스) 수동 입력, RM 소수 2자리(센 정수 저장).
"""
from typing import Any
from fastapi import APIRouter, Depends
from ..performance import build_performance_store
from ..performance import router as _performance_router
from ..performance.variant import use_malaysia
router = APIRouter(prefix="/malaysia")
router.include_router(_performance_router, dependencies=[Depends(use_malaysia)])
__all__ = ["router", "build_malaysia_performance_store"]
def build_malaysia_performance_store(*, dsn: str | None) -> Any:
return build_performance_store(dsn=dsn)
@@ -2,7 +2,7 @@
{% block head_extra %} {% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <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> <script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %} {% endblock %}
@@ -64,7 +64,7 @@
</section> </section>
</div> </div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script> <script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script> <script src="/static/erp-notice-admin.js?v=20261111a" defer></script>
{% endif %} {% endif %}
{% endblock %} {% endblock %}
+17 -11
View File
@@ -4,6 +4,14 @@
> 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`. > 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`.
> 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유. > 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유.
## 두 인스턴스 — [실적] · [말레이시아 실적] (2026-11-20)
- 같은 코드·템플릿·`performance.js` 를 `/performance`(한국, `performance_db`)와 `/malaysia/performance`(`malaysia_performance_db`)에 붙인다.
다른 점은 **`variant.py` 한 곳**(`KR`·`MY`) — 저장소·권한키·주소·광고 채널·통화. 요청마다 `variant.current()`(ContextVar, 말레이시아 마운트 의존성 `use_malaysia`).
- 고칠 때: 주소는 템플릿 `{{ pv.base }}`·JS `BASE`(`.perf data-base`)만 — **`/performance` 를 새로 하드코딩하지 말 것**.
금액 글자는 `num`·`money_t`·`inval`(템플릿)·`money()`(JS) — 말레이시아는 센 정수(÷100, RM 소수 2자리, `data-cents`). 한국 전용 기능(API 수집·자동 업데이트·광고 API·카페24 열)은 `pv.is_kr` 로.
- 상세 `app/modules/malaysia_performance/CLAUDE.md`. 마이그레이션은 두 DB 모두에.
## 구조 (네 영역 분리) ## 구조 (네 영역 분리)
1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리). 1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리).
@@ -79,7 +87,7 @@
## 매출 실적 화면 (2026-10-19) ## 매출 실적 화면 (2026-10-19)
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다. - KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 % + **전년 같은 기간 대비 %**(2026-11-16, `calc.Period.yoy_range` — 1년 전 같은 날짜, 진행 중이면 오늘까지, 연 보기는 직전 비교가 이미 전년이라 없음), 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀). - 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김). - 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload. - **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
@@ -87,7 +95,12 @@
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림 (`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`. (마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `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` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음. - 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타·카톡 플친 줄(이름 붙임, 카페24(전체)·카페24(실적) 같은 줄), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **열 접기**(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 작은 화살표 버튼(`.perf-cfold`, `performance.js initColFold`)으로 열 하나씩 접기/펴기(날짜 열 빼고, 일 합계·그룹 열 포함).
접은 열 = 26px 띠(`is-cfold`, 칸 내용 숨김·클릭/메모 안 됨, 너비는 JS `CFOLD_W` 와 CSS 같게, 수동 열 너비 표도 같음). **로그인한 사람 본인에게만** —
`PUT /api/my-col-fold {kind: sales|ads, cols}` → `perf_settings` key `col_fold:<이메일 sha1>`(key 64자 제한) = `{sales, ads}`, 화면은 표 `data-col-fold`(라우터 `_load_col_fold`). 011 미적용이면 다 펼침·저장 503.
버튼 위 말풍선 = 커서 바로 위를 따라다니는 `.perf-cfold-tip`(열 이름, 12px 굵게 = 제목 글자), 버튼 `title=""` 로 머리글 기본 말풍선 막음.
그룹 하위 열 접기(⊟, localStorage)와는 별개. 테스트 `tests/js/perf_colfold.browser.test.js`, `test_custom_groups.py::test_api_my_col_fold_per_user`.
- **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`). - **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`).
수동 = 매출 실적·광고비 일자별 표에 `perf-colw-manual` → `performance.js initColWidths` 가 자동 너비를 잰 뒤 `table-layout:fixed`(`is-colw-fixed`, 넘치는 글자 …), 수동 = 매출 실적·광고비 일자별 표에 `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`)에 계속 유지, 머리글 오른쪽 경계 `.perf-colw-grip` 드래그(최소 36px)·두 번 누르면 그 열만 자동. **날짜 열(`label`)은 조절 불가 — 늘 자동 너비, 손잡이 없음, 저장값 무시**. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지,
@@ -106,19 +119,12 @@
- **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로. - **표 몸통 칸에는 풍선 도움말(title) 없음**(2026-10-22 사용자 요청) — 입력 칸·날짜 칸(공휴일은 칸 안 글자)·광고비 줄 모두. 열 머리글 말풍선은 그대로.
새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에). 새 칸 기능에 title 을 다시 달지 말 것(설명은 표 아래 안내 문구에).
## 틱톡 (`/performance/tiktok`, 2026-11-05, 마이그레이션 없음)
- 광고비 탭 틀(기간 이동·KPI·표·그래프·연 누적), 표 열 = ROAS·광고비·매출. 값은 광고 API 만(읽기 전용, 칸 입력·메모 없음). 화면 데이터 `ad_spend.build_tiktok_dashboard`.
- **틱톡 탭에서만 보임** — 채널 코드 `tiktok` 은 `ad_sources` 에는 있지만 `ad_spend.CHANNELS` 에는 넣지 않는다(넣으면 광고비 탭 합계에 들어감). 쇼핑몰 표(`perf_marketplaces`)에도 없어 매출 실적 합계·열과 무관. 저장은 다른 광고 API 처럼 `perf_ad_spend`(`source='api'`), 매출 = `metrics["매출"]`.
- 설정 = 실적 설정 **광고 API 연동** 카드 → 틱톡 — 광고 계정 ID·장기 액세스 토큰·틱톡샵 ID(선택). [광고비 업데이트]·광고비 자동 업데이트에 함께 돈다.
- `ad_sources/tiktok_ads.py` — `report/integrated/get`(30일씩), 매출 = 웹 구매금액 + 틱톡샵 매출, 틱톡샵 ID 가 있으면 `gmv_max/report/get` 비용·매출도 더함(항목별 값은 metrics 에 따로 저장). 외화 계정은 그날 환율로 원화(`fx`). ROAS = 매출 ÷ 광고비.
**실제 토큰 대조 전**(2026-11-05) — 공식 문서를 읽지 못해 지표 이름은 이차 자료로 확인. 일반 보고서에 GMV Max 가 이미 들어 있으면 틱톡샵 ID 를 넣었을 때 중복되므로, 처음 쓸 때 광고 관리자 화면과 대조할 것.
## 광고비 (`/performance/ads`) ## 광고비 (`/performance/ads`)
- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니. - 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니. (틱톡 탭은 2026-11-20 삭제 — 코드·`tiktok_ads.py`·데이터(마이그레이션 012) 모두)
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정). - **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감. - **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- **카톡 플친** 열(`kakao_pf`, 메타 오른쪽, 2026-11-16) — 직접 입력, `NO_SALES` 라 ROAS 없음. 매출 탭 카페24 칸 아래 구글·메타 다음 줄, 일 합계 광고비에도 더함.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로. - `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`). - 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드. - 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
@@ -1,14 +1,12 @@
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다 — """광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
틱톡만 예외: 광고비 탭에 안 나오게 CHANNELS 에 넣지 않고 틱톡 탭이 따로 읽는다)."""
from __future__ import annotations from __future__ import annotations
from .base import AdSource from .base import AdSource
from .google_ads import GoogleAdsSource from .google_ads import GoogleAdsSource
from .meta_ads import MetaAdsSource from .meta_ads import MetaAdsSource
from .tiktok_ads import TiktokAdsSource
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource(), TiktokAdsSource()) _SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
_BY_CODE = {s.code: s for s in _SOURCES} _BY_CODE = {s.code: s for s in _SOURCES}
@@ -1,202 +0,0 @@
"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴).
인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다.
조회
GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day.
매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value).
GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다.
- 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다.
- 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음).
- ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다).
공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다.
"""
from __future__ import annotations
import json
import re
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
import httpx
from app.timezone import today_kst
from .. import fx
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired
from .base import AdDay, AdSource
from .meta_ads import _num, _won
API_BASE = "https://business-api.tiktok.com/open_api/v1.3"
MAX_DAYS = 366
SPAN_DAYS = 30
PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다
RATE_LIMIT = 40100
REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate",
"onsite_shopping", "total_onsite_shopping_value")
GMV_METRICS = ("cost", "gross_revenue", "orders")
# metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard).
M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)"
M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수"
M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출"
def _http(ctx: AdapterContext) -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=ctx.timeout_sec)
def _spans(start: date, end: date) -> list[tuple[date, date]]:
"""기간을 SPAN_DAYS 일씩 나눈다."""
out = []
while start <= end:
stop = min(start + timedelta(days=SPAN_DAYS - 1), end)
out.append((start, stop))
start = stop + timedelta(days=1)
return out
class TiktokAdsSource(AdSource):
code = "tiktok"
name = "틱톡"
docs_url = "https://business-api.tiktok.com/portal/docs"
note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). "
"준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678",
help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."),
CredentialField("access_token", "액세스 토큰", secret=True,
help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만",
help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."),
]
def validate_credentials(self, values: dict[str, str]) -> list[str]:
errors = super().validate_credentials(values)
advertiser = (values.get("advertiser_id") or "").strip()
if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser):
errors.append("광고 계정 ID 는 숫자여야 합니다.")
shop = (values.get("shop_id") or "").strip()
if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop):
errors.append("틱톡샵 ID 는 숫자여야 합니다.")
token = (values.get("access_token") or "").strip()
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
return errors
def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다."""
ctx.progress.check()
token = (ctx.credentials.get("access_token") or "").strip()
try:
resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token})
except httpx.HTTPError as exc:
raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
try:
body = resp.json()
except ValueError:
raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None
code = body.get("code") if isinstance(body, dict) else None
if resp.status_code == 200 and code == 0:
return body.get("data") or {}
text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}"
if code == 40102:
raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.")
if code == RATE_LIMIT:
raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.")
if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200):
raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.")
raise ApiError(text)
def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]:
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
rows = self._get(ctx, client, "/advertiser/info/", {
"advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or []
if not rows:
raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.")
return rows[0]
def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date,
**extra: Any) -> list[tuple[date, dict[str, Any]]]:
"""보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로."""
advertiser = (ctx.credentials.get("advertiser_id") or "").strip()
out = []
for s, e in _spans(start, end):
data = self._get(ctx, client, path, {
"advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics),
"start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra})
for r in data.get("list") or []:
try:
day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10])
except ValueError:
continue
out.append((day, r.get("metrics") or {}))
return out
def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]:
"""날짜 → 항목 합(계정 통화)."""
sums: dict[date, dict[str, Decimal]] = {}
def day_of(d: date) -> dict[str, Decimal]:
return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")})
for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end,
report_type="BASIC", data_level="AUCTION_ADVERTISER"):
one = day_of(d)
one["spend"] += _num(m.get("spend"))
one["impr"] += _num(m.get("impressions"))
one["clicks"] += _num(m.get("clicks"))
one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping"))
one["web"] += _num(m.get("total_complete_payment_rate"))
one["shop"] += _num(m.get("total_onsite_shopping_value"))
shop_id = (ctx.credentials.get("shop_id") or "").strip()
if shop_id:
for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])):
one = day_of(d)
one["orders"] += _num(m.get("orders"))
one["gmv_cost"] += _num(m.get("cost"))
one["gmv"] += _num(m.get("gross_revenue"))
return sums
def test_connection(self, ctx: AdapterContext) -> str:
self.require_configured(ctx)
yesterday = today_kst() - timedelta(days=1)
with _http(ctx) as client:
info = self._info(ctx, client)
self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인
return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})"
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
if end < start:
start, end = end, start
if (end - start).days + 1 > MAX_DAYS:
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
self.require_configured(ctx)
with _http(ctx) as client:
currency = str(self._info(ctx, client).get("currency") or "").upper()
if not re.fullmatch(r"[A-Z]{3}", currency):
raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.")
sums = self._collect(ctx, client, start, end)
try:
rates = fx.krw_rates(client, currency, start, end) if sums else {}
except fx.FxError as exc:
raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
return [_day(d, sums[d], rates[d]) for d in sorted(sums)]
def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay:
"""합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로."""
spend = (a["spend"] + a["gmv_cost"]) * rate
revenue = (a["web"] + a["shop"] + a["gmv"]) * rate
roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None
return AdDay(day=day, amount=_won(spend), roas=roas, metrics={
M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None,
M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate),
M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]),
})
+24 -64
View File
@@ -26,15 +26,15 @@ from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
from typing import Any, Callable, Mapping, Sequence from typing import Any, Callable, Mapping, Sequence
from . import calc from . import calc, variant
from .ad_sources.base import ACCOUNTS_KEY from .ad_sources.base import ACCOUNTS_KEY
from .ad_sources.tiktok_ads import M_REVENUE as TIKTOK_REVENUE_KEY
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang). # 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
CHANNELS: tuple[tuple[str, str], ...] = ( CHANNELS: tuple[tuple[str, str], ...] = (
("google", "구글"), ("google", "구글"),
("meta", "메타"), ("meta", "메타"),
("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래
("naver", "네이버"), ("naver", "네이버"),
("coupang_wing", "쿠팡(윙)"), ("coupang_wing", "쿠팡(윙)"),
("coupang_rocket", "쿠팡(로켓)"), ("coupang_rocket", "쿠팡(로켓)"),
@@ -55,10 +55,20 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합. # 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
FILE_ROAS = frozenset({"google", "meta", "naver"}) FILE_ROAS = frozenset({"google", "meta", "naver"})
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널) NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다 NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24)
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: 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" ROAS_SALES_CODE["coupang_wing"] = "coupang"
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
def channel_names() -> dict[str, str]:
"""지금 인스턴스의 광고비 탭 채널(순서 = 표 열) — 한국 실적 = CHANNELS, 말레이시아 실적 = 틱톡·쇼피·라자다(variant.MY)."""
return dict(variant.current().ad_channels or CHANNELS)
def roas_sales() -> dict[str, tuple[str, ...]]:
"""광고 채널 → ROAS 매출 쇼핑몰 코드들(그 합계 ÷ 광고비). 말레이시아 = 쇼핑몰 + 라이브커머스."""
v = variant.current()
return dict(v.ad_roas_sales) if v.ad_channels else {ch: (c,) for ch, c in ROAS_SALES_CODE.items()}
def roas(sales: int, spend: int) -> int | None: def roas(sales: int, spend: int) -> int | None:
@@ -70,7 +80,7 @@ def roas(sales: int, spend: int) -> int | None:
def roas_basis(code: str) -> str: def roas_basis(code: str) -> str:
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값).""" """머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code) return "" if code not in roas_sales() else channel_names().get(code, code)
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int], def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
@@ -95,8 +105,8 @@ def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None.""" """채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
if code in FILE_ROAS: if code in FILE_ROAS:
return file_of(code) if file_of else None return file_of(code) if file_of else None
mcode = ROAS_SALES_CODE.get(code) mcodes = roas_sales().get(code)
return None if mcode is None else roas(sales_of(mcode), spend) return None if mcodes is None else roas(sum(sales_of(m) for m in mcodes), spend)
ROCKET_DATE_COL = 0 # 1열 날짜 ROCKET_DATE_COL = 0 # 1열 날짜
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세) ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
@@ -506,64 +516,14 @@ def _period_nav(period: Any, today: date) -> dict[str, Any]:
]} ]}
def build_tiktok_dashboard(store: Any, *, kind: str, anchor: date, today: date, custom_from: date | None = None,
custom_to: date | None = None, holidays: Mapping[str, str] | None = None) -> dict[str, Any]:
"""틱톡 탭(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프, 열 = ROAS·광고비·매출. 광고 API 가 저장한 perf_ad_spend 만 읽는다.
CHANNELS 에 없어 광고비 탭·매출 실적 합계에는 들어가지 않는다."""
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today)
ref = period.end if period.end < today else today if period.start <= today else period.start
year_period = calc.resolve_period("year", ref)
migration_needed = False
try:
rows = store.ad_details(TIKTOK, min(period.start, cmp_start, year_period.start), max(period.end, year_period.end))
except AdMigrationNeeded:
rows, migration_needed = [], True
cells: dict[tuple[date, str], calc.Money] = {}
for r in rows:
d = date.fromisoformat(r["date"])
cells[(d, "spend")] = calc.Money(gross=int(r["amount"] or 0))
cells[(d, "sales")] = calc.Money(gross=int((r["metrics"] or {}).get(TIKTOK_REVENUE_KEY) or 0))
table = calc.main_table(period, ("spend", "sales"), cells, today=today, holidays=holidays)
for row in table:
row["roas"] = roas(row["cells"]["sales"]["gross"], row["cells"]["spend"]["gross"])
cur = {c: calc.sum_range(cells, [c], period.start, period.end).gross for c in ("spend", "sales")}
prev = {c: calc.sum_range(cells, [c], cmp_start, cmp_end).gross for c in ("spend", "sales")}
word = _period_word(period, today)
spend_y = calc.year_months(year_period.start.year, ["spend"], cells, today=today)
sales_y = calc.year_months(year_period.start.year, ["sales"], cells, today=today)
year_rows = [{"label": a["label"], "future": a["future"], "spend": a["gross"], "sales": b["gross"],
"roas": None if a["future"] else roas(b["gross"], a["gross"])}
for a, b in zip(spend_y["rows"], sales_y["rows"])]
return {
"nav": _period_nav(period, today),
"period": period,
"period_kind": period.kind,
"today": today.isoformat(),
"kpis": [
{"key": "spend", "label": f"{word} 광고비", "value": cur["spend"], "primary": True,
"delta": calc.pct_change(cur["spend"], prev["spend"]), "cmp": cmp_label, "invert": True},
{"key": "sales", "label": f"{word} 매출", "value": cur["sales"],
"delta": calc.pct_change(cur["sales"], prev["sales"]), "cmp": cmp_label},
{"key": "roas", "label": f"{word} ROAS", "pct": roas(cur["sales"], cur["spend"])},
],
"table": table,
"chart_sales": calc.daily_series(period, ["sales"], cells),
"chart_spend": calc.daily_series(period, ["spend"], cells),
"year": {"year": year_period.start.year, "rows": year_rows, "spend": spend_y["total"]["gross"], "sales": sales_y["total"]["gross"],
"roas": roas(sales_y["total"]["gross"], spend_y["total"]["gross"])},
"migration_needed": migration_needed,
}
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date, def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
custom_from: date | None = None, custom_to: date | None = None, custom_from: date | None = None, custom_to: date | None = None,
holidays: Mapping[str, str] | None = None, holidays: Mapping[str, str] | None = None,
sales_codes: Sequence[str] = ()) -> dict[str, Any]: sales_codes: Sequence[str] = ()) -> dict[str, Any]:
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적. """광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다.""" sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
codes = list(CHANNEL_CODES) names = channel_names()
codes = list(names)
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to) period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
cmp_start, cmp_end, cmp_label = period.compare_range(today) cmp_start, cmp_end, cmp_label = period.compare_range(today)
ref = period.end if period.end < today else today if period.start <= today else period.start ref = period.end if period.end < today else today if period.start <= today else period.start
@@ -593,7 +553,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비) # 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
total_codes = list(sales_codes) total_codes = list(sales_codes)
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes)) need = sorted({m for ms in roas_sales().values() for m in ms} | set(total_codes))
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()} sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int: def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
@@ -608,7 +568,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True, {"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True}, "delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio, {"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"}, "note": f"총매출 {variant.money_text(sales_total)}" if sales_total else "매출 없음"},
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross, {"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}, "delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
] ]
@@ -640,7 +600,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"period_kind": period.kind, "period_kind": period.kind,
"today": today.isoformat(), "today": today.isoformat(),
"codes": codes, "codes": codes,
"names": dict(CHANNEL_NAMES), "names": names,
"kpis": kpis, "kpis": kpis,
"table": table, "table": table,
"month": month, "month": month,
@@ -648,7 +608,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"roas_basis": {c: roas_basis(c) for c in codes}, "roas_basis": {c: roas_basis(c) for c in codes},
"detail_channels": sorted(DETAIL_CHANNELS), "detail_channels": sorted(DETAIL_CHANNELS),
"chart_daily": calc.daily_series(period, codes, cells), "chart_daily": calc.daily_series(period, codes, cells),
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes], "chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
# 업로드로 들어온 칸(표시용) — "날짜|채널" # 업로드로 들어온 칸(표시용) — "날짜|채널"
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items() "upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
if s == "upload" and period.start <= d <= period.end), if s == "upload" and period.start <= d <= period.end),
@@ -659,7 +619,7 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
"formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in "formula_cells": {f"{d.isoformat()}|{c}": f for (d, c), f in
(store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas") (store.ad_formulas(period.start, period.end) if hasattr(store, "ad_formulas")
and not migration_needed else {}).items()}, and not migration_needed else {}).items()},
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS], "upload_channels": [{"code": c, "name": names[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS if c in names],
"migration_needed": migration_needed, "migration_needed": migration_needed,
# 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모 # 날짜 칸 메모(마이그레이션 010) — "날짜|채널" → 메모
"memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in "memo_cells": {f"{d.isoformat()}|{c}": m for (d, c), m in
+11
View File
@@ -156,6 +156,17 @@ class Period:
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간") unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
return prev_start, prev_end, f"{unit} {note}".strip() return prev_start, prev_end, f"{unit} {note}".strip()
def yoy_range(self, today: date) -> tuple[date, date, str]:
"""1년 전 같은 날짜 범위(2026-11-16 매출 KPI 전년 대비). 진행 중인 기간이면 오늘까지만. 2/29 → 2/28."""
def back(d: date) -> date:
try:
return d.replace(year=d.year - 1)
except ValueError:
return d.replace(year=d.year - 1, day=28)
end = today if self.start <= today < self.end else self.end
return back(self.start), back(end), "전년 같은 기간"
def resolve_period( def resolve_period(
kind: str, kind: str,
+35 -13
View File
@@ -12,7 +12,9 @@ from typing import Any
from fastapi import HTTPException, Request from fastapi import HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, RedirectResponse
MODULE_KEY = "performance" from . import variant
MODULE_KEY = "performance" # 한국 실적 — 요청마다는 variant.current().module_key(말레이시아 실적 = malaysia_performance)
MODULE_NAME = "실적" MODULE_NAME = "실적"
CONFIG_HELP = ( CONFIG_HELP = (
@@ -20,10 +22,19 @@ CONFIG_HELP = (
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 " "scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요." "PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
) )
CONFIG_HELP_MY = (
"말레이시아 실적 모듈이 아직 설정되지 않았습니다. "
"app/modules/malaysia_performance/CLAUDE.md 대로 malaysia_performance_db 를 만들고 "
"MALAYSIA_PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
)
def config_help() -> str:
return CONFIG_HELP if variant.current().is_kr else CONFIG_HELP_MY
def get_store(request: Request) -> Any: def get_store(request: Request) -> Any:
return getattr(request.app.state, "performance_store", None) return getattr(request.app.state, variant.current().store_attr, None)
def key_ring(): def key_ring():
@@ -60,8 +71,9 @@ def require_user(request: Request) -> dict[str, Any]:
user = get_current_user_record(request) user = get_current_user_record(request)
if user is None: if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.") raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
if not has_module(user, MODULE_KEY): v = variant.current()
raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.") if not has_module(user, v.module_key):
raise HTTPException(status_code=403, detail=f"{v.module_name} 모듈 권한이 없습니다.")
return user return user
@@ -78,7 +90,7 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
user = require_admin(request) if admin else require_user(request) user = require_admin(request) if admin else require_user(request)
st = get_store(request) st = get_store(request)
if st is None: if st is None:
raise HTTPException(status_code=503, detail=CONFIG_HELP) raise HTTPException(status_code=503, detail=config_help())
return st, user return st, user
@@ -90,8 +102,9 @@ def guard(request: Request, *, admin: bool = False):
user = get_current_user_record(request) user = get_current_user_record(request)
if user is None: if user is None:
return login_redirect(request) return login_redirect(request)
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)): v = variant.current()
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다." if not has_module(user, v.module_key) or (admin and not is_admin(user)):
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{v.module_name} 접근 권한이 없습니다."
return render_template(request, "denied.html", return render_template(request, "denied.html",
{"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403) {"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403)
st = get_store(request) st = get_store(request)
@@ -106,21 +119,30 @@ def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse
return render_template( return render_template(
request, "denied.html", request, "denied.html",
{"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user), {"reason": config_help(), "user": user, "is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active=MODULE_KEY)}, "nav_items": build_erp_nav(user, active=variant.current().module_key)},
status_code=503, status_code=503,
) )
def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]: def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "") -> dict[str, Any]:
from app.main import build_erp_nav # noqa: WPS433 from app.main import build_erp_nav # noqa: WPS433
from app.store import is_admin # noqa: WPS433 from app.store import is_admin # noqa: WPS433
v = variant.current()
if not v.is_kr and page_title:
page_title = f"말레이시아 {page_title}"
subtitle = "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출"
if variant.lang() == "en": # 말레이시아 실적 영문 — 화면 머리 제목(나머지 글자는 performance-en.js)
page_title = {"말레이시아 광고비": "Malaysia Ad Spend", "말레이시아 실적 설정": "Malaysia Sales Settings"}.get(
page_title, "Malaysia Sales")
subtitle = "TikTok · Shopee · Lazada sales"
return { return {
"user": user, "user": user,
"is_admin": is_admin(user), "is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active=MODULE_KEY), "nav_items": build_erp_nav(user, active=v.module_key),
"active_tab": active_tab, "active_tab": active_tab,
"page_title": page_title, "page_title": page_title or v.module_name,
"page_subtitle": "쇼핑몰 통합 매출", "page_subtitle": subtitle,
**variant.template_ctx(),
} }
+23 -7
View File
@@ -145,12 +145,21 @@ def load_hidden(store: Any) -> set[str]:
return set(_shared_setting(store, HIDDEN_SETTING) or ()) return set(_shared_setting(store, HIDDEN_SETTING) or ())
RM_UNIT = "rm" # 말레이시아 실적(2026-11-20) — 금액 = 센 정수, 화면 = RM 소수 2자리(단위 설정 없음)
def load_unit(store: Any) -> str: def load_unit(store: Any) -> str:
from . import variant # noqa: WPS433
if not variant.current().is_kr:
return RM_UNIT
return normalize_unit(_shared_setting(store, UNIT_SETTING)) return normalize_unit(_shared_setting(store, UNIT_SETTING))
def amount_text(value: Any, unit: str = "won") -> str: def amount_text(value: Any, unit: str = "won") -> str:
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림).""" """금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림), RM 은 센 ÷ 100 소수 두 자리."""
if unit == RM_UNIT:
return f"{(Decimal(int(value)) / 100).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
div, places, _ = UNITS[normalize_unit(unit)] div, places, _ = UNITS[normalize_unit(unit)]
if div == 1: if div == 1:
return f"{int(value):,}" return f"{int(value):,}"
@@ -161,7 +170,7 @@ 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], 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: period: Any, q_start: date, q_end: date) -> None:
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS). """매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합. 카페24 = 구글·메타·카톡 플친 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준 일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다. (화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음.""" 광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
@@ -217,11 +226,13 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]: def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고, """쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고,
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출).""" 나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
from . import ad_spend # noqa: WPS433 from . import ad_spend, variant # noqa: WPS433
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)} if variant.current().ad_lines: # 말레이시아 실적 — 쇼핑몰 그룹(합계) 칸 아래에 그 쇼핑몰 광고비
return dict(variant.current().ad_lines)
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)}
for ch, c in ad_spend.ROAS_SALES_CODE.items(): for ch, c in ad_spend.ROAS_SALES_CODE.items():
out[c] = out.get(c, ()) + ((ch, ""),) out[c] = out.get(c, ()) + ((ch, ""),)
return out return out
@@ -261,7 +272,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today) m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today) y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start) # 전년 같은 기간 대비(2026-11-16) — 연 보기는 직전 비교가 이미 전년이라 뺀다
yoy = period.yoy_range(today) if period.kind != "year" else None
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start, *(yoy[:1] if yoy else ()))
q_end = max(period.end, year_period.end) q_end = max(period.end, year_period.end)
gb = groupbuy_code(markets) gb = groupbuy_code(markets)
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다 # 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
@@ -292,6 +306,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True, {"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label}, "delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
] ]
if yoy:
kpis[0].update(yoy_delta=calc.pct_change(cur.net, calc.sum_range(summary, codes, yoy[0], yoy[1]).net), yoy_cmp=yoy[2])
share = calc.by_code(summary, codes, period.start, period.end) share = calc.by_code(summary, codes, period.start, period.end)
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다 # 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
@@ -315,7 +331,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
r["total"] = s["total"] r["total"] = s["total"]
if "cafe24" in codes: if "cafe24" in codes:
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"] r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
_ad_lines(store, table, codes, cells, period, q_start, q_end) _ad_lines(store, table, [*codes, *group_members], cells, period, q_start, q_end)
for r in table: for r in table:
for g, members in group_members.items(): for g, members in group_members.items():
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"]) r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
+5 -4
View File
@@ -80,12 +80,13 @@ class _Parser:
return Decimal(tok) return Decimal(tok)
def parse_amount(raw: object) -> tuple[int | None, str | None]: def parse_amount(raw: object, scale: int = 1) -> tuple[int | None, str | None]:
"""칸 입력 → (원 단위 금액, 계산식). 빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음.""" """칸 입력 → (저장 단위 금액, 계산식). scale=100 = 센(말레이시아 실적 RM 소수 2자리 — 12.5 → 1250).
빈 칸 = (None, None)(지움). 숫자 하나(부호 포함)면 계산식 없음."""
text = str(raw if raw is not None else "").strip() text = str(raw if raw is not None else "").strip()
for a, b in _OPS.items(): for a, b in _OPS.items():
text = text.replace(a, b) text = text.replace(a, b)
text = re.sub(r"[,\s원]", "", text) text = re.sub(r"[,\s원]|RM", "", text, flags=re.IGNORECASE)
if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다 if text.startswith("="): # 엑셀 버릇으로 = 를 붙여도 된다
text = text[1:] text = text[1:]
if text == "": if text == "":
@@ -100,7 +101,7 @@ def parse_amount(raw: object) -> tuple[int | None, str | None]:
raise FormulaError("계산할 수 없는 식입니다.") from None raise FormulaError("계산할 수 없는 식입니다.") from None
if p.peek() is not None: if p.peek() is not None:
raise FormulaError("계산식이 올바르지 않습니다.") raise FormulaError("계산식이 올바르지 않습니다.")
amount = int(value.quantize(Decimal("1"), rounding=ROUND_HALF_UP)) amount = int((value * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
# 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다 # 숫자 하나(앞 부호만 있는 것 포함)는 계산식이 아니다
is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(") is_formula = any(t in "+-*/()" for t in tokens[1:]) or (tokens[0] == "(")
return amount, (text if is_formula else None) return amount, (text if is_formula else None)
+6 -6
View File
@@ -77,8 +77,8 @@ def parse_date(value: Any) -> date | None:
return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
def parse_amount(value: Any) -> int | None: def parse_amount(value: Any, scale: int = 1) -> int | None:
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError.""" """금액 칸 → 저장 단위 정수(원, scale=100 이면 센 — 말레이시아 실적 RM 소수 2자리). 빈 칸이면 None, 숫자가 아니면 ValueError."""
if value is None or isinstance(value, bool): if value is None or isinstance(value, bool):
if value is None: if value is None:
return None return None
@@ -86,7 +86,7 @@ def parse_amount(value: Any) -> int | None:
if isinstance(value, (int, float, Decimal)): if isinstance(value, (int, float, Decimal)):
num = Decimal(str(value)) num = Decimal(str(value))
else: else:
text = re.sub(r"[,\s원₩]", "", str(value)) text = re.sub(r"[,\s원₩]|RM", "", str(value), flags=re.IGNORECASE)
if text == "": if text == "":
return None return None
try: try:
@@ -95,7 +95,7 @@ def parse_amount(value: Any) -> int | None:
raise ValueError from None raise ValueError from None
if not num.is_finite(): if not num.is_finite():
raise ValueError raise ValueError
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP)) return int((num * scale).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]: def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
@@ -111,7 +111,7 @@ def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[st
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date, def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult: extra_names: Mapping[str, Iterable[str]] | None = None, scale: int = 1) -> ParseResult:
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서).""" """첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
if not content: if not content:
raise UploadError("빈 파일입니다.") raise UploadError("빈 파일입니다.")
@@ -160,7 +160,7 @@ def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: d
amounts: dict[int, int] = {} amounts: dict[int, int] = {}
for i, raw in cells.items(): for i, raw in cells.items():
try: try:
amt = parse_amount(raw) amt = parse_amount(raw, scale)
except ValueError: except ValueError:
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).") res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
continue continue
+87 -45
View File
@@ -5,6 +5,7 @@
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일 GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
GET /performance/settings 실적 설정(관리자) GET /performance/settings 실적 설정(관리자)
JSON API — 모듈 권한 JSON API — 모듈 권한
PUT /performance/api/my-col-fold 일자별 표에서 접은 열(보는 사람 본인에게만, 매출 실적·광고비 따로)
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리) POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌 background=true 면 백그라운드로 돌리고 작업 번호를 바로 돌려줌
GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대) GET /performance/api/sync/jobs/{id} 매출 업데이트 진행 상황(쇼핑몰별·전체 진행 막대)
@@ -56,7 +57,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from app.timezone import today_kst from app.timezone import today_kst
from . import calc, common from . import calc, common, variant
from .adapters.registry import all_adapters, get_adapter from .adapters.registry import all_adapters, get_adapter
router = APIRouter(prefix="/performance", tags=["performance"]) router = APIRouter(prefix="/performance", tags=["performance"])
@@ -65,7 +66,7 @@ MAX_EVENT_DAYS = 31
MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기) MAX_CHECK_DAYS = 62 # 쇼핑몰 화면 일별 비교(카페24 일별 매출내역 붙여넣기)
MAX_BACKFILL_DAYS = 366 MAX_BACKFILL_DAYS = 366
MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간) MAX_USER_SYNC_DAYS = 92 # 관리자가 아니어도 가져올 수 있는 기간(이번달·직접선택 짧은 기간)
MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(원) MAX_MANUAL_AMOUNT = 10 ** 12 # 수동 입력 한 칸 상한(저장 단위 — 원, 말레이시아 실적은 센)
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx" MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 " AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
"먼저 적용해야 합니다.") "먼저 적용해야 합니다.")
@@ -95,6 +96,10 @@ def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
def _holidays() -> dict[str, str]: def _holidays() -> dict[str, str]:
if not variant.current().is_kr: # 말레이시아 실적 — 말레이시아 공휴일(라이브 커머스 표 공유, 화면 언어로)
from app.modules.live.holidays import holiday_names # noqa: WPS433
return holiday_names(variant.lang())
try: try:
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용) from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용)
@@ -113,7 +118,7 @@ def _code_or_404(store: Any, code: str):
@router.get("/health") @router.get("/health")
def health(request: Request) -> JSONResponse: def health(request: Request) -> JSONResponse:
st = common.get_store(request) st = common.get_store(request)
return JSONResponse({"ok": st is not None, "module": "performance", return JSONResponse({"ok": st is not None, "module": variant.current().module_key,
"encryption_key": common.key_status()["ok"]}) "encryption_key": common.key_status()["ok"]})
@@ -151,6 +156,7 @@ def dashboard_page(
ctx["update_watch"] = _update_watch("sales", user) ctx["update_watch"] = _update_watch("sales", user)
_unit_ctx(store, ctx) _unit_ctx(store, ctx)
_colw_ctx(request, ctx) _colw_ctx(request, ctx)
ctx["col_fold"] = _load_col_fold(store, user).get("sales", [])
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
@@ -163,7 +169,7 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
from . import auto_sync # noqa: WPS433 from . import auto_sync # noqa: WPS433
if not auto_sync.enabled(): if not auto_sync.enabled() or not variant.current().is_kr: # 말레이시아 실적은 API 수집 없음(수동 입력만)
return None return None
try: try:
sched = auto_sync.load_schedules(store)[0][kind] sched = auto_sync.load_schedules(store)[0][kind]
@@ -177,11 +183,15 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
"label": auto_sync.describe(sched)} "label": auto_sync.describe(sched)}
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]: def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str] | None:
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이 """화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다.""" GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다.
말레이시아 실적은 없음 — 진행 작업(jobs)은 한국 실적 것이라 보면 엉뚱하게 새로 고친다."""
from . import jobs # noqa: WPS433 from . import jobs # noqa: WPS433
if not variant.current().is_kr:
return None
job = jobs.last_finished(kind, exclude_user=user.get("email", "")) job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
return {"kind": kind, "seen": job.id if job else ""} return {"kind": kind, "seen": job.id if job else ""}
@@ -206,7 +216,7 @@ def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
unit = load_unit(store) unit = load_unit(store)
ctx["unit"] = unit ctx["unit"] = unit
ctx["unit_label"] = UNITS[unit][2] ctx["unit_label"] = UNITS[unit][2] if unit in UNITS else "RM"
ctx["amt"] = lambda v: amount_text(v, unit) ctx["amt"] = lambda v: amount_text(v, unit)
@@ -243,12 +253,13 @@ def ads_page(
) )
_ad_update_ctx(store, user, ctx) _ad_update_ctx(store, user, ctx)
_colw_ctx(request, ctx) _colw_ctx(request, ctx)
ctx["col_fold"] = _load_col_fold(store, user).get("ads", [])
return render_template(request, "performance/ads.html", return render_template(request, "performance/ads.html",
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx}) {**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None: def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> None:
"""[광고비 업데이트](2026-10-20, 광고비·틱톡 탭 공통) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로. """[광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.""" 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차."""
from . import jobs # noqa: WPS433 from . import jobs # noqa: WPS433
from .ad_sources.registry import get_source # noqa: WPS433 from .ad_sources.registry import get_source # noqa: WPS433
@@ -266,33 +277,6 @@ def _ad_update_ctx(store: Any, user: dict[str, Any], ctx: dict[str, Any]) -> Non
ctx["update_watch"] = _update_watch("ads", user) ctx["update_watch"] = _update_watch("ads", user)
@router.get("/tiktok", response_class=HTMLResponse)
def tiktok_page(
request: Request,
period: str = "month",
d: str | None = None,
from_: str | None = Query(None, alias="from"),
to: str | None = None,
):
"""틱톡 탭(2026-11-05) — 일자별 ROAS·광고비·매출(광고 API 값, 읽기 전용). 설정 = 실적 설정 → 광고 API 연동."""
from app.main import render_template # noqa: WPS433
g = common.guard(request)
if not isinstance(g, tuple):
return g
store, user = g
from .ad_spend import build_tiktok_dashboard # noqa: WPS433
today = today_kst()
ctx = build_tiktok_dashboard(store, kind=period, anchor=_parse_date(d) or today, today=today,
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays())
_ad_update_ctx(store, user, ctx)
ctx["tiktok_configured"] = any(s["code"] == "tiktok" for s in ctx["ad_sync_sources"])
_colw_ctx(request, ctx)
return render_template(request, "performance/tiktok.html",
{**common.base_ctx(user, active_tab="tiktok", page_title="틱톡"), **ctx})
@router.get("/settings", response_class=HTMLResponse) @router.get("/settings", response_class=HTMLResponse)
def settings_page(request: Request): def settings_page(request: Request):
from app.main import render_template # noqa: WPS433 from app.main import render_template # noqa: WPS433
@@ -304,6 +288,12 @@ def settings_page(request: Request):
store, user = g store, user = g
from .dashboard import build_settings # noqa: WPS433 from .dashboard import build_settings # noqa: WPS433
if not variant.current().is_kr: # 말레이시아 실적 — 쇼핑몰(수동 입력)·보기 설정만(API 인증·광고 API·자동 업데이트 카드 없음)
ctx = build_settings(store, configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
_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})
creds, _ = common.services(request, store) creds, _ = common.services(request, store)
ad_creds, ad_sync = _ad_services(store) ad_creds, ad_sync = _ad_services(store)
versions = creds.key_versions_in_use() versions = creds.key_versions_in_use()
@@ -533,7 +523,7 @@ def _cell_amount(raw: Any) -> tuple[int | None, str | None]:
from .formula import FormulaError, parse_amount # noqa: WPS433 from .formula import FormulaError, parse_amount # noqa: WPS433
try: try:
amount, formula = parse_amount(raw) amount, formula = parse_amount(raw, variant.current().scale)
except FormulaError as exc: except FormulaError as exc:
raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None raise HTTPException(status_code=400, detail=f"{exc} (숫자 또는 1000+2000 같은 계산식)") from None
if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT: if amount is not None and abs(amount) > MAX_MANUAL_AMOUNT:
@@ -570,13 +560,31 @@ def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, An
@router.get("/api/manual-sales/sample.xlsx") @router.get("/api/manual-sales/sample.xlsx")
def api_manual_sample(request: Request) -> Any: def api_manual_sample(request: Request) -> Any:
common.require_store(request) store, _ = common.require_store(request)
if not variant.current().is_kr: # 말레이시아 실적 — 지금 수동 입력 쇼핑몰 이름으로 만든다(한국 샘플은 한국 쇼핑몰)
return _manual_sample_from(store)
if not MANUAL_SAMPLE_PATH.is_file(): if not MANUAL_SAMPLE_PATH.is_file():
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.") raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx", return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
def _manual_sample_from(store: Any) -> Any:
import io # noqa: WPS433
import openpyxl # noqa: WPS433
from fastapi.responses import Response # noqa: WPS433
wb = openpyxl.Workbook()
ws = wb.active
ws.append(["날짜", *[m["name"] for m in store.list_marketplaces() if m.get("manual_input") and not m.get("is_group")]])
ws.append([today_kst().isoformat()])
buf = io.BytesIO()
wb.save(buf)
return Response(buf.getvalue(), headers={"Content-Disposition": 'attachment; filename="upload_sample.xlsx"'},
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@router.post("/api/manual-sales/upload") @router.post("/api/manual-sales/upload")
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse: def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다.""" """수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
@@ -590,7 +598,8 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
markets = [m for m in store.list_marketplaces() if get_adapter(m["code"]) is not None and m["enabled"]] 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} extra = {m["code"]: tuple(n for n in (get_adapter(m["code"]).name, _short_name(m["name"])) if n) for m in markets}
try: try:
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra) res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra,
scale=variant.current().scale)
except manual_upload.UploadError as exc: except manual_upload.UploadError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None raise HTTPException(status_code=400, detail=str(exc)) from None
names = {m["code"]: m["name"] for m in markets} names = {m["code"]: m["name"] for m in markets}
@@ -619,9 +628,9 @@ def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONRes
# JSON API — 광고비(모듈 권한자 누구나) # JSON API — 광고비(모듈 권한자 누구나)
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
def _ad_channel(channel: str) -> str: def _ad_channel(channel: str) -> str:
from .ad_spend import CHANNEL_NAMES # noqa: WPS433 from .ad_spend import channel_names # noqa: WPS433
if channel not in CHANNEL_NAMES: if channel not in channel_names():
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.") raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
return channel return channel
@@ -633,14 +642,14 @@ MEMO_MAX = 1000
def api_cell_memo(request: Request, kind: str, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse: 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(광고비, 광고 채널). """날짜 칸 메모(2026-10-22, 마이그레이션 010) — kind = sales(매출 실적, 쇼핑몰) / ad(광고비, 광고 채널).
memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다.""" memo 가 비면 지움. 칸에 금액을 넣을 수 있는 사람(모듈 권한자 누구나)이 쓴다."""
from .ad_spend import CHANNEL_NAMES # noqa: WPS433 from .ad_spend import channel_names # noqa: WPS433
from .db import MemoMigrationNeeded # noqa: WPS433 from .db import MemoMigrationNeeded # noqa: WPS433
store, user = common.require_store(request) store, user = common.require_store(request)
if kind == "sales": if kind == "sales":
_code_or_404(store, code) _code_or_404(store, code)
elif kind == "ad": elif kind == "ad":
if code not in CHANNEL_NAMES: if code not in channel_names():
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.") raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
else: else:
raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.") raise HTTPException(status_code=404, detail="알 수 없는 메모 종류입니다.")
@@ -692,7 +701,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
rows = store.ad_details(channel, start, end) rows = store.ad_details(channel, start, end)
except ad_spend.AdMigrationNeeded as exc: except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(), return JSONResponse({"channel": channel, "name": ad_spend.channel_names()[channel], "from": start.isoformat(),
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)}) "to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
@@ -713,7 +722,7 @@ def api_ad_spend_upload(
_ad_channel(channel) _ad_channel(channel)
parser = ad_spend.PARSERS.get(channel) parser = ad_spend.PARSERS.get(channel)
if parser is None: if parser is None:
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.") raise HTTPException(status_code=400, detail=f"{ad_spend.channel_names()[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
uploads = list(files or []) + ([file] if file is not None else []) uploads = list(files or []) + ([file] if file is not None else [])
if not uploads: if not uploads:
raise HTTPException(status_code=400, detail="파일을 고르세요.") raise HTTPException(status_code=400, detail="파일을 고르세요.")
@@ -741,7 +750,7 @@ def api_ad_spend_upload(
except ad_spend.AdMigrationNeeded as exc: except ad_spend.AdMigrationNeeded as exc:
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
days = sorted(d for d, _ in res.entries) days = sorted(d for d, _ in res.entries)
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.channel_names()[channel],
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads), "total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]], "overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None}) "from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
@@ -1015,6 +1024,39 @@ def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> J
return JSONResponse({"ok": True, "unit": unit}) return JSONResponse({"ok": True, "unit": unit})
COL_FOLD_KINDS = ("sales", "ads")
def _col_fold_key(user: dict[str, Any]) -> str:
"""접은 열(2026-11-06) — 사람마다 perf_settings 한 줄. key 는 64자 제한이라 이메일을 해시로(updated_by 에 이메일)."""
import hashlib # noqa: WPS433
return "col_fold:" + hashlib.sha1(str(user.get("email", "")).lower().encode()).hexdigest()
def _load_col_fold(store: Any, user: dict[str, Any]) -> dict[str, list[str]]:
"""{sales: [열 코드], ads: [...]} — 저장 없음·011 미적용·DB 오류면 빈 값(전부 펼침)."""
try:
value = store.get_setting(_col_fold_key(user))
except Exception: # noqa: BLE001 — 접기만 못 함
return {}
return value if isinstance(value, dict) else {}
@router.put("/api/my-col-fold")
def api_my_col_fold(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""일자별 표에서 접은 열(2026-11-06, 모듈 권한자 누구나) — 로그인한 사람 본인 화면에만 적용, 매출 실적·광고비 따로."""
store, user = common.require_store(request)
kind, cols = payload.get("kind"), payload.get("cols")
if kind not in COL_FOLD_KINDS or not isinstance(cols, list) or len(cols) > 200:
raise HTTPException(status_code=400, detail="접은 열 목록이 올바르지 않습니다.")
cols = sorted({c for c in cols if isinstance(c, str) and 0 < len(c) <= 64 and c != "label"})
value = _load_col_fold(store, user)
value[kind] = cols
_save_shared_setting(store, _col_fold_key(user), value, user)
return JSONResponse({"ok": True, "cols": cols})
def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None: def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None:
from .db import SettingsMigrationNeeded # noqa: WPS433 from .db import SettingsMigrationNeeded # noqa: WPS433
@@ -1,4 +1,4 @@
{# 광고비 업데이트(2026-10-20, 광고비·틱톡 탭 공통) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정) {# 광고비 업데이트(2026-10-20) — 매출 탭과 같은 모양: 마지막 업데이트(광고 API 마지막 성공) · 다음 자동 업데이트(실적 설정의 광고비 일정)
· [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #} · [광고비 업데이트](설정된 광고 API 전부, 진행 창). 업데이트 중에도 누르면 진행 창을 다시 연다. #}
{% if ad_sync_sources %} {% if ad_sync_sources %}
<div class="perf-update"> <div class="perf-update">
@@ -1,19 +1,23 @@
{# 실적 모듈 탭 — [매출 실적] [광고비] [틱톡] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘). {# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #} 설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<nav class="perf-tabs" aria-label="실적 메뉴"> <nav class="perf-tabs" aria-label="{{ pv.module_name }} 메뉴">
<div class="perf-tabs-main" role="tablist"> <div class="perf-tabs-main" role="tablist">
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/" <a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="{{ pv.base }}/"
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}"> role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a> <span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads" <a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="{{ pv.base }}/ads"
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}"> role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a> <span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
<a class="perf-tab perf-tab-tiktok{% if active_tab == 'tiktok' %} is-active{% endif %}" href="/performance/tiktok"
role="tab" aria-selected="{{ 'true' if active_tab == 'tiktok' else 'false' }}">
<span class="material-symbols-outlined" aria-hidden="true">music_note</span>틱톡</a>
</div> </div>
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings" {% if not pv.is_kr %}
{#- 한글·영문 전환(2026-11-20, 말레이시아 실적만) — 누르면 쿠키(mperf_lang)에 저장하고 다시 그린다(performance.js). 고른 적 없으면 브라우저·OS 언어 -#}
<div class="perf-lang" role="group" aria-label="Language" translate="no">
<button type="button" data-perf-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
<button type="button" data-perf-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
</div>
{% endif %}
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="{{ pv.base }}/settings"
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}"> title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a> <span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
</nav> </nav>
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%} {%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
@@ -8,12 +8,12 @@
{%- macro won(v) -%} {%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span> {%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span> {%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%} {%- else -%}{{ num(v) }}{%- endif -%}
{%- endmacro -%} {%- endmacro -%}
{% block content %} {% block content %}
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#} {#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross"> <section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
{% include "performance/_tabs.html" %} {% include "performance/_tabs.html" %}
<div class="perf-toolbar"> <div class="perf-toolbar">
@@ -26,7 +26,7 @@
{% include "performance/_period_nav.html" %} {% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}> <form class="perf-custom" id="perf-custom" method="get" action="{{ pv.base }}/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" /> <input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required /> <input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span> <span class="perf-muted">~</span>
@@ -52,7 +52,7 @@
<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> <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> <span class="perf-muted">{{ k.note }}</span>
{% else %} {% else %}
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b> <b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">{{ money_t(k.value) }}</b>
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span> {% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
{% else %} {% else %}
{% set up = k.delta > 0 %} {% set up = k.delta > 0 %}
@@ -80,7 +80,7 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#} {#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#} {#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#} {#- 열 너비(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"> <table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads" data-cfold-kind="ads" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
<thead> <thead>
<tr> <tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th> <th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
@@ -103,7 +103,7 @@
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) if not up and not ap else none %} {% 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) -#} {% 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 %}" <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> data-manual-code="{{ c }}" data-date="{{ r.date }}" data-memo-code="{{ c }}" data-manual-value="{{ inval(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 %} {% else %}
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td> <td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
{% endif %} {% endif %}
@@ -114,11 +114,21 @@
</table> </table>
</div> </div>
{% if period_kind != 'year' %} {% if period_kind != 'year' %}
{% if pv.is_kr %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움. <p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액), 칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목. 네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다. 파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p> 구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
{% elif lang == 'en' %}
<p class="perf-muted perf-manual-help">Click a date cell to enter that day's <b>ad spend</b> (RM, 2 decimals) — Enter saves and moves down, Esc cancels, saving an empty cell clears it.
Cells show <b>ad spend (ROAS%)</b> — ROAS = that marketplace's (shop + live commerce) gross sales ÷ ad spend (total column = all sales).
Blue = entered value, bold blue = formula (type 10.5+20 without = and it is calculated).</p>
{% else %}
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>(RM, 소수 2자리)를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출).
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(10.5+20 처럼 = 없이 입력하면 바로 계산).</p>
{% endif %}
{% endif %} {% endif %}
</div> </div>
@@ -169,7 +179,7 @@
<div class="erp-card perf-card"> <div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div> <div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
<div class="perf-year-sum"> <div class="perf-year-sum">
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div> <div><span>광고비</span><b>{{ money_t(year.total.gross) }}</b></div>
</div> </div>
<div class="erp-table-wrap"> <div class="erp-table-wrap">
<table class="perf-table perf-year"> <table class="perf-table perf-year">
@@ -195,12 +205,22 @@
</div> </div>
</div> </div>
{% if pv.is_kr %}
<p class="perf-foot perf-muted"> <p class="perf-foot perf-muted">
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함). 광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값). ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다. 구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
</p> </p>
{% elif lang == 'en' %}
<p class="perf-foot perf-muted">
Amounts in RM. ROAS = that marketplace's (shop + live commerce) sales ÷ ad spend × 100. Ad spend to sales = ad spend ÷ gross sales of the same period.
</p>
{% else %}
<p class="perf-foot perf-muted">
금액 단위 RM. ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 ÷ 광고비 × 100. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
</p>
{% endif %}
</section> </section>
<script type="application/json" id="perf-data">{{ { <script type="application/json" id="perf-data">{{ {
@@ -211,7 +231,7 @@
"period_kind": period_kind, "period_kind": period_kind,
"memo_kind": "ad", "memo_kind": "ad",
"today": today, "today": today,
"manual_api": "/performance/api/ad-spend/", "manual_api": pv.base ~ "/api/ad-spend/",
"manual_word": "광고비", "manual_word": "광고비",
"period_start": period.start.isoformat(), "period_start": period.start.isoformat(),
"period_end": period.end.isoformat(), "period_end": period.end.isoformat(),
@@ -223,4 +243,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %} {% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
{%- macro won(v) -%} {%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span> {%- if v is none -%}<span class="perf-na"></span>
@@ -9,7 +9,7 @@
{%- endmacro -%} {%- endmacro -%}
{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#} {#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#}
{%- macro money(v) -%} {%- macro money(v) -%}
{%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%} {%- if unit == 'won' -%}₩{{ amt(v) }}{%- elif unit == 'rm' -%}RM {{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
{%- endmacro -%} {%- endmacro -%}
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#} {#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
{%- macro adl(lines) -%} {%- macro adl(lines) -%}
@@ -30,7 +30,7 @@
{%- endmacro -%} {%- endmacro -%}
{% block content %} {% block content %}
<section class="perf" id="perf-dash" data-metric="{{ metric }}"> <section class="perf" id="perf-dash" data-metric="{{ metric }}" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
{% include "performance/_tabs.html" %} {% include "performance/_tabs.html" %}
<!-- ── 기간 · 필터 · 업데이트 ── --> <!-- ── 기간 · 필터 · 업데이트 ── -->
@@ -44,7 +44,7 @@
{% include "performance/_period_nav.html" %} {% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}> <form class="perf-custom" id="perf-custom" method="get" action="{{ pv.base }}/"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" /> <input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required /> <input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span> <span class="perf-muted">~</span>
@@ -55,7 +55,7 @@
<details class="perf-filter" id="perf-filter"> <details class="perf-filter" id="perf-filter">
<summary class="erp-btn erp-btn-outline">쇼핑몰: {% if selected_all %}전체{% else %}{{ codes | length }}곳{% endif %}</summary> <summary class="erp-btn erp-btn-outline">쇼핑몰: {% if selected_all %}전체{% else %}{{ codes | length }}곳{% endif %}</summary>
<form class="perf-filter-pop" method="get" action="/performance/"> <form class="perf-filter-pop" method="get" action="{{ pv.base }}/">
<input type="hidden" name="period" value="{{ period_kind }}" /> <input type="hidden" name="period" value="{{ period_kind }}" />
{% if period_kind == 'custom' %} {% if period_kind == 'custom' %}
<input type="hidden" name="from" value="{{ period.start.isoformat() }}" /> <input type="hidden" name="from" value="{{ period.start.isoformat() }}" />
@@ -73,6 +73,7 @@
</form> </form>
</details> </details>
{% if pv.is_kr %}{#- 말레이시아 실적은 API 수집 없음(수동 입력만) — 업데이트 줄 없음 -#}
<div class="perf-update"> <div class="perf-update">
<span class="perf-muted" id="perf-last-update">마지막 업데이트 <span class="perf-muted" id="perf-last-update">마지막 업데이트
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span> <b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
@@ -86,10 +87,11 @@
{% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %} {% if running %}업데이트 중 · 진행 보기{% else %}매출 업데이트{% endif %}
</button> </button>
</div> </div>
{% endif %}
</div> </div>
{% if no_marketplaces %} {% if no_marketplaces %}
<div class="perf-notice">매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}<a href="/performance/settings">실적 설정</a>에서 쇼핑몰 사용을 켜세요.{% endif %}</div> <div class="perf-notice">매출에 포함된 쇼핑몰이 없습니다. {% if is_admin %}<a href="{{ pv.base }}/settings">{{ pv.module_name }} 설정</a>에서 쇼핑몰 사용을 켜세요.{% endif %}</div>
{% endif %} {% endif %}
{% if problems %} {% if problems %}
@@ -111,6 +113,14 @@
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span> {% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span> <span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %} {% endif %}
{% if k.yoy_cmp %}
{% if k.yoy_delta is none %}<span class="perf-muted">{{ k.yoy_cmp }} 비교 없음</span>
{% else %}
<span class="perf-delta {% if k.yoy_delta == 0 %}is-flat{% elif k.yoy_delta > 0 %}is-up{% else %}is-down{% endif %}">
{% if k.yoy_delta > 0 %}▲{% elif k.yoy_delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.yoy_delta | abs) }}%</span>
<span class="perf-muted">{{ k.yoy_cmp }} 대비</span>
{% endif %}
{% endif %}
</div> </div>
{% endfor %} {% endfor %}
@@ -119,7 +129,7 @@
<div class="perf-card-head"> <div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2> <h2 class="perf-h">{% if period_kind == 'year' %}월별 × 쇼핑몰{% else %}일자별 × 쇼핑몰{% endif %}</h2>
<span class="perf-head-notes">{% if unit != 'won' %}<span class="perf-muted">단위: {{ unit_label }}</span>{% endif %} <span class="perf-head-notes">{% if unit != 'won' %}<span class="perf-muted">단위: {{ unit_label }}</span>{% endif %}
<span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 카페24 는 구글·메타"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span> <span class="perf-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값.{% if pv.is_kr %} 카페24 는 구글·메타{% else %} 쇼핑몰 그룹(합계) 칸 아래, ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비{% endif %}"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
{% if manual_upload_names %} {% if manual_upload_names %}
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload" <button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button> title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
@@ -134,7 +144,7 @@
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#} {#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#} {#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#} {#- 열 너비(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"> <table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales" data-cfold-kind="sales" data-col-fold="{{ (col_fold or []) | tojson | forceescape }}">
<thead> <thead>
<tr> <tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th> <th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
@@ -162,7 +172,7 @@
{% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %} {% 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 %} {% set gc0 %}{% if sub %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if sub %}</div>{% endif %}{% endset %}
{% if col.kind == 'group' %} {% if col.kind == 'group' %}
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td> <td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
{% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#} {% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#}
{%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페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> <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>
@@ -171,7 +181,7 @@
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %} {% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) %}{#- 메모(010) — 우클릭 메모 삽입·수정·삭제, 있으면 칸 오른쪽 위 빨간 삼각형 -#} {% 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 }}" <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> data-manual-value="{{ inval(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 %} {% else %}
{#- 메모(2026-10-22) — API 쇼핑몰 날짜 칸도 우클릭 메모(data-memo-code). 왼쪽 클릭은 그대로 주문 내역 -#} {#- 메모(2026-10-22) — API 쇼핑몰 날짜 칸도 우클릭 메모(data-memo-code). 왼쪽 클릭은 그대로 주문 내역 -#}
{% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) if r.kind == 'day' else none %} {% set memo = (memo_cells or {}).get(r.date ~ '|' ~ c) if r.kind == 'day' else none %}
@@ -184,9 +194,13 @@
</tbody> </tbody>
</table> </table>
</div> </div>
{% if manual_codes and period_kind != 'year' %} {% if manual_codes and period_kind != 'year' and lang == 'en' %}
<p class="perf-muted perf-manual-help">Click a date cell of a ✎ column to enter its <b>gross sales</b> (RM) — Enter saves and moves down, Esc cancels,
saving an empty cell clears it. Type a formula without = such as <b>10.5+20</b> and it is calculated. Blue = entered value, bold blue = formula.
Commission uses the rate of that day; totals and charts are recalculated when you finish entering.</p>
{% elif manual_codes and period_kind != 'year' %}
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, <p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
비우고 저장하면 다시 API 수집값. <b>1000+2000</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p> 비우고 저장하면 {% if pv.is_kr %}다시 API 수집값{% else %}지움{% endif %}. <b>{{ '1000+2000' if pv.is_kr else '10.5+20' }}</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
{% endif %} {% endif %}
</div> </div>
@@ -270,11 +284,23 @@
</div> </div>
</div> </div>
{% if pv.is_kr %}
<p class="perf-foot perf-muted"> <p class="perf-foot perf-muted">
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며 매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다. 일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음). 일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
</p> </p>
{% elif lang == 'en' %}
<p class="perf-foot perf-muted">
Amounts in RM (2 decimals). For each marketplace, enter shop sales and live commerce sales separately; the marketplace group column is their sum.
Commission uses the rate in effect that day, rounded to the sen. Daily total, headline amount, charts and cumulative = all shops and live commerce.
</p>
{% else %}
<p class="perf-foot perf-muted">
금액 단위 RM(소수 2자리). 쇼핑몰마다 쇼핑몰 매출과 라이브커머스 매출을 따로 입력하고, 쇼핑몰 그룹 열 = 두 매출 합계입니다.
수수료는 그날 적용되는 수수료율로 계산하며 센(0.01 RM) 미만 반올림합니다. 일 합계·상단 금액·그래프·누적 = 모든 쇼핑몰·라이브커머스 합계.
</p>
{% endif %}
</section> </section>
<script type="application/json" id="perf-data">{{ { <script type="application/json" id="perf-data">{{ {
@@ -294,4 +320,4 @@
} | tojson }}</script> } | tojson }}</script>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %} {% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
@@ -1,15 +1,16 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %} {% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%} {%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
{% block content %} {% block content %}
<section class="perf perf-settings" id="perf-settings"> <section class="perf perf-settings" id="perf-settings" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
{% include "performance/_tabs.html" %} {% include "performance/_tabs.html" %}
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #} {# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
{% if is_admin and not key_info.ok %} {% set api_cols = pv.is_kr %}{#- 말레이시아 실적 = 수동 입력만(API 연동·연결 상태·동기화 칸 없음) -#}
{% if is_admin and pv.is_kr and not key_info.ok %}
<div class="perf-notice is-warn"> <div class="perf-notice is-warn">
<b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }} <b>암호화 마스터 키가 없습니다.</b> {{ key_info.message }}
— 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능). — 키가 없으면 API 인증정보를 저장할 수 없습니다(수수료 설정·대시보드는 사용 가능).
@@ -20,8 +21,10 @@
<div class="perf-card-head"> <div class="perf-card-head">
<h2 class="perf-h">쇼핑몰 설정</h2> <h2 class="perf-h">쇼핑몰 설정</h2>
{% if is_admin %} {% if is_admin %}
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다. {% if api_cols %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span> 수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span>
{% elif lang == 'en' %}<span class="perf-muted">Active · Include in sales · Manual entry · Commission rate are saved immediately. Sales are entered in the date cells of the daily sales table (RM, 2 decimals).</span>
{% else %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. 매출은 매출 실적 일자별 표의 날짜 칸에 직접 입력합니다(RM, 소수 2자리).</span>{% endif %}
{% else %} {% else %}
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span> <span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
{% endif %} {% endif %}
@@ -35,9 +38,9 @@
<th>매출 집계</th> <th>매출 집계</th>
<th>수동 입력</th>{% endif %} <th>수동 입력</th>{% endif %}
<th>수수료율</th> <th>수수료율</th>
{% if is_admin %}<th>API 설정</th> {% if is_admin and api_cols %}<th>API 설정</th>
<th>연결 상태</th>{% endif %} <th>연결 상태</th>{% endif %}
<th>마지막 동기화</th> {% if api_cols %}<th>마지막 동기화</th>{% endif %}
{% if is_admin %}<th></th>{% endif %} {% if is_admin %}<th></th>{% endif %}
</tr> </tr>
</thead> </thead>
@@ -51,7 +54,7 @@
{% if is_admin %}<span class="perf-drag" title="끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)" aria-hidden="true">⠿</span>{% endif %} {% 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> <span class="perf-group-name">{{ r.name }}</span> <span class="perf-pill">그룹</span>
</th> </th>
<td colspan="{{ 7 if is_admin else 2 }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td> <td colspan="{{ (7 if is_admin else 2) - (0 if api_cols else (3 if is_admin else 1)) }}" class="perf-muted">하위 쇼핑몰 {{ r.children }}곳 — 매출 실적에서 그룹 열 = 하위 쇼핑몰 매출 합계(수수료도 쇼핑몰별 요율로 계산해 합침)</td>
{% if is_admin %} {% if is_admin %}
<td class="perf-nowrap"> <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" data-act="rename">이름 변경</button>
@@ -87,7 +90,7 @@
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate" <button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-act="rate"
data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button> data-has-history="{{ 1 if r.rate_history else 0 }}">변경{% if r.rate_history > 1 %} · 이력 {{ r.rate_history }}{% endif %}</button>
</td> </td>
{% if is_admin %} {% if is_admin and api_cols %}
<td> <td>
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span> {% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
{% elif r.shared %}<span class="perf-pill">공통 연동</span> {% elif r.shared %}<span class="perf-pill">공통 연동</span>
@@ -102,7 +105,7 @@
{% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %} {% if r.last_error and r.status not in ('ok', 'disabled') %}<div class="perf-err">{{ r.last_error }}</div>{% endif %}
</td> </td>
{% endif %} {% endif %}
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td> {% if api_cols %}<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>{% endif %}
{% if is_admin %} {% if is_admin %}
<td class="perf-nowrap"> <td class="perf-nowrap">
{% if r.is_custom %} {% if r.is_custom %}
@@ -138,7 +141,7 @@
{% endif %} {% endif %}
<p class="perf-foot perf-muted"> <p class="perf-foot perf-muted">
수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음). 수수료율은 <b>적용 시작일</b>부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).
{% if is_admin %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %} {% if is_admin and api_cols %}상태에 마우스를 올리면 마지막 연결 테스트 시각과 최근 오류를 볼 수 있습니다.{% endif %}
</p> </p>
</div> </div>
@@ -169,6 +172,7 @@
<h2 class="perf-h">공통 보기 설정</h2> <h2 class="perf-h">공통 보기 설정</h2>
<span class="perf-muted">모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.</span> <span class="perf-muted">모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.</span>
</div> </div>
{% if pv.is_kr %}{#- 말레이시아 실적은 RM 고정 -#}
<div class="perf-opt-row"> <div class="perf-opt-row">
<span class="perf-opt-label">매출 단위</span> <span class="perf-opt-label">매출 단위</span>
<div class="perf-quick" role="radiogroup" aria-label="매출 단위"> <div class="perf-quick" role="radiogroup" aria-label="매출 단위">
@@ -180,6 +184,7 @@
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 → <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> {% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
</div> </div>
{% endif %}
<div class="perf-opt-row"> <div class="perf-opt-row">
<span class="perf-opt-label">숨길 쇼핑몰</span> <span class="perf-opt-label">숨길 쇼핑몰</span>
<div class="perf-hide-list"> <div class="perf-hide-list">
@@ -192,7 +197,7 @@
</div> </div>
{% endif %} {% endif %}
{% if is_admin and auto_sync_settings %} {% if is_admin and pv.is_kr and auto_sync_settings %}
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위, {# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #} 기본 30분). [저장] = PUT /api/auto-sync-schedule, 스레드(auto_sync.py)가 1분 안에 반영. #}
{% set au = auto_sync_settings %} {% set au = auto_sync_settings %}
@@ -249,13 +254,13 @@
</div> </div>
{% endif %} {% endif %}
{% if is_admin %} {% if is_admin and pv.is_kr %}
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장. {# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #} 가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
<div class="erp-card perf-card" id="perf-ad-sources"> <div class="erp-card perf-card" id="perf-ad-sources">
<div class="perf-card-head"> <div class="perf-card-head">
<h2 class="perf-h">광고 API 연동</h2> <h2 class="perf-h">광고 API 연동</h2>
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 틱톡은 틱톡 탭에서만 보입니다(매출 실적·광고비 탭 합계 제외). 인증정보는 [설정]에서 입력하면 암호화해 저장합니다. <span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span> 설정이 끝나면 광고비 탭 [광고비 업데이트]와 광고비 자동 업데이트(위 "자동 업데이트" 일정) 때 가져옵니다.</span>
</div> </div>
{% if not ad_api_ready %} {% if not ad_api_ready %}
@@ -347,4 +352,4 @@
</section> </section>
{% endblock %} {% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %} {% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
@@ -1,155 +0,0 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261105a" />{% endblock %}
{%- macro won(v) -%}
{%- if v is none -%}<span class="perf-na"></span>
{%- elif v == 0 -%}<span class="perf-zero">–</span>
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
{%- endmacro -%}
{%- macro pct(p) -%}{%- if p is none -%}<span class="perf-zero">–</span>{%- else -%}{{ "{:,}".format(p) }}%{%- endif -%}{%- endmacro -%}
{% block content %}
{#- 틱톡(2026-11-05) — 광고비 탭과 같은 기간 이동·표·그래프. 값은 광고 API 만(읽기 전용, 직접 입력 없음). 매출 실적·광고비 탭 합계에는 안 들어간다. -#}
<section class="perf perf-ads perf-tiktok" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
{% include "performance/_tabs.html" %}
<div class="perf-toolbar">
<div class="perf-quick" role="group" aria-label="기간 선택">
{% for q in nav.quick %}
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
{% endfor %}
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
</div>
{% include "performance/_period_nav.html" %}
<form class="perf-custom" id="perf-custom" method="get" action="/performance/tiktok"{% if period_kind != 'custom' %} hidden{% endif %}>
<input type="hidden" name="period" value="custom" />
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
</form>
{% include "performance/_ad_update.html" %}
</div>
<div class="perf-notice" id="perf-sync-result" hidden></div>
{% if migration_needed %}
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005·006 을 적용해야 합니다.</div>
{% endif %}
{% if not tiktok_configured %}
<div class="perf-notice is-warn">틱톡 API 가 아직 설정되지 않았습니다. {% if is_admin %}<a href="/performance/settings#perf-ad-sources">실적 설정 → 광고 API 연동</a>에서{% else %}관리자가 실적 설정 → 광고 API 연동에서{% endif %} 틱톡 [설정]을 입력하면 데이터가 들어옵니다.</div>
{% endif %}
<div class="perf-kpi-line">
{% for k in kpis %}
<span class="perf-kpi-item">
<span class="perf-muted">{{ k.label }}</span>
{% if k.key == 'roas' %}
<b class="perf-kpi-line-value is-sub">{{ pct(k.pct) }}</b>
{% else %}
<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 %}
{% endif %}
</span>
{% endfor %}
</div>
<div class="erp-card perf-card">
<div class="perf-card-head">
<h2 class="perf-h">{% if period_kind == 'year' %}월별 틱톡 실적{% else %}일자별 틱톡 실적{% endif %}</h2>
</div>
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="tiktok">
<thead>
<tr>
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
<th data-col="roas">ROAS</th>
<th data-col="spend">광고비</th>
<th data-col="sales">매출</th>
</tr>
</thead>
<tbody>
{% for r in table %}
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
<th class="perf-td-label" scope="row">
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
</th>
<td class="perf-num">{{ pct(r.roas) }}</td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.spend.gross) }}</span></td>
<td class="perf-num"><span class="v v-gross">{{ won(r.cells.sales.gross) }}</span></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="perf-grid2">
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 매출 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily"></div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
<div class="perf-chart" id="perf-chart-daily2"></div>
</div>
</div>
<div class="erp-card perf-card">
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적</h2></div>
<div class="erp-table-wrap">
<table class="perf-table perf-year">
<thead><tr><th class="perf-th-label">월</th><th>ROAS</th><th>광고비</th><th>매출</th></tr></thead>
<tbody>
{% for r in year.rows %}
<tr class="{% if r.future %}is-future{% endif %}">
<th class="perf-td-label" scope="row">{{ r.label }}</th>
<td class="perf-num">{% if not r.future %}{{ pct(r.roas) }}{% endif %}</td>
<td class="perf-num">{{ won(r.spend) }}</td>
<td class="perf-num">{{ won(r.sales) }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr class="perf-row-total">
<th class="perf-td-label" scope="row">합계</th>
<td class="perf-num">{{ pct(year.roas) }}</td>
<td class="perf-num">{{ won(year.spend) }}</td>
<td class="perf-num">{{ won(year.sales) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
<p class="perf-foot perf-muted">
틱톡 광고 API 값입니다. 매출 = 광고에 귀속된 구매금액(웹 구매 + 틱톡샵, 틱톡샵 ID 를 넣으면 GMV Max 포함)이며 틱톡샵 전체 판매액과는 다를 수 있습니다.
ROAS = 매출 ÷ 광고비 × 100, 외화 계정은 그날 환율로 원화로 바꿉니다. 이 값은 매출 실적·광고비 탭 합계에 들어가지 않습니다.
[광고비 업데이트]는 설정된 광고 API 전부를 함께 가져옵니다.
</p>
</section>
<script type="application/json" id="perf-data">{{ {
"period_kind": period_kind,
"today": today,
"period_start": period.start.isoformat(),
"period_end": period.end.isoformat(),
"period_label": period.label,
"daily": chart_sales,
"daily2": chart_spend,
"empty_text": "기간 내 틱톡 데이터가 없습니다.",
"auto_sync": auto_sync,
"update_watch": update_watch
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20261105a" defer></script>{% endblock %}
@@ -120,7 +120,7 @@ class _Store:
def test_ad_dashboard_month(): def test_ad_dashboard_month():
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24"]) sales_codes=["cafe24"])
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao", assert ctx["codes"] == ["google", "meta", "kakao_pf", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽 "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 없음 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"]} k = {x["key"]: x for x in ctx["kpis"]}
@@ -380,3 +380,30 @@ def test_cafe24_real_shows_same_ad_lines(client):
row = next(tr for tr in body.split("<tr ") if 'data-date="2026-10-05"' in tr) 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.count("<i>구글</i>11,000") == 2 and row.count("<i>메타</i>22,000") == 2
assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"") assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"")
def test_api_my_col_fold_per_user(client, monkeypatch):
"""열 접기(2026-11-06) — 로그인한 사람마다 따로 저장, 매출 실적·광고비 따로, 화면은 그 사람 값만 그린다."""
perf_router = importlib.import_module("app.modules.performance.router")
r = client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["naver", "label", "naver", 3, "total"]})
assert r.status_code == 200 and r.json()["cols"] == ["naver", "total"]
assert client.put("/performance/api/my-col-fold", json={"kind": "ads", "cols": ["google"]}).status_code == 200
mine = perf_router._col_fold_key({"email": "king@x"})
assert len(mine) <= 64 and client.store.settings[mine] == {"sales": ["naver", "total"], "ads": ["google"]}
assert 'data-col-fold="[&#34;naver&#34;, &#34;total&#34;]"' in client.get("/performance/?period=week&d=2026-10-07").text
assert client.put("/performance/api/my-col-fold", json={"kind": "x", "cols": []}).status_code == 400
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": "naver"}).status_code == 400
# 다른 사람 — 저장값 없음 → 다 펼침, 저장해도 king 값은 그대로
other = {"email": "u@x", "name": "U", "is_admin": False}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (client.store, other))
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (client.store, other))
assert 'data-col-fold="[]"' in client.get("/performance/?period=week&d=2026-10-07").text
client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": ["cafe24"]})
assert client.store.settings[mine]["sales"] == ["naver", "total"]
def raises(key, value, *, user=""):
raise SettingsMigrationNeeded()
client.store.set_setting = raises
assert client.put("/performance/api/my-col-fold", json={"kind": "sales", "cols": []}).status_code == 503
@@ -51,7 +51,7 @@ class _Store:
def test_sales_ad_channels_mapping(): def test_sales_ad_channels_mapping():
m = dashboard.sales_ad_channels() m = dashboard.sales_ad_channels()
assert m["cafe24"] == (("google", "구글"), ("meta", "메타")) assert m["cafe24"] == (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친"))
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),) assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
@@ -187,6 +187,29 @@ def test_kpi_is_net_only():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY) ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
assert [k["key"] for k in ctx["kpis"]] == ["net"] assert [k["key"] for k in ctx["kpis"]] == ["net"]
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567 assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
assert ctx["kpis"][0]["yoy_cmp"] == "전년 같은 기간" and ctx["kpis"][0]["yoy_delta"] is None # 작년 매출 없음
assert "yoy_cmp" not in dashboard.build_dashboard(_Store(), kind="year", anchor=TODAY, today=TODAY)["kpis"][0]
def test_kakao_pf_line_under_cafe24():
"""카톡 플친(2026-11-16) — 광고비 탭 열, ROAS 없음, 매출 탭 카페24 칸 아래 구글·메타 다음 줄."""
from app.modules.performance import ad_spend
assert ad_spend.CHANNEL_NAMES["kakao_pf"] == "카톡 플친" and "kakao_pf" not in ad_spend.ROAS_SALES_CODE
class _S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "kakao_pf"): 30_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 {}
day5 = next(r for r in dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)["table"]
if r.get("date") == "2026-10-05")
assert [(a["label"], a["amount"], a["roas"]) for a in day5["ads"]["cafe24"]] == [("구글", 100_000, None), ("카톡 플친", 30_000, None)]
assert day5["ads_total"]["amount"] == 130_000
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch): def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
@@ -0,0 +1,223 @@
"""[말레이시아 실적](2026-11-20) — 실적 라우터를 /malaysia/performance 에 한 번 더 붙인 인스턴스(variant.MY).
틱톡·쇼피·라자다 그룹(쇼핑몰 + 라이브커머스 하위), 금액 = 센 정수(RM 소수 2자리), 광고비 채널 = 틱톡·쇼피·라자다.
"""
from __future__ import annotations
import importlib
from datetime import date
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common, dashboard, formula, manual_upload, variant
TODAY = date(2026, 10, 7)
D5 = date(2026, 10, 5)
def _row(code, name, sort, **kw):
return {"code": code, "name": name, "sort_order": sort, "enabled": True, "include_in_sales": True,
"manual_input": True, "is_custom": True, "is_group": False, "parent_code": None, **kw}
class _Store:
"""scripts/sql/malaysia_performance_db_seed.sql 과 같은 행 — 그룹 3 + 하위(쇼핑몰·라이브) 6."""
def __init__(self):
self.rows = []
for i, (c, n) in enumerate((("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))):
self.rows += [_row(f"group_{c}", n, i * 10 + 10, is_group=True, include_in_sales=False, manual_input=False),
_row(f"custom_{c}_shop", f"{n} 쇼핑몰", i * 10 + 11, parent_code=f"group_{c}"),
_row(f"custom_{c}_live", f"{n} 라이브커머스", i * 10 + 12, parent_code=f"group_{c}")]
self.manual = {(D5, "custom_tiktok_shop"): 123_450, (D5, "custom_tiktok_live"): 10_005, # RM 1,234.50 · 100.05
(D5, "custom_shopee_shop"): 50_000}
self.ads = {(D5, "tiktok"): 26_691} # RM 266.91 → ROAS = 1,334.55 ÷ 266.91 = 500%
self.saved = []
def get_setting(self, key):
return None
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):
return {k: v for k, v in self.manual.items() if start <= k[0] <= end and k[1] in codes}
manual_amounts = lambda self, start, end, codes, active_only=True: self.daily_amounts(start, end, codes) # noqa: E731
def rate_table(self):
return {}
def statuses(self):
return {}
def last_update_at(self):
return None
def running_codes(self):
return []
def ad_amounts(self, start, end):
rows = {k: v for k, v in self.ads.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def set_manual_sale(self, code, d, amount, user="", formula=None):
self.saved.append(("sale", code, d, amount, formula))
def api_amount(self, code, d):
return 0
def set_ad_spend(self, channel, d, amount, *, source, user="", formula=None):
self.saved.append(("ad", channel, d, amount, formula))
@pytest.fixture()
def my():
token = variant._current.set(variant.MY)
yield
variant._current.reset(token)
@pytest.fixture()
def client(monkeypatch):
perf_router = importlib.import_module("app.modules.performance.router")
from app.modules.malaysia_performance import router as my_router
store = _Store()
user = {"email": "king@x", "name": "King", "is_admin": True}
class _Creds:
def configured_codes(self, adapters):
return {}
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)
app.include_router(my_router)
c = TestClient(app)
c.store = store
return c
def test_amount_parsing_scales_to_sen():
assert formula.parse_amount("1,234.5", 100) == (123_450, None)
assert formula.parse_amount("RM 10.005", 100) == (1001, None) # 센 미만 반올림
assert formula.parse_amount("10.5+20", 100) == (3050, "10.5+20")
assert formula.parse_amount("1000+2000") == (3000, "1000+2000") # 한국 실적 그대로(원)
assert manual_upload.parse_amount("RM 12.34", 100) == 1234 and manual_upload.parse_amount(12.345, 100) == 1235
assert manual_upload.parse_amount("12,000") == 12000
def test_text_helpers(my):
assert variant.num_text(123_450) == "1,234.50" and variant.money_text(5) == "RM 0.05"
assert variant.input_text(123_450) == "1234.50" and variant.input_text(None) == ""
assert dashboard.amount_text(-10_005, dashboard.load_unit(None)) == "-100.05"
def test_text_helpers_kr_unchanged():
assert variant.current() is variant.KR
assert variant.num_text(1234) == "1,234" and variant.money_text(1234) == "₩1,234" and variant.input_text(5) == "5"
def test_get_store_follows_variant(my):
state = SimpleNamespace(performance_store="kr", malaysia_performance_store="my")
assert common.get_store(SimpleNamespace(app=SimpleNamespace(state=state))) == "my"
def test_group_sums_and_ad_line_under_group(my):
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["cells"]["group_tiktok"]["gross"] == 133_455 # 쇼핑몰 + 라이브커머스
assert day5["total"]["gross"] == 183_455 # 그룹은 일 합계에 또 안 더함
assert day5["ads"]["group_tiktok"] == [{"label": "", "amount": 26_691, "roas": 500}]
def test_ad_dashboard_channels(my):
from app.modules.performance.ad_spend import build_ad_dashboard
ctx = build_ad_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY,
sales_codes=[m["code"] for m in dashboard._sales_marketplaces(_Store())])
assert ctx["codes"] == ["tiktok", "shopee", "lazada"] and ctx["upload_channels"] == []
day5 = next(r for r in ctx["table"] if r.get("date") == D5.isoformat())
assert day5["roas"]["tiktok"] == 500 and day5["roas"]["shopee"] is None
assert ctx["kpis"][1]["note"].startswith("총매출 RM ")
def test_pages_render_malaysia(client):
html = client.get("/malaysia/performance/?period=week&d=2026-10-07").text
assert 'data-base="/malaysia/performance"' in html and 'data-cents="1"' in html
assert 'href="/malaysia/performance/ads"' in html and 'id="perf-sync-btn"' not in html
assert "1,234.50" in html and "1,334.55" in html and 'data-manual-value="1234.50"' in html
assert 'data-group-cell="group_tiktok"' in html and "266.91" in html
ads = client.get("/malaysia/performance/ads?period=week&d=2026-10-07").text
assert ">틱톡" in ads and "구글" not in ads.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert '"manual_api": "/malaysia/performance/api/ad-spend/"' in ads
settings = client.get("/malaysia/performance/settings").text
assert "광고 API 연동" not in settings and "자동 업데이트" not in settings and "매출 단위" not in settings
# 같은 앱의 한국 실적은 그대로
kr = client.get("/performance/?period=week&d=2026-10-07").text
assert 'data-base="/performance"' in kr and "data-cents" not in kr
def test_api_saves_sen(client):
r = client.put("/malaysia/performance/api/manual-sales/custom_tiktok_live/2026-10-07", json={"amount": "12.34"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("sale", "custom_tiktok_live", TODAY, 1234, None)
r = client.put("/malaysia/performance/api/ad-spend/shopee/2026-10-07", json={"amount": "1.5*2"})
assert r.status_code == 200, r.text
assert client.store.saved[-1] == ("ad", "shopee", TODAY, 300, "1.5*2")
assert client.put("/malaysia/performance/api/ad-spend/google/2026-10-07", json={"amount": "1"}).status_code == 404
assert client.get("/malaysia/performance/health").json()["module"] == "malaysia_performance"
def test_sample_lists_malaysia_shops(client):
import io
import openpyxl
r = client.get("/malaysia/performance/api/manual-sales/sample.xlsx")
assert r.status_code == 200
head = next(openpyxl.load_workbook(io.BytesIO(r.content)).active.iter_rows(values_only=True))
assert head[:3] == ("날짜", "틱톡 쇼핑몰", "틱톡 라이브커머스") and len(head) == 7
def test_detect_lang_rule():
"""한영 전환(2026-11-20) — 고른 값(쿠키) 먼저, 없으면 브라우저·OS 첫 언어: ko… = 한국어, 그 밖 = 영어, 머리글 없음 = 한국어."""
from app.lang import detect_lang
assert detect_lang(None, "ko-KR,ko;q=0.9,en-US;q=0.8") == "ko" and detect_lang(None, "ko") == "ko"
assert detect_lang(None, "en-US,en;q=0.9,ko;q=0.8") == "en" and detect_lang(None, "ms-MY,ms") == "en"
assert detect_lang(None, "") == "ko" and detect_lang(None, None) == "ko" and detect_lang("<x>", "zh-CN") == "en"
assert detect_lang("ko", "en-US") == "ko" and detect_lang("en", "ko-KR") == "en"
def test_malaysia_page_language(client):
url = "/malaysia/performance/?period=week&d=2026-10-07"
en = client.get(url, headers={"Accept-Language": "en-US,en;q=0.9"}).text
assert 'data-lang="en"' in en and "performance-en.js" in en and 'data-perf-lang="en" class="is-active"' in en
assert "Malaysia Sales" in en and "Deepavali" not in en # 머리 제목 영문, 공휴일은 말레이시아 표(10월 주엔 없음)
ko = client.get(url, headers={"Accept-Language": "ko-KR,ko"}).text
assert 'data-lang="ko"' in ko and "performance-en.js" not in ko
client.cookies.set("mperf_lang", "ko")
assert "performance-en.js" not in client.get(url, headers={"Accept-Language": "en-US"}).text # 고른 값이 먼저
client.cookies.clear()
kr = client.get("/performance/?period=week&d=2026-10-07", headers={"Accept-Language": "en-US"}).text
assert 'data-lang="ko"' in kr and "performance-en.js" not in kr and 'data-perf-lang' not in kr # 한국 실적은 늘 한글·토글 없음
def test_malaysia_holidays(my):
perf_router = importlib.import_module("app.modules.performance.router")
assert perf_router._holidays()["2026-08-31"] == "독립기념일"
token = variant._lang.set("en")
try:
assert perf_router._holidays()["2026-08-31"] == "Merdeka Day"
finally:
variant._lang.reset(token)
@@ -160,6 +160,11 @@ def test_periods():
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게) # 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31)) s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28)) assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
# 전년 같은 기간 — 진행 중이면 오늘까지, 2/29 → 2/28
s, e, label = calc.resolve_period("month", date(2026, 11, 16)).yoy_range(today=date(2026, 11, 16))
assert (s, e, label) == (date(2025, 11, 1), date(2025, 11, 16), "전년 같은 기간")
s, e, _ = calc.resolve_period("month", date(2028, 2, 10)).yoy_range(today=date(2028, 3, 5))
assert (s, e) == (date(2027, 2, 1), date(2027, 2, 28))
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
@@ -1,216 +0,0 @@
"""틱톡 탭(2026-11-05) — 입력 검사·요청 매개변수·30일 나누기·매출 합산·환율·오류 안내·화면 데이터·다른 탭과 분리.
틱톡 서버는 가짜(httpx MockTransport)."""
from __future__ import annotations
import json
from datetime import date
from decimal import Decimal
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from app.modules.performance import ad_spend, fx
from app.modules.performance.ad_sources import tiktok_ads as tt
from app.modules.performance.ad_sources.registry import get_source
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, TokenExpired
TOKEN = "tiktoktoken0123456789abcdefSECRET"
class Creds:
def __init__(self, values):
self.values = values
def get(self, key):
return self.values.get(key, "")
def has(self, key):
return bool(self.values.get(key))
def ctx(**extra):
return AdapterContext(code="tiktok", credentials=Creds({"advertiser_id": "71234567", "access_token": TOKEN, **extra}), timeout_sec=5.0)
def server(monkeypatch, *, currency="KRW", report=None, gmv=None, seen=None):
"""가짜 틱톡 + 환율 서버. seen 에 (경로, 쿼리, 머리글)을 쌓는다."""
def handler(req: httpx.Request) -> httpx.Response:
url = urlparse(str(req.url))
q = {k: v[0] for k, v in parse_qs(url.query).items()}
if seen is not None:
seen.append((url.path, q, req.headers.get("access-token")))
if "business-api.tiktok.com" not in str(req.url):
return httpx.Response(200, json=[{"date": "2026-10-05", "base": "MYR", "quote": "KRW", "rate": 300}])
if url.path.endswith("/advertiser/info/"):
return httpx.Response(200, json={"code": 0, "data": {"list": [{"name": "DBX", "currency": currency, "timezone": "Asia/Seoul"}]}})
rows = gmv if url.path.endswith("/gmv_max/report/get/") else report
if isinstance(rows, httpx.Response):
return rows
return httpx.Response(200, json={"code": 0, "data": {"list": [
{"dimensions": {"stat_time_day": f"{d} 00:00:00"}, "metrics": m} for d, m in (rows or {}).items()]}})
monkeypatch.setattr(tt, "_http", lambda c: httpx.Client(transport=httpx.MockTransport(handler)))
def test_registered_but_not_a_channel():
"""틱톡은 광고 연동에는 있지만 광고비 탭 채널이 아니다(틱톡 탭에서만 보임)."""
assert get_source("tiktok").name == "틱톡"
assert "tiktok" not in ad_spend.CHANNEL_CODES
@pytest.mark.parametrize("values,word", [
({"advertiser_id": "abc", "access_token": TOKEN}, "광고 계정 ID"),
({"advertiser_id": "71234567", "access_token": "short"}, "액세스 토큰"),
({"advertiser_id": "71234567", "access_token": TOKEN, "shop_id": "x1"}, "틱톡샵 ID"),
])
def test_validation(values, word):
assert any(word in e for e in tt.TiktokAdsSource().validate_credentials(values))
def test_stored_values_pass_validation():
assert tt.TiktokAdsSource().validate_credentials({"advertiser_id": "71234567", "access_token": "__stored__"}) == []
def test_fetch_sums_revenue_and_splits_30_days(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {
"spend": "1000", "impressions": "50", "clicks": "5", "complete_payment": "1", "onsite_shopping": "2",
"total_complete_payment_rate": "2000", "total_onsite_shopping_value": "1000.4"}})
days = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 9, 1), date(2026, 11, 3))
reports = [q for path, q, _ in seen if path.endswith("/report/integrated/get/")]
assert [(q["start_date"], q["end_date"]) for q in reports] == [
("2026-09-01", "2026-09-30"), ("2026-10-01", "2026-10-30"), ("2026-10-31", "2026-11-03")]
assert reports[0]["data_level"] == "AUCTION_ADVERTISER" and "stat_time_day" in json.loads(reports[0]["dimensions"])
assert not [p for p, _, _ in seen if p.endswith("/gmv_max/report/get/")] # 틱톡샵 ID 없으면 안 물음
assert all(h == TOKEN for _, _, h in seen) and not any(TOKEN in json.dumps(q) for _, q, _ in seen) # 토큰은 머리글로만
# 같은 날 응답이 쪽마다 오므로 3번 더해진다 — 가짜 서버가 기간과 무관하게 같은 줄을 주는 탓, 합산 동작 자체를 확인
d = days[0]
assert d.day == date(2026, 10, 5) and d.amount == 3000 and d.metrics[tt.M_REVENUE] == 9001
assert d.roas == Decimal("300.04") and d.metrics[tt.M_ORDERS] == 9
def test_gmv_max_added_only_with_shop_id(monkeypatch):
seen = []
server(monkeypatch, seen=seen, report={"2026-10-05": {"spend": "100", "total_onsite_shopping_value": "100"}},
gmv={"2026-10-05": {"cost": "100", "gross_revenue": "500", "orders": "3"}})
d = tt.TiktokAdsSource().fetch_days(ctx(shop_id="7555"), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 200 and d.metrics[tt.M_REVENUE] == 600 and d.roas == Decimal("300.00")
assert d.metrics[tt.M_GMV_REVENUE] == 500 and d.metrics[tt.M_GMV_COST] == 100 # 대조용으로 따로 남김
gmv_q = next(q for p, q, _ in seen if p.endswith("/gmv_max/report/get/"))
assert json.loads(gmv_q["store_ids"]) == ["7555"]
def test_foreign_currency_uses_that_day_rate(monkeypatch):
fx.clear_cache()
server(monkeypatch, currency="MYR", report={"2026-10-05": {"spend": "10", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.amount == 3000 and d.metrics[tt.M_REVENUE] == 12000 and d.roas == Decimal("400.00")
fx.clear_cache()
def test_no_spend_means_no_roas(monkeypatch):
server(monkeypatch, report={"2026-10-05": {"spend": "0", "total_onsite_shopping_value": "40"}})
d = tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))[0]
assert d.roas is None and d.metrics[tt.M_ROAS] is None
@pytest.mark.parametrize("code,exc", [(40102, TokenExpired), (40105, AuthFailed), (40100, ApiError), (40002, ApiError)])
def test_error_codes(monkeypatch, code, exc):
server(monkeypatch, report=httpx.Response(200, json={"code": code, "message": "bad"}))
with pytest.raises(exc) as got:
tt.TiktokAdsSource().fetch_days(ctx(), date(2026, 10, 5), date(2026, 10, 5))
assert str(code) in str(got.value) and TOKEN not in str(got.value)
def test_connection_also_asks_report(monkeypatch):
"""연결 테스트가 보고서까지 물어야 지표 이름 오류를 저장 전에 잡는다."""
seen = []
server(monkeypatch, seen=seen)
msg = tt.TiktokAdsSource().test_connection(ctx())
assert "DBX" in msg and "KRW" in msg
assert any(p.endswith("/report/integrated/get/") for p, _, _ in seen)
class Store:
def __init__(self, rows=None, missing=False):
self.rows, self.missing = rows or [], missing
def ad_details(self, code, start, end):
assert code == "tiktok"
if self.missing:
raise ad_spend.AdMigrationNeeded("005")
return [r for r in self.rows if start.isoformat() <= r["date"] <= end.isoformat()]
def row(day, spend, sales):
return {"date": day, "amount": spend, "roas": None, "metrics": {tt.M_REVENUE: sales}, "source": "api"}
def test_dashboard_table_and_kpis():
store = Store([row("2026-10-05", 1000, 3000), row("2026-10-06", 1000, 1000), row("2026-09-05", 500, 500)])
ctx_ = ad_spend.build_tiktok_dashboard(store, kind="month", anchor=date(2026, 10, 15), today=date(2026, 10, 31),
holidays={"2026-10-09": "한글날"})
total = ctx_["table"][0]
assert total["kind"] == "total" and total["cells"]["spend"]["gross"] == 2000 and total["cells"]["sales"]["gross"] == 4000 and total["roas"] == 200
day = next(r for r in ctx_["table"] if r.get("date") == "2026-10-05")
assert day["roas"] == 300
assert next(r for r in ctx_["table"] if r.get("date") == "2026-10-09")["holiday"] == "한글날"
kpi = {k["key"]: k for k in ctx_["kpis"]}
assert kpi["spend"]["value"] == 2000 and kpi["sales"]["value"] == 4000 and kpi["roas"]["pct"] == 200
assert kpi["spend"]["delta"] == 300.0 and kpi["sales"]["delta"] == 700.0
assert ctx_["year"]["spend"] == 2500 and ctx_["year"]["sales"] == 4500 and ctx_["year"]["rows"][9]["roas"] == 200
assert ctx_["year"]["rows"][10]["future"] is True and ctx_["year"]["rows"][10]["roas"] is None
assert sum(p["gross"] for p in ctx_["chart_sales"]) == 4000 and sum(p["gross"] for p in ctx_["chart_spend"]) == 2000
def test_dashboard_without_table_or_data():
got = ad_spend.build_tiktok_dashboard(Store(missing=True), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["migration_needed"] is True and got["table"][0]["roas"] is None
assert {k["key"]: k for k in got["kpis"]}["roas"]["pct"] is None
def test_ads_tab_ignores_tiktok_rows():
"""perf_ad_spend 에 틱톡 줄이 있어도 광고비 탭 합계에 안 들어간다."""
class AdStore:
def ad_amounts(self, start, end):
return {(date(2026, 10, 5), "google"): 100, (date(2026, 10, 5), "tiktok"): 9000}, {}
def daily_amounts(self, start, end, codes):
return {}
got = ad_spend.build_ad_dashboard(AdStore(), kind="month", anchor=date(2026, 10, 1), today=date(2026, 10, 31))
assert got["table"][0]["total"]["gross"] == 100 and "tiktok" not in got["codes"]
assert {k["key"]: k for k in got["kpis"]}["spend"]["value"] == 100
def test_page_renders_after_ads_tab(monkeypatch):
"""진짜 라우터·템플릿 — 탭 순서, 열 순서, 값, 미설정 안내, 칸 입력 없음."""
import importlib
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.modules.performance import common
perf_router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
store = Store([row("2026-10-05", 1000, 3000)])
user = {"email": "a@x", "name": "A", "role": "user"}
class Sync:
def configured(self):
return {"google": True, "tiktok": False}
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, user))
monkeypatch.setattr(perf_router, "_ad_services", lambda st: (None, Sync()))
monkeypatch.setattr(perf_router, "_auto_sync_ctx", lambda st, kind: None)
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 31))
app = FastAPI()
app.include_router(perf_router.router)
html = TestClient(app).get("/performance/tiktok").text
tabs = html.split('class="perf-tabs-main"', 1)[1]
assert tabs.index("광고비</a>") < tabs.index("틱톡</a>") and "perf-tab-tiktok is-active" in tabs
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
assert head.index("ROAS") < head.index("광고비") < head.index("매출")
assert "3,000" in html and "300%" in html
assert "틱톡 API 가 아직 설정되지 않았습니다" in html and "data-manual-code" not in html
+99
View File
@@ -0,0 +1,99 @@
"""실적 모듈 인스턴스(2026-11-20) — 같은 코드·화면으로 [실적](한국)과 [말레이시아 실적]을 띄운다.
app.main 이 router 를 두 번 붙인다: /performance(한국, 기본값) · /malaysia/performance(말레이시아 — 마운트 의존성
use_malaysia 가 이 요청의 ContextVar 를 MY 로). 저장소·권한키·주소·광고 채널·통화는 current() 로 읽는다.
데이터는 DB 로 나뉜다(같은 표 구조 — malaysia_performance_db, app/modules/malaysia_performance/CLAUDE.md).
"""
from __future__ import annotations
from contextvars import ContextVar
from dataclasses import dataclass, field
from decimal import ROUND_HALF_UP, Decimal
from typing import Any
from fastapi import Request
from app.lang import detect_lang
@dataclass(frozen=True)
class Variant:
key: str # kr | my
base: str # 주소 앞부분(템플릿·JS 가 이 뒤에 /api/… 를 붙인다)
module_key: str # 권한키
module_name: str # 메뉴·탭 이름
store_attr: str # app.state 저장소 이름
db_name: str # 안내 문구용
scale: int = 1 # 금액 저장 단위 — 1 = 원, 100 = 센(RM 소수 2자리를 정수로 저장해 계산은 그대로)
currency: str = "₩"
# 광고비 탭 채널 — 비면 한국 실적 채널(ad_spend.CHANNELS)
ad_channels: tuple[tuple[str, str], ...] = ()
# 광고 채널 → ROAS 매출 쇼핑몰 코드들(합계) · 매출 실적 열(그룹) → 그 칸 아래 광고비 줄 [(채널, 줄 이름)]
ad_roas_sales: dict[str, tuple[str, ...]] = field(default_factory=dict)
ad_lines: dict[str, tuple[tuple[str, str], ...]] = field(default_factory=dict)
@property
def is_kr(self) -> bool:
return self.key == "kr"
KR = Variant("kr", "/performance", "performance", "실적", "performance_store", "performance_db")
# 쇼핑몰마다 그룹(합계 열) + 쇼핑몰·라이브커머스 하위 2개 — 코드는 scripts/sql/malaysia_performance_db_seed.sql 과 같다
_MY_SHOPS = (("tiktok", "틱톡"), ("shopee", "쇼피"), ("lazada", "라자다"))
MY = Variant(
"my", "/malaysia/performance", "malaysia_performance", "말레이시아 실적", "malaysia_performance_store",
"malaysia_performance_db", scale=100, currency="RM",
ad_channels=_MY_SHOPS,
ad_roas_sales={c: (f"custom_{c}_shop", f"custom_{c}_live") for c, _ in _MY_SHOPS},
ad_lines={f"group_{c}": ((c, ""),) for c, _ in _MY_SHOPS},
)
_current: ContextVar[Variant] = ContextVar("perf_variant", default=KR)
# 화면 언어(2026-11-20) — 말레이시아 실적만 한영 전환(쿠키 → 없으면 브라우저·OS 언어, app/lang.py). 한국 실적은 늘 ko.
LANG_COOKIE = "mperf_lang"
_lang: ContextVar[str] = ContextVar("perf_lang", default="ko")
def current() -> Variant:
return _current.get()
def lang() -> str:
return _lang.get()
async def use_malaysia(request: Request) -> None:
"""말레이시아 마운트 의존성 — async 라 요청 태스크 컨텍스트에 설정되고 동기 핸들러(스레드풀)로 복사된다."""
_current.set(MY)
_lang.set(detect_lang(request.cookies.get(LANG_COOKIE), request.headers.get("accept-language")))
def num_text(value: Any) -> str:
"""금액(저장 단위 정수) → 쉼표 숫자. 원 = 정수, 센 = RM 소수 2자리."""
v = current()
if v.scale == 1:
return f"{int(value or 0):,}"
return f"{(Decimal(int(value or 0)) / v.scale).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,.2f}"
def money_text(value: Any) -> str:
"""통화 기호 붙인 금액 — ₩1,234 / RM 1,234.50."""
v = current()
return f"₩{num_text(value)}" if v.scale == 1 else f"{v.currency} {num_text(value)}"
def input_text(value: Any) -> str:
"""날짜 칸 편집창에 보일 값(쉼표 없음) — 빈 값은 빈 글자."""
if value in (None, ""):
return ""
v = current()
if v.scale == 1:
return str(int(value))
return f"{Decimal(int(value)) / v.scale:.2f}"
def template_ctx() -> dict[str, Any]:
"""모든 실적 화면 공통 — pv(인스턴스), num·money·inval(금액 글자), lang(ko|en — 영문이면 performance-en.js 가 번역)."""
return {"pv": current(), "num": num_text, "money_t": money_text, "inval": input_text, "lang": lang()}
+17 -2
View File
@@ -17,6 +17,8 @@
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title). - 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다. - 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
- UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것. - UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것.
- **시각 고르기 = 공용 시각 팝업**(2026-11-11, `openTimePopover`·`enhanceTimeInput`, `PJLib` 로도) — 날짜 팝업 모양, 시 00~23·분 5분 단위, 끝에서 멈춤.
프로젝트(긴급 공지 포함)에서 `<input type="time">` 기본 시계 금지. 모달 dialog 안 칸이면 그 창 안에 popover 로 붙음(body 면 inert 로 마우스가 안 먹음).
- 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css` - 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css`
(2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨). (2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨).
@@ -24,7 +26,8 @@
- **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**. - **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**.
- 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다. - 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다.
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버·소유자 변경. - Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·담당자별 합계·전체 멤버·소유자 변경.
- 전체 보기 메뉴 = Project 옵션 대상자(아래 "Project 옵션" 절, `access.can_all_view`, 화면 `pj_all_view`).
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14). - Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). - 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403). - 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
@@ -47,7 +50,7 @@
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe). - 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글. - 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다. - 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
- 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표. - 사이드바 메뉴: 수신함·전체 보기(Project 옵션 대상자 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다. - 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝). - 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부). **필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
@@ -95,6 +98,14 @@
## 알림 ## 알림
- **매일 하는 업무**(2026-11-11, 마이그레이션 033 `tasks.repeat_daily`) — 날짜 팝업 `openDatePopover({allowDaily, daily})` 아래 [매일](repeat 아이콘) =
`{due_date: null, repeat_daily: true}`(서버 `db.update_task` 가 마감일·시각 비움, 마감일을 고르면 자동으로 꺼짐). 업무 행에 `repeat_daily` 키가 있을 때만(=033 적용) 버튼이 보인다.
카드·목록·내 업무·세부 업무·업무 창 마감 칸 = `dueInfo(…, daily)` → `.is-daily`(CSS ::before repeat 아이콘 + "매일", 노랑).
알림 = `reminders.run_daily_alerts`(데몬 1분 주기, 영업일, `daily_alert_times` 중 지난 가장 늦은 시각 하나 — `task_reminders` kind `daily@HH:MM`·그날로 중복 방지)
→ 담당자(없으면 협업자)에게 `type=daily` 알림 → 큰 팝업 `_ALERT_TYPES` 에 포함, 줄 배경 노랑(`.pj-alert-item.is-daily`), PC 알림 프로그램 `Alert.IsDaily`.
추가 칸(보드 아래 메인 업무 추가·카드 세부 업무 추가 줄)에도 [매일] — `data-daily-ready`(`db.daily_ready`), `POST …/tasks` 의 `repeat_daily: true` = 만든 뒤 `update_task` 로 켬.
033 미적용이면 [매일] 숨김·PUT/POST 503·알림 skip.
- 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐. - 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`). - 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17). - **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
@@ -111,6 +122,10 @@
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에. - 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`). - 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`). - 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`).
- **"전체 보기" 메뉴를 볼 사람**(2026-11-11) = 프로젝트 화면 분류에 처음 여는 탭과 묶음. 옵션 키 `all_view_users`(이메일 목록, DB 변경 없음 — 029 키·값 표),
`null`(설정 전) = 예전처럼 Pro user 이상. 후보 = `GET /api/assignable-users`(아이콘+이름 `memberPickHtml`, `pro` 표시로 기본 체크) + [전체 선택/해제].
메뉴 표시만 정함(데이터는 멤버 범위 그대로) — 사이드바 `pj_all_view`(`_role_ctx(user, request)`), `project.js canAllView`(`data-all-view`). 대시보드 담당자별 합계는 여전히 Pro user 이상.
- **알림 분류 — 매일 하는 업무 알림 시각**(2026-11-11) = 옵션 키 `daily_alert_times`(["HH:MM"…] 최대 12, 기본 ["09:00"], 빈 목록 = 끔). 행마다 시각 칸 + 휴지통, [알림 추가].
- 긴급 공지 = 수퍼관리자만. - 긴급 공지 = 수퍼관리자만.
## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9) ## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9)
+8
View File
@@ -70,6 +70,14 @@ def is_pro(user: dict[str, Any] | None) -> bool:
return role_of(user) in ("super", "admin", "pro") return role_of(user) in ("super", "admin", "pro")
def can_all_view(user: dict[str, Any] | None, allowed: list[str] | None) -> bool:
"""왼쪽 "전체 보기" 메뉴를 보는가 — Project 옵션 all_view_users(목록에 든 사람만), 설정 전(None)이면 Pro user 이상.
메뉴 표시만 정한다 — 전체 보기도 멤버인 프로젝트 범위라 데이터 권한은 그대로(모듈 권한은 화면 진입에서 이미 확인)."""
if allowed is None:
return is_pro(user)
return str((user or {}).get("email") or "").strip().lower() in allowed
def sees_all_projects(user: dict[str, Any] | None) -> bool: def sees_all_projects(user: dict[str, Any] | None) -> bool:
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야).""" """멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
return can_use_module(user) and _is_super(user) return can_use_module(user) and _is_super(user)
+45 -3
View File
@@ -888,6 +888,14 @@ class ProjectStore:
for k in ("start_time", "due_time"): for k in ("start_time", "due_time"):
if k in fields: if k in fields:
clean[k] = store.validate_time(fields[k]) clean[k] = store.validate_time(fields[k])
# 매일 하는 업무(033) — 켜면 마감일·마감 시각을 비운다(마감일 없이 매일).
if "repeat_daily" in fields:
if not isinstance(fields["repeat_daily"], bool):
raise ValueError("매일 반복 값이 올바르지 않습니다.")
clean["repeat_daily"] = fields["repeat_daily"]
if fields["repeat_daily"]:
clean["due_date"] = None
clean["due_time"] = None
newly_assigned: str | None = None newly_assigned: str | None = None
newly_completed = False newly_completed = False
@@ -899,7 +907,11 @@ class ProjectStore:
prev = self._serialize(row) prev = self._serialize(row)
sets: list[str] = [] sets: list[str] = []
params: list[Any] = [] params: list[Any] = []
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"): # 마감일을 고르면 매일 반복은 꺼진다(열이 있을 때만 — 033 미적용이면 키가 없다)
if clean.get("due_date") and prev.get("repeat_daily") and "repeat_daily" not in clean:
clean["repeat_daily"] = False
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time",
"repeat_daily"):
if k in clean: if k in clean:
sets.append(f"{k} = %s") sets.append(f"{k} = %s")
params.append(clean[k]) params.append(clean[k])
@@ -1746,6 +1758,18 @@ class ProjectStore:
([int(i) for i in ordered_ids], stage_id), ([int(i) for i in ordered_ids], stage_id),
) )
def daily_ready(self) -> bool:
"""tasks.repeat_daily(마이그레이션 033, 매일 하는 업무) 가 있는지. 한 번 켜지면 기억."""
if getattr(self, "_daily_ready", False):
return True
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
"AND table_name = 'tasks' AND column_name = 'repeat_daily'"
).fetchone())
self._daily_ready = ok
return ok
def link_order_ready(self) -> bool: def link_order_ready(self) -> bool:
"""task_project_links.sort_order(마이그레이션 032) 가 있는지. 한 번 켜지면 기억.""" """task_project_links.sort_order(마이그레이션 032) 가 있는지. 한 번 켜지면 기억."""
if getattr(self, "_link_order_ready", False): if getattr(self, "_link_order_ready", False):
@@ -2268,9 +2292,27 @@ class ProjectStore:
).fetchall() ).fetchall()
return [self._serialize(r) for r in rows] return [self._serialize(r) for r in rows]
def list_open_daily_tasks(self) -> list[dict[str, Any]]:
"""매일 하는 업무(033 repeat_daily) 중 미완료 + 팔로워 목록. 보관 프로젝트는 뺀다.
033 미적용이면 psycopg_errors.UndefinedColumn(알림 데몬이 그날은 건너뜀)."""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT t.id, t.title, t.assignee_email, t.project_id, t.parent_task_id, p.name AS project_name,
COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email)
FROM task_followers f WHERE f.task_id = t.id),
'{}'::text[]) AS followers
FROM tasks t
JOIN projects p ON p.id = t.project_id
WHERE t.repeat_daily AND t.completed_at IS NULL AND p.status <> 'archived'
ORDER BY t.id
""",
).fetchall()
return [self._serialize(r) for r in rows]
def add_reminder_notification( def add_reminder_notification(
self, *, task_id: int, kind: str, due_date: str, recipient_email: str, self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
project_id: int | None, title: str, body: str, project_id: int | None, title: str, body: str, ntype: str | None = None,
) -> bool: ) -> bool:
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True, """마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서 이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
@@ -2289,7 +2331,7 @@ class ProjectStore:
"INSERT INTO project_notifications " "INSERT INTO project_notifications "
"(recipient_email, actor_email, project_id, task_id, type, title, body) " "(recipient_email, actor_email, project_id, task_id, type, title, body) "
"VALUES (%s,'',%s,%s,%s,%s,%s)", "VALUES (%s,'',%s,%s,%s,%s,%s)",
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)), (rcpt, project_id, task_id, ntype or kind, store.norm_str(title), store.norm_str(body)),
) )
return True return True
+60 -2
View File
@@ -15,6 +15,11 @@
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가 "오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다. 동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다.
매일 하는 업무(033 tasks.repeat_daily, run_daily_alerts) — Project 옵션 daily_alert_times 시각(KST, 영업일)이
지나면 미완료 매일 업무의 담당자(없으면 협업자)에게 수신함 알림(type=daily, 큰 팝업에 따로 색). 데몬은 1분마다 깨어
지난 시각 중 가장 늦은 것 하나만 보낸다(서버가 꺼져 있다 켜져도 몇 번씩 쏟아지지 않게). 중복 방지는 같은
task_reminders(kind='daily@HH:MM', due_date=그날).
환경변수: 환경변수:
PROJECT_REMINDERS false 면 끈다(기본 켜짐) PROJECT_REMINDERS false 면 끈다(기본 켜짐)
PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9) PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
@@ -41,6 +46,7 @@ logger = logging.getLogger("project.reminders")
KIND_DUE_SOON = "due_soon" KIND_DUE_SOON = "due_soon"
KIND_DUE_TODAY = "due_today" KIND_DUE_TODAY = "due_today"
KIND_OVERDUE = "overdue" KIND_OVERDUE = "overdue"
NTYPE_DAILY = "daily"
OVERDUE_WINDOW_DAYS = 7 OVERDUE_WINDOW_DAYS = 7
@@ -139,6 +145,39 @@ def run_due_reminders(
return counts return counts
def daily_slot(times: list[str], hhmm: str) -> str | None:
"""설정 시각들 중 지금(hhmm)까지 지난 가장 늦은 시각 — 없으면 None."""
passed = [t for t in times if t <= hhmm]
return max(passed) if passed else None
def run_daily_alerts(
st: Any, *, today: date, slot: str, lookup: access.UserLookup | None = None,
) -> int:
"""매일 하는 업무 알림 한 번(그날 slot 시각분). 새로 만든 알림 수. 수신자·권한·중복 규칙은 마감 알림과 같다."""
made = 0
for t in st.list_open_daily_tasks():
assignee = store.norm_str(t.get("assignee_email"), lower=True)
wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
try:
recipients = access.filter_recipients(st, t, wanted, lookup)
except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다
logger.warning("매일 업무 알림 수신자 확인 실패: task=%s", t["id"])
continue
for rcpt in recipients:
try:
created = st.add_reminder_notification(
task_id=t["id"], kind=f"daily@{slot}", due_date=today.isoformat(), recipient_email=rcpt,
project_id=t["project_id"], title=f"매일 업무: {t['title']}",
body=f"{t.get('project_name') or ''} · 매일 {slot}", ntype=NTYPE_DAILY,
)
except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도
logger.warning("매일 업무 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"])
continue
made += int(bool(created))
return made
def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None: def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None:
from app.mail import send_email # noqa: WPS433 from app.mail import send_email # noqa: WPS433
@@ -176,10 +215,14 @@ def start_reminder_thread(st: Any) -> bool:
def _loop() -> None: def _loop() -> None:
last_run: date | None = None last_run: date | None = None
last_due_try = 0.0
daily_done: tuple[date, str] | None = None # 마지막으로 보낸 (날짜, 시각)
while True: while True:
try:
now = now_kst() now = now_kst()
today = now.date() today = now.date()
if time.monotonic() - last_due_try >= 300: # 마감 알림은 예전처럼 5분마다 확인
last_due_try = time.monotonic()
try:
if last_run != today and now.hour >= hour and is_workday(today): if last_run != today and now.hour >= hour and is_workday(today):
counts = run_due_reminders(st, today=today) counts = run_due_reminders(st, today=today)
last_run = today last_run = today
@@ -191,7 +234,22 @@ def start_reminder_thread(st: Any) -> bool:
last_run = now_kst().date() last_run = now_kst().date()
else: else:
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__) logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
time.sleep(300) try:
if is_workday(today):
times = store.normalize_project_options(st.get_project_options())["daily_alert_times"]
slot = daily_slot(times, now.strftime("%H:%M"))
if slot and daily_done not in ((today, slot), (today, "skip")):
made = run_daily_alerts(st, today=today, slot=slot)
daily_done = (today, slot)
if made:
logger.info("매일 업무 알림 %s: %d건", slot, made)
except Exception as exc: # noqa: BLE001
if type(exc).__name__ in ("UndefinedColumn", "UndefinedTable"):
daily_done = (today, "skip") # 033(또는 008) 미적용 — 오늘은 그만(로그 도배 방지)
logger.warning("매일 업무 알림 skip — project_db_033 마이그레이션 필요")
else:
logger.warning("매일 업무 알림 실패(%s) — 1분 뒤 재시도", type(exc).__name__)
time.sleep(60)
threading.Thread(target=_loop, name="project-reminders", daemon=True).start() threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
return True return True
+33 -16
View File
@@ -105,12 +105,15 @@ def _require_pro(request: Request) -> dict[str, Any]:
return user return user
def _role_ctx(user: dict[str, Any]) -> dict[str, Any]: def _role_ctx(user: dict[str, Any], request: Request | None = None) -> dict[str, Any]:
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용.""" """화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용,
pj_all_view 는 왼쪽 "전체 보기" 메뉴(Project 옵션 all_view_users — request 가 없으면 옵션 기본값 기준)."""
from app.store import is_admin # noqa: WPS433 from app.store import is_admin # noqa: WPS433
opts = _project_options(_store(request) if request is not None else None)
return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user), return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user),
"pj_admin": access.is_project_admin(user)} "pj_admin": access.is_project_admin(user),
"pj_all_view": access.can_all_view(user, opts["all_view_users"])}
def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool: def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool:
@@ -429,7 +432,7 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 " "scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
"컨테이너를 재기동하세요.", "컨테이너를 재기동하세요.",
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
}, },
status_code=503, status_code=503,
@@ -678,7 +681,7 @@ def my_tasks_page(request: Request) -> HTMLResponse:
"project/mytasks.html", "project/mytasks.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"page_title": "내 업무", "page_title": "내 업무",
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.", "page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
@@ -726,7 +729,7 @@ def task_permalink(request: Request, task_id: int):
{ {
"reason": reason, "reason": reason,
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
}, },
status_code=status, status_code=status,
@@ -806,7 +809,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. " "reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.", "프로젝트 관리자에게 멤버 배정을 요청하세요.",
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
}, },
status_code=403, status_code=403,
@@ -896,8 +899,9 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
"project/project.html", "project/project.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"pj_options": _project_options(st), "pj_options": _project_options(st),
"pj_daily_ready": st.daily_ready(), # 033 — 새 업무·세부 업무 추가 칸 날짜 팝업의 [매일]
"can_manage": can_manage, "can_manage": can_manage,
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"page_title": project["name"], "page_title": project["name"],
@@ -967,7 +971,7 @@ def _db_or_503(request: Request) -> Any:
def _project_options(st: Any) -> dict[str, Any]: def _project_options(st: Any) -> dict[str, Any]:
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다.""" """시스템 Project 옵션(처음 여는 탭·보드 카드 표지·전체 보기 대상자) — 읽기 실패해도 화면은 기본값으로 연다."""
if st is None: if st is None:
return store.normalize_project_options(None) return store.normalize_project_options(None)
try: try:
@@ -1218,6 +1222,7 @@ def api_assignable_users(request: Request) -> JSONResponse:
"name": u.get("name") or u["email"].split("@")[0], "name": u.get("name") or u["email"].split("@")[0],
"id": u["email"].split("@")[0], "id": u["email"].split("@")[0],
"avatar": u.get("picture") or "", "avatar": u.get("picture") or "",
"pro": access.is_pro(u), # Project 옵션 "전체 보기" 대상자 기본값(설정 전 = Pro user 이상)
} }
for u in user_store.list_all() for u in user_store.list_all()
if has_module(u, "project") if has_module(u, "project")
@@ -1545,12 +1550,22 @@ def _create_task_for(
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그. """작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서.""" 돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
project, followers = _task_create_checks(request, st, user, project_id, payload) project, followers = _task_create_checks(request, st, user, project_id, payload)
daily = payload.get("repeat_daily", False) # 추가 칸 날짜 팝업 [매일](033) — 만든 뒤 켠다(마감일은 비움)
if not isinstance(daily, bool):
raise HTTPException(status_code=400, detail="매일 반복 값이 올바르지 않습니다.")
try: try:
task = st.create_task(**_task_create_fields(user, project_id, payload)) task = st.create_task(**_task_create_fields(user, project_id, payload))
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) raise HTTPException(status_code=400, detail=str(exc))
except KeyError as exc: except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) raise HTTPException(status_code=404, detail=str(exc))
if daily:
try:
task = st.update_task(task_id=task["id"], fields={"repeat_daily": True}, actor=user["email"])
except UndefinedColumn:
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
task.pop("_newly_assigned", None)
task.pop("_newly_completed", None)
return task, _task_created_effects(request, st, user, project, task, followers, bg) return task, _task_created_effects(request, st, user, project, task, followers, bg)
@@ -1673,6 +1688,8 @@ def api_update_task(
try: try:
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"], task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
assignee_allowed=_registered_project_user) assignee_allowed=_registered_project_user)
except UndefinedColumn:
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
except ValueError as exc: except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) raise HTTPException(status_code=400, detail=str(exc))
except KeyError: except KeyError:
@@ -2813,7 +2830,7 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
return out return out
_ALERT_TYPES = ("mention", "assigned") _ALERT_TYPES = ("mention", "assigned", "daily") # daily = 매일 하는 업무(reminders.run_daily_alerts, 033)
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것) _ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
_ALERT_PAGE = 200 _ALERT_PAGE = 200
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게 _ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
@@ -2963,7 +2980,7 @@ def notifier_page(request: Request) -> Any:
"project/notifier.html", "project/notifier.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin), "nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st), "goal_years": _goal_years_nav(st),
@@ -3114,7 +3131,7 @@ def trash_page(request: Request) -> HTMLResponse:
"project/trash.html", "project/trash.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, True), "nav_projects": _nav_projects(st, user, True),
"goal_years": _goal_years_nav(st), "goal_years": _goal_years_nav(st),
@@ -3191,7 +3208,7 @@ def help_page(request: Request) -> HTMLResponse:
"project/help.html", "project/help.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"page_title": "프로젝트 관리 도움말", "page_title": "프로젝트 관리 도움말",
"page_subtitle": "처음 쓰는 분을 위한 기능 안내", "page_subtitle": "처음 쓰는 분을 위한 기능 안내",
@@ -3240,7 +3257,7 @@ def inbox_page(request: Request) -> HTMLResponse:
"project/inbox.html", "project/inbox.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"nav_projects": nav_projects, "nav_projects": nav_projects,
"goal_years": _goal_years_nav(st), "goal_years": _goal_years_nav(st),
@@ -3450,7 +3467,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
"project/goals.html", "project/goals.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin), "nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st), "goal_years": _goal_years_nav(st),
@@ -4001,7 +4018,7 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
"project/goal_meeting.html", "project/goal_meeting.html",
{ {
"user": user, "user": user,
**_role_ctx(user), **_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"), "nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin), "nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st), "goal_years": _goal_years_nav(st),
+51
View File
@@ -383,7 +383,41 @@ PROJECT_VIEWS: tuple[str, ...] = ("board", "list", "calendar", "timeline", "dash
PROJECT_OPTION_DEFAULTS: dict[str, Any] = { PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭 "default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지) "board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
"all_view_users": None, # 왼쪽 "전체 보기" 메뉴를 볼 사람(이메일 목록) — None = 예전처럼 Pro user 이상
"daily_alert_times": ["09:00"], # 매일 업무(033 repeat_daily) 알림 시각들(KST, 영업일)
} }
ALL_VIEW_USERS_MAX = 2000
DAILY_ALERT_TIMES_MAX = 12
def _time_list(raw: Any) -> list[str] | None:
"""'HH:MM' 목록 → 정규화·중복 제거·정렬. 목록이 아니거나 잘못된 시각이 끼면 None(빈 목록 = 알림 끔)."""
if not isinstance(raw, list) or len(raw) > DAILY_ALERT_TIMES_MAX:
return None
out: set[str] = set()
for t in raw:
if not isinstance(t, str):
return None
try:
v = validate_time(t)
except ValueError:
return None
if v is None:
return None
out.add(v)
return sorted(out)
def _email_list(raw: Any) -> list[str] | None:
"""이메일 목록 → 소문자·중복 제거·정렬. 목록이 아니거나 이상한 값이 끼면 None."""
if not isinstance(raw, list) or len(raw) > ALL_VIEW_USERS_MAX:
return None
out: set[str] = set()
for e in raw:
if not isinstance(e, str) or "@" not in e or len(e) > 254:
return None
out.add(e.strip().lower())
return sorted(out)
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]: def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
@@ -394,6 +428,13 @@ def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
out["default_view"] = raw["default_view"] out["default_view"] = raw["default_view"]
if isinstance(raw.get("board_cover"), bool): if isinstance(raw.get("board_cover"), bool):
out["board_cover"] = raw["board_cover"] out["board_cover"] = raw["board_cover"]
if raw.get("all_view_users") is not None:
out["all_view_users"] = _email_list(raw["all_view_users"])
times = _time_list(raw.get("daily_alert_times"))
if times is not None:
out["daily_alert_times"] = times
else:
out["daily_alert_times"] = list(PROJECT_OPTION_DEFAULTS["daily_alert_times"])
return out return out
@@ -413,6 +454,16 @@ def validate_project_options(payload: Any) -> dict[str, Any]:
if not isinstance(payload["board_cover"], bool): if not isinstance(payload["board_cover"], bool):
raise ValueError("카드 표지 값이 올바르지 않습니다.") raise ValueError("카드 표지 값이 올바르지 않습니다.")
out["board_cover"] = payload["board_cover"] out["board_cover"] = payload["board_cover"]
if "all_view_users" in payload:
v = payload["all_view_users"]
out["all_view_users"] = None if v is None else _email_list(v)
if v is not None and out["all_view_users"] is None:
raise ValueError("전체 보기 대상자 값이 올바르지 않습니다.")
if "daily_alert_times" in payload:
times = _time_list(payload["daily_alert_times"])
if times is None:
raise ValueError(f"매일 업무 알림 시각이 올바르지 않습니다(HH:MM, 최대 {DAILY_ALERT_TIMES_MAX}개).")
out["daily_alert_times"] = times
return out return out
@@ -1,8 +1,9 @@
{# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다. {# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다.
· 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원). · 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원).
· 프로젝트 화면(처음 여는 탭)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에 · 프로젝트 화면(처음 여는 탭·"전체 보기" 메뉴 대상자)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view· 저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view·
data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영. data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영.
· 알림(매일 하는 업무 알림 시각 여러 개) — 수퍼관리자·Admin, 모든 사용자.
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #} · 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션"> <button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
<span class="material-symbols-outlined">settings</span> <span class="material-symbols-outlined">settings</span>
@@ -24,6 +25,8 @@
<span class="material-symbols-outlined">space_dashboard</span>프로젝트 화면</button> <span class="material-symbols-outlined">space_dashboard</span>프로젝트 화면</button>
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-board" id="pj-opt-tab-board" data-pane="board" tabindex="-1"> <button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-board" id="pj-opt-tab-board" data-pane="board" tabindex="-1">
<span class="material-symbols-outlined">view_kanban</span>보드</button> <span class="material-symbols-outlined">view_kanban</span>보드</button>
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-alert" id="pj-opt-tab-alert" data-pane="alert" tabindex="-1">
<span class="material-symbols-outlined">notifications</span>알림</button>
{% endif %} {% endif %}
{% if user and user.is_super_admin %} {% if user and user.is_super_admin %}
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-admin" id="pj-opt-tab-admin" data-pane="admin" tabindex="-1"> <button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-admin" id="pj-opt-tab-admin" data-pane="admin" tabindex="-1">
@@ -62,7 +65,16 @@
<label><input type="radio" name="default_view" value="timeline"><span class="material-symbols-outlined">view_timeline</span>타임라인</label> <label><input type="radio" name="default_view" value="timeline"><span class="material-symbols-outlined">view_timeline</span>타임라인</label>
<label><input type="radio" name="default_view" value="dashboard"><span class="material-symbols-outlined">monitoring</span>대시보드</label> <label><input type="radio" name="default_view" value="dashboard"><span class="material-symbols-outlined">monitoring</span>대시보드</label>
</div> </div>
<small class="pj-options-note">왼쪽 "전체 보기"는 지금처럼 대시보드로 열립니다.</small> </div>
{# 전체 보기 대상자(2026-11-11) — 체크한 사람에게만 왼쪽 "전체 보기" 메뉴가 보인다. 설정 전(all_view_users=null)이면
Pro user 이상이 체크된 채로 열린다. 후보 = project 권한 보유자(GET /project/api/assignable-users). #}
<div class="pj-options-row is-stack">
<div class="pj-options-allview-head">
<span class="pj-options-label" id="pj-options-allview-label"><b>"전체 보기" 메뉴를 볼 사람</b><small>체크한 사람에게만 왼쪽 "전체 보기"가 보입니다(멤버인 프로젝트만 모아 봄, 대시보드로 열림)</small></span>
<button type="button" class="pj-btn pj-options-allview-all" id="pj-options-allview-all">전체 선택</button>
</div>
<div class="pj-member-picker pj-options-allview" id="pj-options-allview" role="group" aria-labelledby="pj-options-allview-label"></div>
<small class="pj-options-note" id="pj-options-allview-count"></small>
</div> </div>
</div> </div>
</section> </section>
@@ -76,6 +88,18 @@
</label> </label>
</div> </div>
</section> </section>
{# 알림(2026-11-11) — 매일 하는 업무(033 repeat_daily) 알림 시각 여러 개(daily_alert_times, 영업일, 서버 reminders.py). #}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-alert" aria-labelledby="pj-opt-tab-alert" data-pane="alert" hidden>
<h3>알림 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
<div class="pj-options-group">
<div class="pj-options-row is-stack">
<span class="pj-options-label" id="pj-options-daily-label"><b>매일 하는 업무 알림 시각</b><small>날짜 팝업에서 [매일]로 정한 업무를 이 시각마다 담당자(없으면 협업자)에게 알립니다 — 평일(공휴일 제외)</small></span>
<ol class="pj-options-times" id="pj-options-daily-times" aria-labelledby="pj-options-daily-label"></ol>
<div><button type="button" class="pj-btn" id="pj-options-daily-add"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">add</span> 알림 추가</button></div>
<small class="pj-options-note">알림이 하나도 없으면 매일 업무 알림을 보내지 않습니다.</small>
</div>
</div>
</section>
{% endif %} {% endif %}
{% if user and user.is_super_admin %} {% if user and user.is_super_admin %}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-admin" aria-labelledby="pj-opt-tab-admin" data-pane="admin" hidden> <section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-admin" aria-labelledby="pj-opt-tab-admin" data-pane="admin" hidden>
@@ -105,4 +129,4 @@
document.documentElement.dataset.pjFont = pf; document.documentElement.dataset.pjFont = pf;
} catch (_) {} } catch (_) {}
</script> </script>
<script src="/static/project-options.js?v=20261016c" defer></script> <script src="/static/project-options.js?v=20261111e" defer></script>
@@ -10,7 +10,8 @@
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시 side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함) goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
goal_year_active 목표 화면에서 보고 있는 연도 goal_year_active 목표 화면에서 보고 있는 연도
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가 pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·휴지통·전체 멤버·연도 추가
pj_all_view "전체 보기" 메뉴 — Project 옵션 대상자(설정 전이면 Pro user 이상, router._role_ctx)
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만) pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림), 목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #} 새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
@@ -39,9 +40,9 @@
<span class="pj-side-navbadge" id="pj-mention-badge" <span class="pj-side-navbadge" id="pj-mention-badge"
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span> {% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
</a> </a>
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트) {# 전체 보기(2026-10-08 — 멤버인 프로젝트 범위, 2026-11-11 부터 볼 사람은 Project 옵션 "프로젝트 화면" 대상자) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #} 화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
{% if pj_pro %} {% if pj_all_view %}
{% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %} {% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %}
{% if _all_pid %} {% if _all_pid %}
<a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all"> <a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all">
@@ -1,7 +1,7 @@
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %} {% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -289,5 +289,5 @@
<script src="/static/project-goal-text.js?v=20261026a" defer></script> <script src="/static/project-goal-text.js?v=20261026a" defer></script>
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script> <script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -207,5 +207,5 @@
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261026a" defer></script> <script src="/static/project-goal-text.js?v=20261026a" defer></script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" /> <link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -96,7 +96,7 @@
<h2><span class="pjh-num">2</span>화면 구성</h2> <h2><span class="pjh-num">2</span>화면 구성</h2>
<div class="pjh-map" aria-hidden="true"> <div class="pjh-map" aria-hidden="true">
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div> <div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div> <div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(옵션에서 고른 사람) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div> <div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div>
</div> </div>
<h3>왼쪽 사이드바</h3> <h3>왼쪽 사이드바</h3>
@@ -118,10 +118,11 @@
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li> <li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다. <li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다. <b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다. 아래 프로젝트 화면·보드·알림 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다. 분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다. <b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). <b>"전체 보기" 메뉴를 볼 사람</b> — 직원 아이콘을 체크한 사람에게만 왼쪽 "전체 보기"가 보입니다([전체 선택]으로 한 번에, 처음엔 Pro user 이상이 체크돼 있음). "전체 보기"는 늘 대시보드로 열립니다.
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영). <b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
<b>알림</b>: 매일 하는 업무 알림 시각 — <span class="pjh-ui">알림 추가</span>로 여러 개, 시각은 각각 정하고 휴지통 아이콘으로 뺍니다(처음엔 오전 9시 하나, 모두 빼면 매일 업무 알림 없음).
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li> <span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
</ul> </ul>
<h3>프로젝트 제목</h3> <h3>프로젝트 제목</h3>
@@ -151,7 +152,7 @@
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr> <tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr> <tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr> <tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr> <tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td colspan="3">Project 옵션 → 프로젝트 화면에서 고른 사람(처음엔 Pro user 이상, 멤버인 프로젝트 범위)</td></tr>
<tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr> <tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr> <tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr> <tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
@@ -230,7 +231,7 @@
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr> <tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
</table> </table>
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3> <h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다 <p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Project 옵션에서 고른 사람(처음엔 Pro user 이상)은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만). (왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다. 전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p> 다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
@@ -291,6 +292,7 @@
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr> <tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr> <tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr> <tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
<tr><td style="color:#b07a00"><span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일</td><td><b>매일 하는 업무</b> — 마감일 없이 매일 해야 하는 업무. 날짜 창 아래 <span class="pjh-ui">매일</span>을 누르면 정해지고(다시 누르거나 날짜를 고르면 풀림), 정한 시각마다 알림이 갑니다(17장).</td></tr>
</table> </table>
</section> </section>
@@ -524,6 +526,7 @@
<tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr> <tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr> <tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr> <tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr>
<tr><td>매일 업무</td><td>담당자(없으면 협업자). <b>매일 하는 업무</b>(마감일 칸 <span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일)가 끝나지 않았으면 평일(공휴일 제외) Project 옵션 → 알림에서 정한 시각마다 화면 아래 큰 알림에 <b>노란 줄</b>로 뜹니다(PC 알림 프로그램도).</td></tr>
</table> </table>
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p> <p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
</section> </section>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -106,5 +106,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }} "today": {{ today | tojson }}
} }
</script> </script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -108,5 +108,5 @@
}); });
})(); })();
</script> </script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host --> <!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host --> <!-- 타임라인 vis-timeline — self-host -->
@@ -27,7 +27,7 @@
<div class="pj-wrap pj-project-view" <div class="pj-wrap pj-project-view"
data-project-id="{{ project.id }}" data-project-id="{{ project.id }}"
data-can-manage="{{ 'true' if can_manage else 'false' }}" data-can-manage="{{ 'true' if can_manage else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}" data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-all-view="{{ 'true' if pj_all_view else 'false' }}" data-daily-ready="{{ '1' if pj_daily_ready else '' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}" data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
data-default-view="{{ pj_options.default_view if pj_options else 'board' }}" data-default-view="{{ pj_options.default_view if pj_options else 'board' }}"
data-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}" data-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}"
@@ -476,5 +476,5 @@
</script> </script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script> <script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %} {% extends "erp_base.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" /> <link rel="stylesheet" href="/static/project.css?v=20261111f" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" /> <link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %} {% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %} {% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %} {% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261030b" defer></script> <script src="/static/project.js?v=20261111d" defer></script>
{% endblock %} {% endblock %}
+107 -29
View File
@@ -149,10 +149,16 @@
return out + "</select>"; return out + "</select>";
} }
// 품목 토글 — [켜짐, 꺼짐] 표기
var FLAG_LABELS = {
display: ["진열", "미진열"], selling: ["판매", "중지"],
use_inventory: ["사용", "미사용"], display_soldout: ["표시", "안함"]
};
var FLAGS = Object.keys(FLAG_LABELS);
function toggleBtn(flag, on) { function toggleBtn(flag, on) {
var label = flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지");
return '<button type="button" class="cf24-v-toggle' + (on ? " is-on" : "") + '" data-flag="' + flag + return '<button type="button" class="cf24-v-toggle' + (on ? " is-on" : "") + '" data-flag="' + flag +
'" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + label + "</button>"; '" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + FLAG_LABELS[flag][on ? 0 : 1] + "</button>";
} }
function paintToggle(btn, on, resetInitial) { function paintToggle(btn, on, resetInitial) {
@@ -160,7 +166,25 @@
if (resetInitial) btn.dataset.initial = btn.dataset.on; if (resetInitial) btn.dataset.initial = btn.dataset.on;
btn.classList.toggle("is-on", on); btn.classList.toggle("is-on", on);
btn.classList.toggle("is-dirty", btn.dataset.on !== btn.dataset.initial); btn.classList.toggle("is-dirty", btn.dataset.on !== btn.dataset.initial);
btn.textContent = btn.dataset.flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지"); btn.textContent = FLAG_LABELS[btn.dataset.flag][on ? 0 : 1];
}
// 재고관리 · 재고 수량 · 품절표시 칸 (진열·판매 다음)
var INVENTORY_TH = '<th class="cf24-v-flag">재고관리</th><th class="cf24-v-qty">재고</th><th class="cf24-v-flag">품절표시</th>';
function inventoryCells(variant) {
var qty = variant && variant.quantity != null ? String(variant.quantity) : "0";
return '<td class="cf24-v-flag">' + toggleBtn("use_inventory", !!(variant && variant.use_inventory)) + "</td>" +
'<td class="cf24-v-qty"><input type="text" name="quantity" inputmode="numeric" value="' + esc(qty) + '" /></td>' +
'<td class="cf24-v-flag">' + toggleBtn("display_soldout", !!(variant && variant.display_soldout)) + "</td>";
}
// 행의 품목 입력 요소들 — 저장 패치(variantPatch/newRowPatch)용
function variantFields(tr, into) {
into.custom = tr.querySelector('[name="custom_variant_code"]');
into.amount = tr.querySelector('[name="additional_amount"]');
into.quantity = tr.querySelector('[name="quantity"]');
FLAGS.forEach(function (flag) { into[flag] = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]'); });
return into;
} }
function bindToggles(container) { function bindToggles(container) {
@@ -309,6 +333,48 @@
function amountPlain(v) { return String(parseInt(String(v || "0").replace(/,/g, ""), 10) || 0); } function amountPlain(v) { return String(parseInt(String(v || "0").replace(/,/g, ""), 10) || 0); }
function norm(s) { return String(s || "").replace(/\s+/g, "").toLowerCase(); } function norm(s) { return String(s || "").replace(/\s+/g, "").toLowerCase(); }
// 판매 가격 칸 = 기본 정보 판매가 + 추가금액. 화면 계산용이고 저장되는 값은 추가금액뿐이다.
function basePrice() {
var el = root.querySelector('#cf24-basic-form [name="price"]');
return parseInt(amountPlain(el && el.value), 10);
}
function salePrice(amount) { return String(basePrice() + parseInt(amountPlain(amount), 10)); }
function salePriceCell(amount) {
return '<td class="cf24-v-amount"><input type="text" class="cf24-sale-price" inputmode="numeric" value="' + salePrice(amount) + '" /></td>';
}
function bindSalePrice(tbody) {
// capture: 불러오기·입력 복원이 보내는 input 이벤트는 버블링하지 않는다.
tbody.addEventListener("input", function (e) {
var tr = e.target.closest("tr");
var sale = tr.querySelector(".cf24-sale-price");
var amount = tr.querySelector('[name="additional_amount"]');
if (e.target === sale) {
sale.value = sale.value.replace(/\D/g, "");
amount.value = sale.value ? String(parseInt(sale.value, 10) - basePrice()) : "0";
amount.dispatchEvent(new Event("input")); // 변경 표시
} else if (e.target === amount && document.activeElement !== sale) {
sale.value = salePrice(amount.value);
}
}, true);
tbody.addEventListener("focusout", function (e) {
if (!e.target.classList.contains("cf24-sale-price")) return;
e.target.value = salePrice(e.target.closest("tr").querySelector('[name="additional_amount"]').value);
});
tbody.addEventListener("keydown", function (e) {
// isComposing: 한글 조합 중 Enter 는 글자 확정용이다 — 여기서 옮기면 글자가 깨지거나 두 칸 내려간다.
if (e.isComposing || !e.target.matches('[name="option_text"], [name="custom_variant_code"], [name="additional_amount"], .cf24-sale-price, [name="quantity"]')) return;
var down = e.key === "Enter" || e.key === "ArrowDown";
if (!down && e.key !== "ArrowUp") return;
e.preventDefault();
var tr = e.target.closest("tr")[down ? "nextElementSibling" : "previousElementSibling"];
if (!tr) return;
var next = tr.cells[e.target.closest("td").cellIndex].querySelector('input[type="text"]');
next.focus();
next.select();
});
}
/* ═══════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════
화면 분기 화면 분기
═══════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════ */
@@ -380,8 +446,10 @@
: '<span class="cf24-muted">저장 시 부여</span>') + "</td>" + : '<span class="cf24-muted">저장 시 부여</span>') + "</td>" +
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(variant ? variant.custom_variant_code : "") + '" /></td>' + '<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(variant ? variant.custom_variant_code : "") + '" /></td>' +
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(variant ? variant.additional_amount : "0")) + '" /></td>' + '<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(variant ? variant.additional_amount : "0")) + '" /></td>' +
salePriceCell(variant ? variant.additional_amount : "0") +
'<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" + '<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" +
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" + '<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" +
inventoryCells(variant) +
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" + '<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
"</tr>"; "</tr>";
} }
@@ -406,7 +474,7 @@
"</div>" + "</div>" +
'<div class="cf24-u-tablewrap"><table class="cf24-variants cf24-u-table"><thead><tr>' + '<div class="cf24-u-tablewrap"><table class="cf24-variants cf24-u-table"><thead><tr>' +
'<th class="cf24-u-drag"></th><th class="cf24-u-thumb">썸네일</th><th>옵션값 이름</th><th class="cf24-v-syscode">품목코드</th>' + '<th class="cf24-u-drag"></th><th class="cf24-u-thumb">썸네일</th><th>옵션값 이름</th><th class="cf24-v-syscode">품목코드</th>' +
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th>' + '<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th>' +
"</tr></thead><tbody id=\"cf24-u-body\">"; "</tr></thead><tbody id=\"cf24-u-body\">";
rows.forEach(function (r, i) { html += rowHtml(r, canDrag, i); }); rows.forEach(function (r, i) { html += rowHtml(r, canDrag, i); });
if (isNew) html += rowHtml({ index: null, value: null, variant: null }, true, null); if (isNew) html += rowHtml({ index: null, value: null, variant: null }, true, null);
@@ -436,6 +504,7 @@
var tbody = body.querySelector("#cf24-u-body"); var tbody = body.querySelector("#cf24-u-body");
var msg = body.querySelector("#cf24-u-msg"); var msg = body.querySelector("#cf24-u-msg");
trackDirty(wrap); trackDirty(wrap);
bindSalePrice(tbody);
bindToggles(tbody); bindToggles(tbody);
bindCopy(tbody); bindCopy(tbody);
bindThumbUploads(tbody, msg); bindThumbUploads(tbody, msg);
@@ -525,8 +594,8 @@
link: tr.querySelector('[name="option_link_image"]').value, link: tr.querySelector('[name="option_link_image"]').value,
custom: tr.querySelector('[name="custom_variant_code"]').value, custom: tr.querySelector('[name="custom_variant_code"]').value,
amount: tr.querySelector('[name="additional_amount"]').value, amount: tr.querySelector('[name="additional_amount"]').value,
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]').dataset.on, quantity: tr.querySelector('[name="quantity"]').value,
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]').dataset.on flags: FLAGS.map(function (flag) { return tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]').dataset.on; })
}; };
}); });
} }
@@ -554,11 +623,12 @@
set('[name="option_text"]', k.text); set('[name="option_text"]', k.text);
set('[name="custom_variant_code"]', k.custom); set('[name="custom_variant_code"]', k.custom);
set('[name="additional_amount"]', k.amount); set('[name="additional_amount"]', k.amount);
set('[name="quantity"]', k.quantity);
if (k.image) { tr.querySelector('[name="option_image_file"]').value = k.image; } if (k.image) { tr.querySelector('[name="option_image_file"]').value = k.image; }
if (k.link) { tr.querySelector('[name="option_link_image"]').value = k.link; } if (k.link) { tr.querySelector('[name="option_link_image"]').value = k.link; }
["display", "selling"].forEach(function (flag) { FLAGS.forEach(function (flag, i) {
var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]'); var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]');
if (btn && btn.dataset.on !== k[flag]) paintToggle(btn, k[flag] === "1", false); if (btn && btn.dataset.on !== k.flags[i]) paintToggle(btn, k.flags[i] === "1", false);
}); });
}); });
} }
@@ -722,7 +792,7 @@
/* ── 저장 (통합) ── */ /* ── 저장 (통합) ── */
function collectUnified(tbody) { function collectUnified(tbody) {
return Array.prototype.map.call(tbody.children, function (tr, i) { return Array.prototype.map.call(tbody.children, function (tr, i) {
return { return variantFields(tr, {
tr: tr, tr: tr,
position: i, position: i,
isNew: tr.classList.contains("is-new"), isNew: tr.classList.contains("is-new"),
@@ -730,12 +800,8 @@
code: tr.dataset.code || "", code: tr.dataset.code || "",
text: tr.querySelector('[name="option_text"]').value.trim(), text: tr.querySelector('[name="option_text"]').value.trim(),
image: tr.querySelector('[name="option_image_file"]').value, image: tr.querySelector('[name="option_image_file"]').value,
link: tr.querySelector('[name="option_link_image"]').value, link: tr.querySelector('[name="option_link_image"]').value
custom: tr.querySelector('[name="custom_variant_code"]'), });
amount: tr.querySelector('[name="additional_amount"]'),
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'),
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]')
};
}); });
} }
@@ -757,20 +823,25 @@
var any = false; var any = false;
if (r.custom.value !== r.custom.defaultValue) { patch.custom_variant_code = r.custom.value.trim(); any = true; } if (r.custom.value !== r.custom.defaultValue) { patch.custom_variant_code = r.custom.value.trim(); any = true; }
if (r.amount.value !== r.amount.defaultValue) { patch.additional_amount = r.amount.value.trim() || "0"; any = true; } if (r.amount.value !== r.amount.defaultValue) { patch.additional_amount = r.amount.value.trim() || "0"; any = true; }
if (r.display.dataset.on !== r.display.dataset.initial) { patch.display = r.display.dataset.on === "1" ? "on" : "off"; any = true; } if (r.quantity.value !== r.quantity.defaultValue) { patch.quantity = r.quantity.value.trim() || "0"; any = true; }
if (r.selling.dataset.on !== r.selling.dataset.initial) { patch.selling = r.selling.dataset.on === "1" ? "on" : "off"; any = true; } FLAGS.forEach(function (flag) {
if (r[flag].dataset.on !== r[flag].dataset.initial) { patch[flag] = r[flag].dataset.on === "1" ? "on" : "off"; any = true; }
});
if (withOrder) { patch.display_order = r.position + 1; any = true; } if (withOrder) { patch.display_order = r.position + 1; any = true; }
return any ? patch : null; return any ? patch : null;
} }
// 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매)과 다른 것만 // 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매·재고관리 미사용·재고 0·품절표시 안함)과 다른 것만
function newRowPatch(r, code) { function newRowPatch(r, code) {
var p = { variant_code: code }; var p = { variant_code: code };
var any = false; var any = false;
if (r.custom.value.trim()) { p.custom_variant_code = r.custom.value.trim(); any = true; } if (r.custom.value.trim()) { p.custom_variant_code = r.custom.value.trim(); any = true; }
if (amountPlain(r.amount.value) !== "0") { p.additional_amount = r.amount.value.trim(); any = true; } if (amountPlain(r.amount.value) !== "0") { p.additional_amount = r.amount.value.trim(); any = true; }
if (r.display.dataset.on !== "1") { p.display = "off"; any = true; } if (amountPlain(r.quantity.value) !== "0") { p.quantity = r.quantity.value.trim(); any = true; }
if (r.selling.dataset.on !== "1") { p.selling = "off"; any = true; } FLAGS.forEach(function (flag) {
var defaultOn = flag === "display" || flag === "selling";
if ((r[flag].dataset.on === "1") !== defaultOn) { p[flag] = defaultOn ? "off" : "on"; any = true; }
});
return any ? p : null; return any ? p : null;
} }
@@ -822,7 +893,7 @@
var lines = []; var lines = [];
if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식"); if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식");
if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매" + (orderChanged ? "·순서" : "") + ")"); if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매·재고" + (orderChanged ? "·순서" : "") + ")");
window.erpConfirm("카페24에 바로 반영합니다. 계속할까요?\n\n- " + lines.join("\n- ")).then(function (ok) { window.erpConfirm("카페24에 바로 반영합니다. 계속할까요?\n\n- " + lines.join("\n- ")).then(function (ok) {
if (!ok) return; if (!ok) return;
saveBtn.disabled = true; saveBtn.disabled = true;
@@ -844,10 +915,15 @@
setMsg(msg, "품목 " + patches.length + "건 반영 중…", ""); setMsg(msg, "품목 " + patches.length + "건 반영 중…", "");
return apiJson("PUT", "/cafe24/products/" + no + "/variants", { rows: patches }); return apiJson("PUT", "/cafe24/products/" + no + "/variants", { rows: patches });
}); });
var shopWarn = "";
chain chain
.then(function () { return load(); }) .then(function (data) {
var bad = Object.keys((data && data.shop_failed) || {});
if (bad.length) shopWarn = " 단, 다른 쇼핑몰(" + bad.join(", ") + "번) 진열/판매 반영 실패: " + data.shop_failed[bad[0]];
return load();
})
.then(function () { .then(function () {
setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다.", "is-ok"); setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다." + shopWarn, shopWarn ? "is-err" : "is-ok");
}) })
.catch(function (err) { .catch(function (err) {
setMsg(msg, "실패: " + err.message + " — 화면을 다시 불러옵니다.", "is-err"); setMsg(msg, "실패: " + err.message + " — 화면을 다시 불러옵니다.", "is-err");
@@ -964,7 +1040,7 @@
html += '<p class="cf24-muted">품목이 아직 조회되지 않았습니다. 잠시 뒤 창을 닫았다 다시 여세요.</p>'; html += '<p class="cf24-muted">품목이 아직 조회되지 않았습니다. 잠시 뒤 창을 닫았다 다시 여세요.</p>';
} else { } else {
html += '<div class="cf24-variants-wrap"><table class="cf24-variants"><thead><tr><th class="cf24-v-imgcol"></th><th>옵션</th><th class="cf24-v-syscode">품목코드</th>' + html += '<div class="cf24-variants-wrap"><table class="cf24-variants"><thead><tr><th class="cf24-v-imgcol"></th><th>옵션</th><th class="cf24-v-syscode">품목코드</th>' +
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th></tr></thead><tbody>'; '<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th></tr></thead><tbody>';
variants.forEach(function (v) { variants.forEach(function (v) {
var label = v.options.map(function (o) { return o.value; }).join(" / ") || v.variant_code; var label = v.options.map(function (o) { return o.value; }).join(" / ") || v.variant_code;
html += '<tr class="cf24-v-item" data-code="' + esc(v.variant_code) + '">' + html += '<tr class="cf24-v-item" data-code="' + esc(v.variant_code) + '">' +
@@ -973,7 +1049,9 @@
'<td class="cf24-v-syscode"><button type="button" class="cf24-v-copy" data-copy-text="' + esc(v.variant_code) + '">' + esc(v.variant_code) + "</button></td>" + '<td class="cf24-v-syscode"><button type="button" class="cf24-v-copy" data-copy-text="' + esc(v.variant_code) + '">' + esc(v.variant_code) + "</button></td>" +
'<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(v.custom_variant_code) + '" /></td>' + '<td class="cf24-v-code"><input type="text" name="custom_variant_code" maxlength="40" value="' + esc(v.custom_variant_code) + '" /></td>' +
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(v.additional_amount)) + '" /></td>' + '<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(v.additional_amount)) + '" /></td>' +
salePriceCell(v.additional_amount) +
'<td class="cf24-v-flag">' + toggleBtn("display", !!v.display) + "</td><td class=\"cf24-v-flag\">" + toggleBtn("selling", !!v.selling) + "</td>" + '<td class="cf24-v-flag">' + toggleBtn("display", !!v.display) + "</td><td class=\"cf24-v-flag\">" + toggleBtn("selling", !!v.selling) + "</td>" +
inventoryCells(v) +
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" data-code="' + esc(v.variant_code) + '" title="품목 삭제 (카페24에 바로 반영)">✕</button></td></tr>'; '<td class="cf24-u-del"><button type="button" class="cf24-u-remove" data-code="' + esc(v.variant_code) + '" title="품목 삭제 (카페24에 바로 반영)">✕</button></td></tr>';
}); });
html += "</tbody></table></div><div class=\"cf24-side-actions\" style=\"margin-top:8px;\"><span class=\"cf24-muted\" id=\"cf24-var-msg\"></span>" + html += "</tbody></table></div><div class=\"cf24-side-actions\" style=\"margin-top:8px;\"><span class=\"cf24-muted\" id=\"cf24-var-msg\"></span>" +
@@ -990,6 +1068,7 @@
var wrap = body.querySelector(".cf24-variants-wrap"); var wrap = body.querySelector(".cf24-variants-wrap");
if (wrap) { if (wrap) {
trackDirty(wrap); trackDirty(wrap);
bindSalePrice(wrap.querySelector("tbody"));
bindToggles(wrap); bindToggles(wrap);
bindCopy(wrap); bindCopy(wrap);
body.querySelector("#cf24-var-save").addEventListener("click", function () { saveMultiVariants(wrap); }); body.querySelector("#cf24-var-save").addEventListener("click", function () { saveMultiVariants(wrap); });
@@ -1055,9 +1134,7 @@
var saveBtn = body.querySelector("#cf24-var-save"); var saveBtn = body.querySelector("#cf24-var-save");
var rows = []; var rows = [];
wrap.querySelectorAll("tr[data-code]").forEach(function (tr) { wrap.querySelectorAll("tr[data-code]").forEach(function (tr) {
var r = { code: tr.dataset.code, custom: tr.querySelector('[name="custom_variant_code"]'), amount: tr.querySelector('[name="additional_amount"]'), var p = variantPatch(variantFields(tr, { code: tr.dataset.code }), false);
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'), selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]') };
var p = variantPatch(r, false);
if (p) rows.push(p); if (p) rows.push(p);
}); });
if (!rows.length) { setMsg(msg, "바뀐 품목이 없습니다.", ""); return; } if (!rows.length) { setMsg(msg, "바뀐 품목이 없습니다.", ""); return; }
@@ -1074,6 +1151,7 @@
if (!tr) return; if (!tr) return;
if (u.custom_variant_code !== undefined) tr.querySelector('[name="custom_variant_code"]').value = u.custom_variant_code; if (u.custom_variant_code !== undefined) tr.querySelector('[name="custom_variant_code"]').value = u.custom_variant_code;
if (u.additional_amount !== undefined) tr.querySelector('[name="additional_amount"]').value = amountPlain(u.additional_amount); if (u.additional_amount !== undefined) tr.querySelector('[name="additional_amount"]').value = amountPlain(u.additional_amount);
if (u.quantity != null) tr.querySelector('[name="quantity"]').value = String(u.quantity);
tr.querySelectorAll(".cf24-v-toggle").forEach(function (btn) { tr.querySelectorAll(".cf24-v-toggle").forEach(function (btn) {
if (u[btn.dataset.flag] !== undefined) paintToggle(btn, !!u[btn.dataset.flag], true); if (u[btn.dataset.flag] !== undefined) paintToggle(btn, !!u[btn.dataset.flag], true);
}); });
@@ -1081,8 +1159,8 @@
if (v.variant_code !== code) return; if (v.variant_code !== code) return;
if (u.custom_variant_code !== undefined) v.custom_variant_code = u.custom_variant_code; if (u.custom_variant_code !== undefined) v.custom_variant_code = u.custom_variant_code;
if (u.additional_amount !== undefined) v.additional_amount = u.additional_amount; if (u.additional_amount !== undefined) v.additional_amount = u.additional_amount;
if (u.display !== undefined) v.display = !!u.display; if (u.quantity != null) v.quantity = u.quantity;
if (u.selling !== undefined) v.selling = !!u.selling; FLAGS.forEach(function (flag) { if (u[flag] !== undefined) v[flag] = !!u[flag]; });
}); });
}); });
commitValues(wrap); commitValues(wrap);
+33 -5
View File
@@ -17,6 +17,7 @@
.erp-page { .erp-page {
max-width: none; max-width: none;
box-sizing: border-box; box-sizing: border-box;
padding-top: 10px; /* 상단 탭 위 여백 — 아래 여백은 _nav.html 의 margin-bottom 과 같은 10px */
} }
.cf24-card { .cf24-card {
@@ -123,12 +124,14 @@
.cf24-list-table tbody td { .cf24-list-table tbody td {
padding: 6px 4px; padding: 6px 4px;
vertical-align: top; vertical-align: middle;
} }
/* 목록 폭 550px 기준. 고정폭을 뺀 나머지(약 290px)가 상품명 몫이다. /* 목록 폭 550px 기준. 고정폭을 뺀 나머지(약 290px)가 상품명 몫이다.
진열/판매 칸은 제목(2글자) + 정렬 화살표가 들어갈 만큼만. */ 진열/판매 칸은 제목(2글자) + 정렬 화살표가 들어갈 만큼만. */
.cf24-col-no { width: 40px; text-align: right; color: var(--color-midtone-gray, #737373); } .cf24-col-no { width: 40px; text-align: right; color: var(--color-midtone-gray, #737373); }
.cf24-col-thumb { width: 64px; box-sizing: content-box; }
.cf24-thumb { display: block; width: 64px; height: 64px; object-fit: contain; background: var(--color-ghost-gray, #f2f2f2); }
.cf24-col-flag { width: 40px; text-align: center; } .cf24-col-flag { width: 40px; text-align: center; }
.cf24-col-date { width: 78px; white-space: nowrap; color: var(--color-midtone-gray, #737373); } .cf24-col-date { width: 78px; white-space: nowrap; color: var(--color-midtone-gray, #737373); }
.cf24-col-name { word-break: break-word; } .cf24-col-name { word-break: break-word; }
@@ -746,6 +749,27 @@
grid-column: 1 / -1; grid-column: 1 / -1;
} }
/* 예약 대표 이미지 — 칸 제목은 다른 칸과 같게, 파일 고르기는 가로 한 줄 */
.cf24-schedule-image {
display: flex;
flex-direction: column;
gap: 4px;
font-size: var(--text-caption, 12px);
color: var(--color-midtone-gray, #737373);
}
.cf24-schedule-grid label.cf24-file-pick {
flex-direction: row;
}
.cf24-sched-img {
display: block;
width: 48px;
height: 48px;
margin-top: 4px;
object-fit: cover;
border: 1px solid var(--color-border, #e5e5e5);
border-radius: 4px;
}
/* 날짜/시간을 별도 input 으로 나눈다 — datetime-local 은 한국어 로캘에서 /* 날짜/시간을 별도 input 으로 나눈다 — datetime-local 은 한국어 로캘에서
"2026. 08. 14. 오후 07:00" 형태로 길어져 auto-fit minmax(160px, 1fr) 칸에 "2026. 08. 14. 오후 07:00" 형태로 길어져 auto-fit minmax(160px, 1fr) 칸에
잘렸다(실측). 지금은 표시 텍스트를 우리가 직접 그리므로(아래 .cf24-dt-*) 폭을 잘렸다(실측). 지금은 표시 텍스트를 우리가 직접 그리므로(아래 .cf24-dt-*) 폭을
@@ -855,7 +879,8 @@
/* 목록은 320~460px 사이에서 **먼저** 줄어들고(편집기 640px 를 남기는 폭), 편집기가 남는 폭을, 패널은 380px 고정. /* 목록은 320~460px 사이에서 **먼저** 줄어들고(편집기 640px 를 남기는 폭), 편집기가 남는 폭을, 패널은 380px 고정.
minmax(320px, 460px) 였을 때는 목록이 460px 를 먼저 차지해 1440폭(세로 모니터)에서 편집기가 288px 로 눌렸다(2026-10-15). minmax(320px, 460px) 였을 때는 목록이 460px 를 먼저 차지해 1440폭(세로 모니터)에서 편집기가 288px 로 눌렸다(2026-10-15).
1920px: 목록 460 → 편집기 약 850px. 1601px: 목록 320 → 편집기 약 610px. 그보다 좁으면 아래 2분할. */ 1920px: 목록 460 → 편집기 약 850px. 1601px: 목록 320 → 편집기 약 610px. 그보다 좁으면 아래 2분할. */
grid-template-columns: clamp(320px, calc(100% - 380px - 24px - 640px), 460px) minmax(0, 1fr) 380px; /* 대표 이미지 열(64+패딩 8) 만큼 목록 상·하한을 72px 올렸다 — 상품명 칸 폭은 그대로. */
grid-template-columns: clamp(392px, calc(100% - 380px - 24px - 640px), 532px) minmax(0, 1fr) 380px;
} }
/* 2분할(정보 패널을 편집기 아래로) 경계 — 가로 화면은 예전대로 1360px 이하, **세로 화면은 1600px 이하**(2026-10-15). /* 2분할(정보 패널을 편집기 아래로) 경계 — 가로 화면은 예전대로 1360px 이하, **세로 화면은 1600px 이하**(2026-10-15).
@@ -865,7 +890,7 @@
/* 폭이 모자라면 정보 패널을 편집기 아래로 내린다(목록은 그대로 왼쪽). /* 폭이 모자라면 정보 패널을 편집기 아래로 내린다(목록은 그대로 왼쪽).
아래 칸은 높이를 제한해 편집기가 너무 눌리지 않게 한다(패널 안에서 스크롤). */ 아래 칸은 높이를 제한해 편집기가 너무 눌리지 않게 한다(패널 안에서 스크롤). */
.cf24-split.cf24-split-3 { .cf24-split.cf24-split-3 {
grid-template-columns: minmax(300px, 380px) minmax(0, 1fr); grid-template-columns: minmax(372px, 452px) minmax(0, 1fr);
grid-template-areas: "list editor" "list side"; grid-template-areas: "list editor" "list side";
grid-template-rows: minmax(0, 1fr) auto; grid-template-rows: minmax(0, 1fr) auto;
} }
@@ -1306,7 +1331,8 @@ body.cf24-modal-open {
} }
.cf24-variants th { .cf24-variants th {
font-weight: 500; font-weight: 700;
text-align: center;
font-size: 12px; font-size: 12px;
color: var(--color-midtone-gray, #737373); color: var(--color-midtone-gray, #737373);
white-space: nowrap; white-space: nowrap;
@@ -1323,7 +1349,9 @@ body.cf24-modal-open {
.cf24-v-code { width: 132px; } .cf24-v-code { width: 132px; }
.cf24-v-amount { width: 90px; } .cf24-v-amount { width: 90px; }
.cf24-v-amount input { text-align: right; } .cf24-v-amount input { text-align: right; }
.cf24-v-flag { width: 56px; text-align: center; } .cf24-v-qty { width: 70px; }
.cf24-v-qty input { text-align: right; }
.cf24-variants .cf24-v-flag { width: 56px; text-align: center; }
/* 품목코드 — 클릭하면 클립보드로. 눌리는 것임을 커서·밑줄로 알린다. */ /* 품목코드 — 클릭하면 클립보드로. 눌리는 것임을 커서·밑줄로 알린다. */
.cf24-v-copy { .cf24-v-copy {
+1
View File
@@ -54,6 +54,7 @@
}); });
// ── 날짜 — 프로젝트 날짜 팝업 ── // ── 날짜 — 프로젝트 날짜 팝업 ──
L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" }); L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" });
if (L.enhanceTimeInput) L.enhanceTimeInput(timeEl, { placeholder: "00:00" }); // 프로젝트 공용 시각 팝업(5분 단위)
// ── 받는 사람 — 프로젝트 멤버 고르기 모양 ── // ── 받는 사람 — 프로젝트 멤버 고르기 모양 ──
peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>'; peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>';
function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; } function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; }
+8 -3
View File
@@ -4,7 +4,7 @@
* 대상 셀렉터는 UI 크롬(제목/헤더/버튼/라벨/배지/옵션/안내문)으로 한정 → * 대상 셀렉터는 UI 크롬(제목/헤더/버튼/라벨/배지/옵션/안내문)으로 한정 →
* 데이터 셀(상품코드/수량)은 건드리지 않음. * 데이터 셀(상품코드/수량)은 건드리지 않음.
* - 상품명: 서버가 data-ko / data-en 을 함께 렌더 → 언어에 맞게 textContent 교체. * - 상품명: 서버가 data-ko / data-en 을 함께 렌더 → 언어에 맞게 textContent 교체.
* - 선택값은 localStorage('mys_lang') 에 저장, 모든 화면 공통 적용. * - 선택값은 localStorage('mys_lang') 에 저장, 모든 화면 공통 적용. 저장값이 없으면 브라우저·OS 언어(ko → 한글, 그 밖 → 영어).
*/ */
(function () { (function () {
"use strict"; "use strict";
@@ -173,13 +173,18 @@
document.documentElement.setAttribute("data-mys-lang", lang); document.documentElement.setAttribute("data-mys-lang", lang);
} }
// 고른 값(localStorage) 이 없으면 브라우저·OS 기본 언어 — 한국어(ko…)면 한글, 그 밖은 영어(2026-11-20, app/lang.py 와 같은 규칙)
function current() { function current() {
return localStorage.getItem("mys_lang") === "en" ? "en" : "ko"; var saved = null;
try { saved = localStorage.getItem("mys_lang"); } catch (_) { /* 저장소 없음 */ }
if (saved === "en" || saved === "ko") return saved;
var os = String((navigator.languages && navigator.languages[0]) || navigator.language || "ko").toLowerCase();
return os.indexOf("ko") === 0 ? "ko" : "en";
} }
function toggle() { function toggle() {
var next = current() === "en" ? "ko" : "en"; var next = current() === "en" ? "ko" : "en";
localStorage.setItem("mys_lang", next); try { localStorage.setItem("mys_lang", next); } catch (_) { /* 기억만 못 함 */ }
applyLang(next); applyLang(next);
} }
+269
View File
@@ -0,0 +1,269 @@
/* 말레이시아 실적 영문 화면(2026-11-20) — 서버가 영문(lang=en)일 때만 performance.js 앞에 싣는다. 한국 실적은 안 쓴다.
*
* 같은 템플릿·performance.js 를 한국 실적과 함께 쓰므로 한글을 고치지 않고, 그린 뒤 글자를 바꾼다:
* ① 사전(EN — 한글 문구 그대로가 키) ② 패턴(RULES — 날짜·기간·이름이 섞인 글) ③ 낱말 치환(PHRASES — 결과에 한글이 안 남을 때만).
* .perf 안 글자·title·aria-label·placeholder, 나중에 생기는 창·메뉴·말풍선(MutationObserver), 알림·확인 창 문구(erpAlert·erpConfirm·alert·confirm).
* 못 바꾼 글은 한글 그대로 두고 window.__perfI18nMissing 에 모은다 — tests/js/perf_malaysia_en.browser.test.js 가 화면에 한글이 없는지 본다.
* 새 화면 문구를 넣으면 여기에도 영문을 넣는다. 긴 안내 문단(굵은 글자 섞임)은 템플릿에 {% if lang == 'en' %} 로 따로 쓴다.
*/
(function () {
"use strict";
const ROOT = document.querySelector(".perf[data-lang='en']");
if (!ROOT) return;
const HANGUL = /[가-힣]/;
const EN = {
// 탭·기간·표
"매출 실적": "Sales", "광고비": "Ad Spend", "실적 설정": "Settings", "수수료 설정": "Commission settings",
"말레이시아 실적 메뉴": "Malaysia Sales menu", "말레이시아 실적 설정": "Settings", "기간 선택": "Period", "이번달": "This month",
"올해": "This year", "직접선택": "Custom", "조회": "Apply", "전체": "All", "적용": "Apply", "표시 기준": "Show",
"총매출": "Gross sales", "수수료": "Commission", "수수료 차감 매출": "Net sales", "매출": "Sales",
"엑셀 업로드": "Excel upload", "파일 업로드": "File upload", "단위: RM": "Unit: RM", "광고비(ROAS%)": "Ad spend (ROAS%)",
"날짜": "Date", "월": "Month", "일 합계": "Daily total", "월 합계": "Monthly total", "기간 합계": "Period total",
"연간 합계": "Annual total", "주간합계": "Week total", "합계": "Total", "쇼핑몰": "Marketplace", "채널": "Channel",
"매출 비중": "Share", "비중": "Share", "그룹": "Group", "수동 입력": "Manual entry", "ROAS": "ROAS",
"일별 매출 추이": "Daily sales trend", "월별 매출 추이": "Monthly sales trend", "쇼핑몰별 비중": "Share by marketplace",
"일별 광고비 추이": "Daily ad spend trend", "월별 광고비 추이": "Monthly ad spend trend", "채널별 비중": "Share by channel",
"일자별 × 쇼핑몰": "Daily × marketplace", "월별 × 쇼핑몰": "Monthly × marketplace",
"일자별 × 광고 채널": "Daily × ad channel", "월별 × 광고 채널": "Monthly × ad channel",
"기간 내 매출이 없습니다.": "No sales in this period.", "기간 내 광고비가 없습니다.": "No ad spend in this period.",
"매출 없음": "No sales", "하위 쇼핑몰 접기/펴기": "Collapse / expand sub columns",
"수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력": "Enter manual sales from an Excel file",
"매출에 포함된 쇼핑몰이 없습니다.": "No marketplaces are included in sales.", "에서 쇼핑몰 사용을 켜세요.": "— turn marketplaces on.",
"매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 쇼핑몰 그룹(합계) 칸 아래, ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비":
"Orange figures = that marketplace's ad spend (ROAS%), same as the Ad Spend tab. Shown under the marketplace group (total) cell; ROAS = shop + live commerce sales ÷ ad spend",
"중지됨": "Stopped",
// 설정
"쇼핑몰 설정": "Marketplaces", "사용": "Active", "매출 집계": "In sales", "수수료율": "Commission rate",
"미설정": "Not set", "변경": "Change", "이름 변경": "Rename", "삭제": "Delete", "그룹 없음": "No group",
"직접 추가": "Custom", "+ 쇼핑몰 추가(수동 입력)": "+ Add marketplace (manual)", "+ 그룹 추가": "+ Add group",
"끌어서 순서 변경": "Drag to reorder", "끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)": "Drag to reorder (a group moves with its sub marketplaces)",
"사용 여부": "Active", "매출 집계에 포함": "Include in sales",
"⠿ 를 끌어 순서를 바꾸면 매출 실적 열 순서에 그대로 반영됩니다. 그룹은 직접 추가한 쇼핑몰만 묶을 수 있습니다.":
"Drag ⠿ to reorder — the sales table columns follow. Only custom marketplaces can be grouped.",
"실적 설정에서 직접 추가한 쇼핑몰": "Marketplace added in settings",
"수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다": "Manual-only marketplace — always on (no API)",
"API 연동 없이 실적 일자별 표에 매출을 직접 입력하는 쇼핑몰을 추가": "Add a marketplace whose sales you enter by hand in the daily table",
"직접 추가한 쇼핑몰을 묶는 그룹 — 그룹 매출 = 하위 쇼핑몰 매출 합계": "A group of custom marketplaces — group sales = sum of its marketplaces",
"그룹 — 그룹으로 묶으면 매출 실적에서 그룹 열이 하위 쇼핑몰 매출 합계": "Group — the group column shows the sum of its marketplaces",
"보기 설정": "View settings", "표 열 너비": "Column width", "자동(글자 길이)": "Auto (fit text)", "수동 조절": "Manual",
"조절한 너비 초기화": "Reset widths", "초기화했습니다": "Reset",
"매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.":
"How the Sales and Ad Spend screens look. Applies to this browser only and saves immediately.",
"열 너비가 글자 길이에 맞춰 자동으로 정해집니다.": "Column widths fit the text automatically.",
"매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.":
"Drag the right edge of a header to resize (double-click for auto width). Widths are kept.",
"매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?": "Clear all adjusted column widths and go back to auto width?",
"공통 보기 설정": "Shared view settings", "모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.":
"Applies to everyone's Sales screen. Saves immediately.",
"숨길 쇼핑몰": "Hidden columns",
"체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다.":
"Checked marketplaces are hidden from the daily table only. Totals, charts and cumulative amounts stay the same.",
"수수료율은": "Commission rates apply from the", "적용 시작일": "Effective date",
"부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).": "; earlier sales keep the old rate (past results don't change).",
"쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.":
"Set the commission rate per marketplace. Saved immediately and used for commission and net sales.",
// 창(performance.js)
"닫기": "Close", "업로드": "Upload", "취소": "Cancel", "저장": "Save", "확인": "OK", "샘플 파일 받기": "Download sample",
"수동 입력 엑셀 업로드": "Excel upload (manual sales)", "엑셀 파일": "Excel file", "엑셀 파일을 고르세요.": "Choose an Excel file.",
"올리는 중…": "Uploading…", "불러오는 중…": "Loading…", "없음": "None",
"1열에": "Column 1:", ", 2열부터": ", from column 2:", "쇼핑몰 이름": "marketplace names",
"을 머리글로 적고 그날": "as headers, then each day's", "을 넣습니다. 값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.":
". Only filled cells are saved (overwriting that day); empty cells stay as they are.",
"반영할 값이 없습니다(값이 있는 칸이 없음).": "Nothing to save (no filled cells).",
"창을 닫으면 표·합계·그래프가 다시 계산됩니다.": "Totals and charts are recalculated when you close this window.",
"메모 삽입": "Insert note", "메모 수정": "Edit note", "메모 삭제": "Delete note", "메모": "Note",
"메모를 입력하세요 (Ctrl+Enter 저장)": "Type a note (Ctrl+Enter to save)",
"수수료율(%)": "Commission rate (%)", "예: 5, 10.8, 15.35": "e.g. 5, 10.8, 15.35", "처음부터(과거 전체)": "From the start (all past)",
"이 날짜부터 새 요율로 계산하고, 그 전 실적은 예전 요율을 유지합니다.": "The new rate applies from this date; earlier sales keep the old rate.",
"변경 이력": "Change history", "요율": "Rate", "변경자": "Changed by", "처음부터": "From the start",
"이력이 없습니다(현재 0%).": "No history (currently 0%).",
"이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다.": "Delete this rate? Commission for that period will be recalculated.",
"쇼핑몰 추가(수동 입력)": "Add marketplace (manual)", "그룹 추가": "Add group", "이름": "Name",
"그룹 이름 변경": "Rename group", "쇼핑몰 이름 변경": "Rename marketplace", "언어": "Language",
"숫자 또는 1000+2000 같은 계산식만 입력하세요.": "Enter a number or a formula such as 10.5+20.",
// 서버 오류(말레이시아 실적에서 날 수 있는 것)
"금액이 너무 큽니다.": "The amount is too large.", "날짜가 필요합니다.": "A date is required.",
"알 수 없는 쇼핑몰입니다.": "Unknown marketplace.", "알 수 없는 광고 채널입니다.": "Unknown ad channel.",
"이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).": "Manual entry is off for this marketplace (turn it on in Settings).",
"이름을 입력하세요.": "Enter a name.", "그룹은 다른 그룹에 넣을 수 없습니다.": "A group can't be put in another group.",
"그룹은 이름만 바꿀 수 있습니다.": "Only a group's name can be changed.", "그룹을 찾지 못했습니다.": "Group not found.",
"수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.": "Manual entry can't be turned off for a manual-only marketplace.",
"수수료 이력을 찾지 못했습니다.": "Rate history not found.", "수수료율은 0 ~ 100 사이여야 합니다.": "The rate must be between 0 and 100.",
"수수료율은 소수점 셋째 자리까지 입력할 수 있습니다.": "Up to 3 decimal places.",
"수수료율은 숫자로 입력하세요(예: 5, 10.8, 15.35).": "Enter the rate as a number (e.g. 5, 10.8, 15.35).",
"적용 시작일을 입력하세요.": "Enter the effective date.", "순서 목록이 비었습니다.": "The order list is empty.",
"순서 목록에 같은 쇼핑몰이 두 번 있습니다.": "A marketplace appears twice in the order.", "파일을 고르세요.": "Choose a file.",
"숫자와 + - * / ( ) 만 입력할 수 있습니다.": "Only numbers and + - * / ( ) are allowed.", "계산식이 끝나지 않았습니다.": "The formula is incomplete.",
"0으로 나눌 수 없습니다.": "Can't divide by 0.", "괄호가 맞지 않습니다.": "Brackets don't match.",
"계산식이 올바르지 않습니다.": "The formula is invalid.", "계산식이 너무 깁니다.": "The formula is too long.", "계산할 수 없는 식입니다.": "Can't calculate this formula.",
"빈 파일입니다.": "The file is empty.", "파일이 너무 큽니다(5MB 이하).": "The file is too large (5 MB max).",
"엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.": "Can't read the Excel (.xlsx) file. Save it in the sample format and upload again.",
"1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.": "Row 1 needs Date and marketplace name headers.",
"기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요).": "Built-in marketplaces can't be deleted (turn them off instead).",
"기본 쇼핑몰은 이름·그룹을 바꿀 수 없습니다.": "Built-in marketplaces can't be renamed or grouped.",
"요청 실패": "Request failed",
// 쇼핑몰 이름(seed — 바꾼 이름은 낱말 치환으로)
"틱톡": "TikTok", "쇼피": "Shopee", "라자다": "Lazada",
};
const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const DOW = { "월": "Mon", "화": "Tue", "수": "Wed", "목": "Thu", "금": "Fri", "토": "Sat", "일": "Sun" };
const list = function (s) { return s.split(", ").map(tr).join(", "); };
// 값이 섞인 글 — [정규식, (일치) → 영문]. 위에서부터 처음 맞는 것.
const RULES = [
[/^(\d{4})년 (\d{1,2})월 (\d{1,2})일 ~ (?:(\d{4})년 )?(\d{1,2})월 (\d{1,2})일$/, function (m) {
return MON[m[2] - 1] + " " + m[3] + (m[4] && m[4] !== m[1] ? ", " + m[1] : "") + " – " + MON[m[5] - 1] + " " + m[6] + ", " + (m[4] || m[1]); }],
[/^(\d{4})년 (\d{1,2})월 (\d{1,2})일 \((.)\)$/, function (m) { return DOW[m[4]] + ", " + MON[m[2] - 1] + " " + m[3] + ", " + m[1]; }],
[/^(\d{4})년 (\d{1,2})월$/, function (m) { return MON[m[2] - 1] + " " + m[1]; }],
[/^(\d{4})년$/, function (m) { return m[1]; }],
[/^(\d{2}\/\d{2})\((.)\)$/, function (m) { return m[1] + " " + DOW[m[2]]; }],
[/^주간합계 \((.+)\)$/, function (m) { return "Week total (" + m[1] + ")"; }],
[/^(\d{4})년 누적$/, function (m) { return m[1] + " year to date"; }],
[/^(\d{4})년 누적 광고비$/, function (m) { return m[1] + " ad spend YTD"; }],
[/^(\d{4})년 (\d{1,2})월 쇼핑몰별 누적 실적$/, function (m) { return MON[m[2] - 1] + " " + m[1] + " by marketplace"; }],
[/^(\d{4})년 (\d{1,2})월 채널별 광고비$/, function (m) { return MON[m[2] - 1] + " " + m[1] + " ad spend by channel"; }],
[/^(.+) 대비$/, function (m) { return "vs " + tr(m[1]).toLowerCase(); }],
[/^(.+) 비교 없음$/, function (m) { return "no comparison with " + tr(m[1]).toLowerCase(); }],
[/^쇼핑몰: (\d+)곳$/, function (m) { return "Marketplaces: " + m[1]; }],
[/^쇼핑몰: 전체$/, function () { return "Marketplaces: All"; }],
[/^하위 쇼핑몰 (\d+)곳 — /, function (m) { return m[1] + " sub marketplaces — the group column on Sales = their sum (commission at each marketplace's rate)"; }],
[/^(.+) — 하위 쇼핑몰 (\d+)곳 매출 합계$/, function (m) { return tr(m[1]) + " — sum of " + m[2] + " sub marketplaces"; }],
[/^(.+) — 수동 입력\(날짜 칸을 눌러 입력\)$/, function (m) { return tr(m[1]) + " — manual entry (click a date cell)"; }],
[/^(.+) 하위 쇼핑몰 (접기|펴기)$/, function (m) { return (m[2] === "접기" ? "Collapse " : "Expand ") + tr(m[1]); }],
[/^(.+) 열 (접기|펴기)$/, function (m) { return (m[2] === "접기" ? "Collapse column " : "Expand column ") + tr(m[1]); }],
[/^(.+) — 날짜 칸을 눌러 광고비 입력\. 괄호 = ROAS\((.+) 매출 ÷ 광고비\)$/, function (m) {
return tr(m[1]) + " — click a date cell to enter ad spend. Brackets = ROAS (" + tr(m[2]) + " sales ÷ ad spend)"; }],
[/^총매출 RM (.+)$/, function (m) { return "Gross sales RM " + m[1]; }],
[/^(\d{1,2})월 (.+)$/, function (m) { return MON[m[1] - 1] + " " + m[2]; }], // 그래프 말풍선 "10월 1,834.55 RM"
[/^(\d{1,2})월$/, function (m) { return MON[m[1] - 1]; }],
[/^입력 가능한 쇼핑몰: (.*)$/, function (m) { return "Marketplaces you can enter: " + list(m[1]); }],
[/^건너뛴 열: (.*)$/, function (m) { return "Skipped columns: " + m[1].split(", ").map(function (c) {
return c.replace(/^(.*)\((알 수 없는 쇼핑몰|수동 입력 꺼짐)\)$/, function (_, n, why) {
return tr(n) + " (" + (why === "수동 입력 꺼짐" ? "manual entry off" : "unknown marketplace") + ")"; }); }).join(", "); }],
[/^(.+) · (\d{4}\.\d{2}\.\d{2}) 메모$/, function (m) { return "Note · " + tr(m[1]) + " · " + m[2]; }],
[/^(메모 삽입|메모 수정) · (.+) · (\d{4}\.\d{2}\.\d{2})$/, function (m) { return tr(m[1]) + " · " + tr(m[2]) + " · " + m[3]; }],
[/^(.+) 칸의 메모를 지울까요\?$/, function (m) { return "Delete the note in " + tr(m[1]) + "?"; }],
[/^(.+) 수수료율$/, function (m) { return tr(m[1]) + " commission rate"; }],
[/^쇼핑몰 \[(.+)\]을 삭제할까요\?(?: 입력해 둔 매출 ([\d,]+)일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다\.)?$/, function (m) {
return "Delete marketplace [" + tr(m[1]) + "]?" + (m[2] ? " Its " + m[2] + " days of entered sales and commission rates will be deleted too. This can't be undone." : ""); }],
[/^그룹 \[(.+)\]을 삭제할까요\? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다\.$/, function (m) {
return "Delete group [" + tr(m[1]) + "]? Its marketplaces stay, with no group."; }],
[/^([\d,]+)칸 반영 \((.+)\)$/, function (m) { return m[1] + " cells saved (" + m[2] + ")"; }],
[/^(.+) ([\d,]+)일$/, function (m) { return tr(m[1]) + " " + m[2] + " days"; }],
[/^저장 실패\((.+?)\): (.*)$/, function (m) { return "Save failed (" + m[1] + "): " + tr(m[2]); }],
[/^(저장|삭제|메모 저장|메모 삭제|순서 저장|업로드) 실패: (.*)$/, function (m) {
return { "저장": "Save", "삭제": "Delete", "메모 저장": "Saving the note", "메모 삭제": "Deleting the note", "순서 저장": "Saving the order", "업로드": "Upload" }[m[1]] + " failed: " + tr(m[2]); }],
[/^업로드 실패 \((\d+)\)$/, function (m) { return "Upload failed (" + m[1] + ")"; }],
[/^접은 열을 저장하지 못했습니다: (.*)$/, function (m) { return "Couldn't save folded columns: " + tr(m[1]); }],
[/^요청 실패 \((\d+)\)$/, function (m) { return "Request failed (" + m[1] + ")"; }],
[/^(.*) \(숫자 또는 1000\+2000 같은 계산식\)$/, function (m) { return tr(m[1]) + " (a number or a formula such as 10.5+20)"; }],
[/^같은 이름\((.+)\)이 이미 있습니다\.$/, function (m) { return "The name (" + m[1] + ") already exists."; }],
[/^이름은 (\d+)자까지입니다\.$/, function (m) { return "Names can be up to " + m[1] + " characters."; }],
[/^메모는 ([\d,]+)자까지 쓸 수 있습니다\.$/, function (m) { return "Notes can be up to " + m[1] + " characters."; }],
[/^잘못된 칸이 (\d+)개(\+?) 있어 아무것도 저장하지 않았습니다\. 고친 뒤 다시 올려 주세요\.$/, function (m) {
return m[1] + m[2] + " invalid cells — nothing was saved. Fix them and upload again."; }],
[/^([A-Z]+\d+): 금액이 숫자가 아닙니다\((.*)\)\.$/, function (m) { return m[1] + ": the amount is not a number (" + m[2] + ")."; }],
[/^([A-Z]+\d+): 금액이 너무 큽니다\.$/, function (m) { return m[1] + ": the amount is too large."; }],
[/^([A-Z]+\d+): 날짜를 읽을 수 없습니다\((.*)\)\.$/, function (m) { return m[1] + ": can't read the date (" + m[2] + ")."; }],
[/^(\d+)행: 날짜가 비어 있습니다\.$/, function (m) { return "Row " + m[1] + ": the date is empty."; }],
[/^([A-Z]+\d+): (.+) (\d{4}-\d{2}-\d{2}) 이 ([A-Z]+\d+) 와 겹칩니다\.$/, function (m) {
return m[1] + ": " + tr(m[2]) + " " + m[3] + " overlaps " + m[4] + "."; }],
[/^([A-Z]+\d+) (.+): 같은 쇼핑몰 열이 두 번 있습니다\.$/, function (m) { return m[1] + " " + tr(m[2]) + ": the same marketplace column appears twice."; }],
[/^반영할 쇼핑몰 열이 없습니다\./, function () { return "No columns to save — use the names of marketplaces with manual entry on as headers."; }],
[/^한 번에 ([\d,]+)일까지 올릴 수 있습니다\.$/, function (m) { return "Up to " + m[1] + " days per upload."; }],
[/^(.+) 형식이 올바르지 않습니다\(YYYY-MM-DD\)\.$/, function (m) { return tr(m[1]) + " must be YYYY-MM-DD."; }],
];
// 낱말 치환 — 긴 것부터. 결과에 한글이 하나도 안 남을 때만 쓴다(문장이 반쯤 바뀌지 않게).
const PHRASES = [
["라이브커머스", "Live Commerce"], ["쇼핑몰", "Shop"], ["틱톡", "TikTok"], ["쇼피", "Shopee"], ["라자다", "Lazada"],
["수수료 차감 매출", "net sales"], ["매출 대비 광고비", "ad spend to sales"], ["누적 광고비", "ad spend YTD"],
["전년 같은 기간", "same period last year"], ["전월 같은 기간", "same period last month"], ["전주 같은 기간", "same period last week"],
["전일 같은 기간", "same time yesterday"], ["직전 기간 같은 기간", "same span of the previous period"],
["같은 기간", "same period"], ["직전 기간", "previous period"],
["이번달", "This month"], ["이번주", "This week"], ["올해", "This year"], ["오늘", "Today"], ["선택 기간", "Selected period"],
["해당 월", "That month"], ["해당 주", "That week"], ["해당 연도", "That year"], ["해당일", "That day"],
["이전달", "Previous month"], ["다음달", "Next month"], ["이전주", "Previous week"], ["다음주", "Next week"],
["이전해", "Previous year"], ["다음해", "Next year"], ["다음날", "Next day"],
["전월", "last month"], ["전주", "last week"], ["전년", "last year"], ["전일", "previous day"],
["이전", "Previous"], ["다음", "Next"], ["광고비", "ad spend"], ["매출", "sales"], ["누적", "YTD"], ["대체", "(Replacement)"],
["날짜", "date"], ["시작일", "start date"], ["종료일", "end date"],
].sort(function (a, b) { return b[0].length - a[0].length; });
const missing = window.__perfI18nMissing = [];
const done = new Map();
function tr(text) {
if (!text || !HANGUL.test(text)) return text;
if (done.has(text)) return done.get(text);
const lead = text.match(/^\s*/)[0], tail = text.match(/\s*$/)[0], core = text.trim();
let out = EN[core];
if (out === undefined) {
for (let i = 0; i < RULES.length; i++) {
const m = core.match(RULES[i][0]);
if (m) { out = RULES[i][1](m); break; }
}
}
if ((out === undefined || HANGUL.test(out)) && core.indexOf("\n") >= 0) { // 여러 줄 알림 — 줄마다
const lines = core.split("\n").map(tr);
out = lines.some(function (l) { return HANGUL.test(l); }) ? undefined : lines.join("\n");
}
if (out === undefined || HANGUL.test(out)) {
let s = core;
PHRASES.forEach(function (p) { s = s.split(p[0]).join(p[1]); });
out = HANGUL.test(s) ? undefined : s.replace(/\s+/g, " ").replace(/^([a-z])/, function (c) { return c.toUpperCase(); });
}
if (out === undefined) { if (missing.indexOf(core) < 0) missing.push(core); }
const res = out === undefined ? text : lead + out + tail;
done.set(text, res);
return res;
}
const ATTRS = ["title", "aria-label", "placeholder"];
function noText(el) { return !el || !!el.closest("[translate='no'], script, style, textarea"); }
function fixAttrs(el) {
if (el.closest("[translate='no']")) return;
ATTRS.forEach(function (a) {
const v = el.getAttribute(a);
if (v && HANGUL.test(v)) { const t = tr(v); if (t !== v) el.setAttribute(a, t); }
});
}
function fixText(n) {
if (HANGUL.test(n.nodeValue) && !noText(n.parentElement)) { const v = tr(n.nodeValue); if (v !== n.nodeValue) n.nodeValue = v; }
}
function walk(root) {
if (!root) return;
if (root.nodeType === 3) { fixText(root); return; }
if (root.nodeType !== 1) return;
fixAttrs(root);
const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
for (let n = tw.nextNode(); n; n = tw.nextNode()) {
if (n.nodeType === 3) fixText(n); else fixAttrs(n);
}
}
// 알림·확인 창 문구 — 창을 그리기 전에 바꾼다(erp-dialog.js 창의 [확인]·[취소] 단추는 아래 관찰자가 바꾼다).
["erpAlert", "erpConfirm", "erpPrompt"].forEach(function (name) {
const orig = window[name];
if (typeof orig === "function") window[name] = function (msg) { const a = Array.prototype.slice.call(arguments); a[0] = tr(String(msg)); return orig.apply(this, a); };
});
["alert", "confirm"].forEach(function (name) {
const orig = window[name];
window[name] = function (msg) { return orig.call(window, tr(String(msg == null ? "" : msg))); };
});
// 이 화면 것만 — .perf 안 + 실적 창·메뉴·말풍선(perf-…)·알림 창. ERP 셸(사이드바·공지 등)은 건드리지 않는다.
function mine(node) {
const el = node.nodeType === 1 ? node : node.parentElement;
return !!el && (ROOT.contains(el) || !!el.closest('[class*="perf-"], .erp-dialog-backdrop'));
}
walk(ROOT);
ROOT.classList.add("is-i18n");
new MutationObserver(function (records) {
records.forEach(function (r) {
if (r.type !== "childList") { if (mine(r.target)) walk(r.target); return; }
r.addedNodes.forEach(function (n) { if (mine(n)) walk(n); });
});
}).observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ATTRS });
window.__perfI18n = tr;
})();
+23 -5
View File
@@ -43,13 +43,19 @@
.perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); } .perf-tab.is-active { color: #fff; box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
.perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); } .perf-tab-sales.is-active, .perf-tab-sales.is-active:hover { background: var(--color-deep-black, #1e1f21); }
.perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); } .perf-tab-ads.is-active, .perf-tab-ads.is-active:hover { background: var(--perf-ad, #d9480f); }
.perf-tab-tiktok.is-active, .perf-tab-tiktok.is-active:hover { background: var(--perf-tiktok, #e11d48); }
a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; } a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-tab-gear { .perf-tab-gear {
margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; margin-left: auto; display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px;
border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none; border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none;
} }
.perf-tab-gear .material-symbols-outlined { font-size: 22px; } .perf-tab-gear .material-symbols-outlined { font-size: 22px; }
/* 한글·영문 전환(말레이시아 실적, 2026-11-20) — 톱니 바로 왼쪽. 영문 화면은 번역(performance-en.js)이 끝날 때까지 숨김(한글이 번쩍이지 않게) */
.perf-lang { margin-left: auto; display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 999px; background: #fff; }
.perf-lang button { min-width: 40px; padding: 4px 10px; border: 0; border-radius: 999px; background: none; font-size: 12px; font-weight: 600; color: #4b5563; cursor: pointer; }
.perf-lang button.is-active { background: #111; color: #fff; }
.perf-lang + .perf-tab-gear { margin-left: 0; }
.perf[data-lang="en"]:not(.is-i18n) { visibility: hidden; animation: perf-i18n-reveal 0s linear 1.5s forwards; } /* 스크립트를 못 실어도 1.5초 뒤엔 보인다 */
@keyframes perf-i18n-reveal { to { visibility: visible; } }
.perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); } .perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); }
.perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); } .perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); }
@@ -60,10 +66,6 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); } .perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
/* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */ /* 광고 API(구글 광고 등)로 가져온 칸 — 초록 숫자 */
.perf-ads td.is-api .v-gross { color: #1e8e3e; } .perf-ads td.is-api .v-gross { color: #1e8e3e; }
/* 틱톡 화면 — 광고비 화면 틀에 색만 바꿈 */
.perf, .perf-modal { --perf-tiktok: #e11d48; }
.perf-tiktok .perf-quick .perf-seg.is-active { background: var(--perf-tiktok); }
.perf-tiktok .perf-chart .bar { fill: var(--perf-tiktok); }
.perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; } .perf-ad-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap; }
/* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */ /* 광고 API 설정 창 — 서비스 계정 JSON 같은 여러 줄 항목 */
.perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; } .perf-cred-multi { width: 100%; font-family: ui-monospace, Consolas, monospace; font-size: 12px; resize: vertical; }
@@ -523,3 +525,19 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
.perf-main thead th:hover > .perf-colw-grip::after { background: #c3c6cb; } .perf-main thead th:hover > .perf-colw-grip::after { background: #c3c6cb; }
.perf-main thead th > .perf-colw-grip:hover::after, .perf-colw-grip.is-active::after { background: #1a56db; } .perf-main thead th > .perf-colw-grip:hover::after, .perf-colw-grip.is-active::after { background: #1a56db; }
body.perf-colw-dragging, body.perf-colw-dragging * { cursor: col-resize !important; user-select: none; } body.perf-colw-dragging, body.perf-colw-dragging * { cursor: col-resize !important; user-select: none; }
/* 열 접기(2026-11-06) — 일자별 표 머리글 위 버튼(performance.js initColFold), 접은 열 = 26px 띠(버튼만, 너비는 JS CFOLD_W 와 같게) */
.perf-cfold { display: flex; align-items: center; justify-content: center; width: 20px; height: 16px; margin: -4px auto 2px; padding: 0;
border: 0; border-radius: 4px; background: none; color: #b5b8bd; cursor: pointer; }
.perf-cfold:hover { background: rgba(0, 0, 0, .08); color: #333; }
.perf-cfold:focus-visible { outline: 2px solid #1a56db; outline-offset: 1px; }
.perf-cfold svg { transition: transform .2s ease; }
.perf-cfold[aria-expanded="false"] svg { transform: rotate(180deg); }
.perf-main th.is-cfold, .perf-main td.is-cfold { width: 26px; min-width: 26px; max-width: 26px; padding-left: 0; padding-right: 0;
font-size: 0; pointer-events: none; }
.perf-main .is-cfold > :not(.perf-cfold) { display: none !important; } /* 보기 기준(총매출·차감) 표시 규칙보다 우선 */
.perf-main th.is-cfold .perf-cfold { pointer-events: auto; margin-top: 0; }
@media (prefers-reduced-motion: reduce) { .perf-cfold svg { transition: none; } }
/* 열 접기 버튼 말풍선 — 커서 바로 위, 글자 = 열 제목 크기(12px 굵게) */
.perf-cfold-tip { position: fixed; z-index: 2200; transform: translate(-50%, calc(-100% - 12px)); padding: 5px 9px; border-radius: 6px;
background: #222; color: #fff; font-size: 12px; font-weight: 700; line-height: 1.4; white-space: nowrap; pointer-events: none;
box-shadow: 0 4px 12px rgba(0, 0, 0, .18); }
+128 -47
View File
@@ -1,6 +1,8 @@
/* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작. /* 실적(쇼핑몰 통합 매출) — 대시보드 / 설정 화면 동작.
* *
* 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(/performance/api/…)로만. * 쇼핑몰 API 는 브라우저에서 직접 부르지 않는다. 모든 요청은 우리 서버(BASE/api/…)로만.
* 같은 화면이 [실적](/performance)과 [말레이시아 실적](/malaysia/performance, 2026-11-20)에 쓰인다 — 주소는 .perf data-base,
* 말레이시아는 data-cents(금액 = 센 정수, 화면 = RM 소수 2자리).
* 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다). * 인증정보 창은 저장된 비밀값을 받지 않는다(서버가 "저장됨" 여부만 준다).
*/ */
(function () { (function () {
@@ -22,22 +24,39 @@
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]; return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
}); });
} }
const PERF_ROOT = document.querySelector(".perf");
const BASE = (PERF_ROOT && PERF_ROOT.dataset.base) || "/performance";
const CENTS = !!(PERF_ROOT && PERF_ROOT.dataset.cents); // 말레이시아 실적 — 금액 = 센(0.01 RM) 정수
const CUR = CENTS ? "RM" : "원";
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); } function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; } // 금액(저장 단위) → 글자. 원 = 정수, 센 = RM 소수 2자리(서버 variant.num_text 와 같음)
function money(n) {
return CENTS ? (Number(n || 0) / 100).toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : fmt(n);
}
function won(n) { return n ? money(n) : '<span class="perf-zero">–</span>'; }
// 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리) // 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
function unitWon(n, unit) { function unitWon(n, unit) {
if (!n) return won(0); if (!n) return won(0);
if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR"); if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR");
if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 }); if (unit === "million") return (Math.round(n / 100000) / 10).toLocaleString("ko-KR", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
return fmt(n); return money(n);
} }
// 축 눈금용 짧은 금액(1.2억 / 350만) // 축 눈금용 짧은 금액(1.2억 / 350만)
function short(n) { function short(n) {
if (CENTS) n = Math.round(n / 100);
const a = Math.abs(n), s = n < 0 ? "-" : ""; const a = Math.abs(n), s = n < 0 ? "-" : "";
if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억"; if (a >= 100000000) return s + (a / 100000000).toFixed(a >= 1000000000 ? 0 : 1).replace(/\.0$/, "") + "억";
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만"; if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
return s + fmt(a); return s + fmt(a);
} }
// 한글·영문 전환(말레이시아 실적, 2026-11-20) — 고른 언어를 쿠키(mperf_lang, 이 모듈 주소에만)에 두고 다시 그린다(서버가 언어를 정함)
document.addEventListener("click", function (e) {
const b = e.target.closest && e.target.closest("button[data-perf-lang]");
if (!b || b.classList.contains("is-active")) return;
document.cookie = "mperf_lang=" + b.dataset.perfLang + "; path=" + BASE + "; max-age=31536000; SameSite=Lax" +
(location.protocol === "https:" ? "; Secure" : "");
location.reload();
});
function alertMsg(msg, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : Promise.resolve(window.alert(msg)); } function alertMsg(msg, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : Promise.resolve(window.alert(msg)); }
function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); } function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); }
@@ -179,7 +198,7 @@
b.disabled = true; b.disabled = true;
b.textContent = "중지하는 중…"; b.textContent = "중지하는 중…";
try { try {
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" + const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/shops/" +
encodeURIComponent(b.dataset.stop) + "/stop"); encodeURIComponent(b.dataset.stop) + "/stop");
last = r.job; last = r.job;
renderSyncJob(m.body, r.job, false); renderSyncJob(m.body, r.job, false);
@@ -197,7 +216,7 @@
cancelBtn.disabled = true; cancelBtn.disabled = true;
cancelBtn.textContent = "취소하는 중…"; cancelBtn.textContent = "취소하는 중…";
try { try {
const r = await api("POST", "/performance/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel"); const r = await api("POST", BASE + "/api/sync/jobs/" + encodeURIComponent(jobId) + "/cancel");
last = r.job; last = r.job;
renderSyncJob(m.body, r.job, false); renderSyncJob(m.body, r.job, false);
} catch (err) { } catch (err) {
@@ -207,7 +226,7 @@
} }
}); });
(existing ? Promise.resolve({ job: existing, joined: true }) (existing ? Promise.resolve({ job: existing, joined: true })
: api("POST", startUrl || "/performance/api/sync", Object.assign({ background: true }, payload))).then(function (res) { : api("POST", startUrl || BASE + "/api/sync", Object.assign({ background: true }, payload))).then(function (res) {
last = res.job; last = res.job;
jobId = res.job.id; jobId = res.job.id;
const joined = res.joined; const joined = res.joined;
@@ -217,7 +236,7 @@
async function poll() { async function poll() {
if (closed) return; if (closed) return;
try { try {
const r = await api("GET", "/performance/api/sync/jobs/" + encodeURIComponent(res.job.id)); const r = await api("GET", BASE + "/api/sync/jobs/" + encodeURIComponent(res.job.id));
last = r.job; last = r.job;
renderSyncJob(m.body, r.job, joined); renderSyncJob(m.body, r.job, joined);
if (r.job.finished) { if (r.job.finished) {
@@ -257,6 +276,7 @@
// 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로. // 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로.
// 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다. // 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다.
const COLW_MIN = 36; const COLW_MIN = 36;
const CFOLD_W = 26; // 접은 열 너비 — performance.css .is-cfold 와 같게
function initColWidths(root) { function initColWidths(root) {
const table = root.querySelector("table.perf-colw-manual"); const table = root.querySelector("table.perf-colw-manual");
const row = table && table.tHead && table.tHead.rows[0]; const row = table && table.tHead && table.tHead.rows[0];
@@ -271,7 +291,11 @@
} }
// 날짜 열(label)은 조절 안 함(2026-10-27) — 늘 자동 너비(글자 길이), 손잡이 없음 // 날짜 열(label)은 조절 안 함(2026-10-27) — 늘 자동 너비(글자 길이), 손잡이 없음
function fixedCol(th) { return th.dataset.col === "label"; } function fixedCol(th) { return th.dataset.col === "label"; }
function widthOf(th) { const c = th.dataset.col; return (!fixedCol(th) && saved[c]) || auto[c] || 80; } function widthOf(th) {
if (th.classList.contains("is-cfold")) return CFOLD_W; // 접은 열(initColFold) — 좁은 띠
const c = th.dataset.col;
return (!fixedCol(th) && saved[c]) || auto[c] || 80;
}
function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전) function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전)
let sum = 0; let sum = 0;
heads.forEach(function (th) { heads.forEach(function (th) {
@@ -288,7 +312,7 @@
table.style.width = ""; table.style.width = "";
heads.forEach(function (th) { heads.forEach(function (th) {
const w = th.getBoundingClientRect().width; const w = th.getBoundingClientRect().width;
if (w > 0) auto[th.dataset.col] = Math.ceil(w); if (w > 0 && !th.classList.contains("is-cfold")) auto[th.dataset.col] = Math.ceil(w);
}); });
apply(); apply();
} }
@@ -342,11 +366,68 @@
}; };
} }
// 열 접기(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 버튼으로 열 하나씩 접기/펴기(날짜 열 빼고).
// 접은 열 = 좁은 띠(버튼만, 칸 클릭·메모 안 됨). 보는 사람(로그인 계정)마다 서버에 저장(PUT /api/my-col-fold) — 다른 사람 화면은 그대로.
function initColFold(root, colw) {
const table = root.querySelector("table[data-cfold-kind]");
const row = table && table.tHead && table.tHead.rows[0];
if (!row) return;
let folded = [];
try { folded = JSON.parse(table.dataset.colFold || "[]") || []; } catch (_) { folded = []; }
const ICON = '<svg viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M7.5 3 4.5 6l3 3" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
function setFold(th, fold) {
const i = th.cellIndex;
Array.prototype.forEach.call(table.rows, function (r) { if (r.cells[i]) r.cells[i].classList.toggle("is-cfold", fold); });
const b = th.querySelector(".perf-cfold");
b.setAttribute("aria-expanded", fold ? "false" : "true");
b.setAttribute("aria-label", b.dataset.name + (fold ? " 열 펴기" : " 열 접기"));
}
// 버튼 위 말풍선(2026-11-06) — 커서 위를 따라다니며 쇼핑몰(열) 이름, 글자 크기 = 열 제목. 빈 title 로 머리글 th 의 기본 말풍선은 막는다
let tip = null;
function hideTip() { if (tip) { tip.remove(); tip = null; } }
row.addEventListener("pointermove", function (e) {
const b = e.target.closest(".perf-cfold");
if (!b || (tip && tip._b !== b)) hideTip();
if (!b) return;
if (!tip) { tip = el("div", { class: "perf-cfold-tip", role: "tooltip", text: b.dataset.name }); tip._b = b; document.body.appendChild(tip); }
tip.style.left = e.clientX + "px";
tip.style.top = e.clientY + "px";
});
row.addEventListener("pointerleave", hideTip);
window.addEventListener("scroll", hideTip, true);
Array.prototype.forEach.call(row.cells, function (th) {
const col = th.dataset.col;
if (!col || col === "label") return;
const b = document.createElement("button");
b.type = "button";
b.className = "perf-cfold";
b.title = "";
b.dataset.name = th.textContent.replace(/[✎\s]+/g, " ").trim();
b.innerHTML = ICON;
th.insertBefore(b, th.firstChild);
setFold(th, folded.indexOf(col) >= 0);
});
if (colw && folded.length) colw.apply();
row.addEventListener("click", function (e) {
const b = e.target.closest(".perf-cfold");
if (!b) return;
e.stopPropagation();
const th = b.parentElement, col = th.dataset.col;
const fold = !th.classList.contains("is-cfold");
setFold(th, fold);
if (colw) colw.apply();
folded = folded.filter(function (c) { return c !== col; });
if (fold) folded.push(col);
api("PUT", BASE + "/api/my-col-fold", { kind: table.dataset.cfoldKind, cols: folded })
.catch(function (err) { alertMsg("접은 열을 저장하지 못했습니다: " + err.message); });
});
}
function initDashboard(root) { function initDashboard(root) {
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}"); const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" }; const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐 const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/"; const MANUAL_API = data.manual_api || BASE + "/api/manual-sales/";
const MANUAL_WORD = data.manual_word || "총매출"; const MANUAL_WORD = data.manual_word || "총매출";
const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다."; const EMPTY_TEXT = data.empty_text || "기간 내 매출이 없습니다.";
@@ -359,7 +440,6 @@
b.classList.toggle("is-active", b.dataset.metric === m); b.classList.toggle("is-active", b.dataset.metric === m);
}); });
drawDaily(m, "perf-chart-daily", data.daily); drawDaily(m, "perf-chart-daily", data.daily);
drawDaily(m, "perf-chart-daily2", data.daily2); // 틱톡 탭 — 매출·광고비 두 그래프
drawShare(m); drawShare(m);
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; }); root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
} }
@@ -423,6 +503,7 @@
if (fold) collapsed.push(code); if (fold) collapsed.push(code);
try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ } try { localStorage.setItem(GROUP_KEY, JSON.stringify(collapsed)); } catch (_) { /* 기억만 못 함 */ }
}); });
initColFold(root, colw);
// 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로). // 수동 입력 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글. 값이 있는 칸만 반영(빈 칸은 기존 값 그대로).
// 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다. // 잘못된 칸이 있으면 서버가 아무것도 저장하지 않고 칸 위치 목록을 돌려준다.
@@ -435,7 +516,7 @@
'<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' + '<p class="perf-muted" style="margin:0 0 8px">1열에 <b>날짜</b>, 2열부터 <b>쇼핑몰 이름</b>을 머리글로 적고 그날 <b>총매출</b>을 넣습니다. ' +
"값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" + "값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.</p>" +
'<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" + '<p class="perf-muted" style="margin:0 0 10px">입력 가능한 쇼핑몰: ' + (shops || "없음") + "</p>" +
'<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="/performance/api/manual-sales/sample.xlsx" download>' + '<p style="margin:0 0 12px"><a class="erp-btn erp-btn-outline erp-btn-sm" href="' + BASE + '/api/manual-sales/sample.xlsx" download>' +
"샘플 파일 받기</a></p>" + "샘플 파일 받기</a></p>" +
'<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' + '<input type="file" class="erp-input perf-upload-file" accept=".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" aria-label="엑셀 파일" />' +
'<div class="perf-upload-result"></div>'; '<div class="perf-upload-result"></div>';
@@ -455,7 +536,7 @@
fd.append("file", f); fd.append("file", f);
let res, body = null; let res, body = null;
try { try {
res = await fetch("/performance/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd }); res = await fetch(BASE + "/api/manual-sales/upload", { method: "POST", credentials: "same-origin", body: fd });
try { body = await res.json(); } catch (_) { body = null; } try { body = await res.json(); } catch (_) { body = null; }
} catch (err) { } catch (err) {
out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>"; out.innerHTML = '<p class="perf-notice is-warn">업로드 실패: ' + esc(err.message) + "</p>";
@@ -525,7 +606,7 @@
}); });
let res, body = null; let res, body = null;
try { try {
res = await fetch("/performance/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value), res = await fetch(BASE + "/api/ad-spend/upload?channel=" + encodeURIComponent(sel.value),
{ method: "POST", credentials: "same-origin", body: fd }); { method: "POST", credentials: "same-origin", body: fd });
try { body = await res.json(); } catch (_) { body = null; } try { body = await res.json(); } catch (_) { body = null; }
} catch (err) { } catch (err) {
@@ -561,7 +642,7 @@
let running = false; let running = false;
try { try {
let cur = null; let cur = null;
try { cur = (await api("GET", "/performance/api/ad-sync/current")).job; } catch (_) { cur = null; } try { cur = (await api("GET", BASE + "/api/ad-sync/current")).job; } catch (_) { cur = null; }
let job; let job;
if (cur && !cur.finished) { if (cur && !cur.finished) {
job = await runSyncWithProgress(null, "광고비 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur); job = await runSyncWithProgress(null, "광고비 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
@@ -569,7 +650,7 @@
const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today; const from = data.period_start, to = data.period_end < data.today ? data.period_end : data.today;
if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다."); if (from > data.today) throw new Error("앞으로의 기간은 가져올 수 없습니다.");
job = await runSyncWithProgress({ from: from, to: to }, "광고비 업데이트 " + from + " ~ " + to, null, job = await runSyncWithProgress({ from: from, to: to }, "광고비 업데이트 " + from + " ~ " + to, null,
"/performance/api/ad-sync"); BASE + "/api/ad-sync");
} }
running = !!(job && !job.finished); running = !!(job && !job.finished);
const ok = [], bad = [], other = []; const ok = [], bad = [], other = [];
@@ -618,7 +699,7 @@
const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true }); const m = openModal(name + " 광고 보고서 · " + (data.period_label || ""), { wide: true });
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>'; m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
try { try {
const res = await api("GET", "/performance/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" + const res = await api("GET", BASE + "/api/ad-spend/" + encodeURIComponent(code) + "/details?from=" +
encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end)); encodeURIComponent(data.period_start) + "&to=" + encodeURIComponent(data.period_end));
if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; } if (!res.rows || !res.rows.length) { m.body.innerHTML = '<p class="perf-muted">이 기간 보고서 자료가 없습니다(파일 업로드 또는 광고 API 불러오기).</p>'; return; }
const cols = res.columns || []; const cols = res.columns || [];
@@ -707,7 +788,7 @@
try { try {
// 이미 돌고 있는 업데이트(다른 사람·자동 업데이트 포함)가 있으면 새로 시작하지 않고 그 진행 창을 다시 연다 // 이미 돌고 있는 업데이트(다른 사람·자동 업데이트 포함)가 있으면 새로 시작하지 않고 그 진행 창을 다시 연다
let cur = null; let cur = null;
try { cur = (await api("GET", "/performance/api/sync/current")).job; } catch (_) { cur = null; } try { cur = (await api("GET", BASE + "/api/sync/current")).job; } catch (_) { cur = null; }
let job; let job;
if (cur && !cur.finished) { if (cur && !cur.finished) {
job = await runSyncWithProgress(null, "매출 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur); job = await runSyncWithProgress(null, "매출 업데이트 진행 상황 " + (cur.from || "") + " ~ " + (cur.to || ""), cur);
@@ -792,7 +873,7 @@
}, 120); }, 120);
} }
function saveManual(td, text) { function saveManual(td, text) {
const raw = String(text || "").replace(/[,\s원]/g, "").replace(/^=/, ""); const raw = String(text || "").replace(/[,\s원]|RM/gi, "").replace(/^=/, "");
if (raw !== "" && !/^[-+*/().\d×÷xX]+$/.test(raw)) { if (raw !== "" && !/^[-+*/().\d×÷xX]+$/.test(raw)) {
return Promise.reject(new Error("숫자 또는 1000+2000 같은 계산식만 입력하세요.")); return Promise.reject(new Error("숫자 또는 1000+2000 같은 계산식만 입력하세요."));
} }
@@ -801,7 +882,7 @@
return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" + return api("PUT", MANUAL_API + encodeURIComponent(td.dataset.manualCode) + "/" +
encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : raw }); encodeURIComponent(td.dataset.date), { amount: raw === "" ? null : raw });
}).then(function (res) { }).then(function (res) {
const manual = res.manual == null ? "" : String(res.manual); const manual = res.manual == null ? "" : CENTS ? (res.manual / 100).toFixed(2) : String(res.manual);
td.dataset.manualValue = manual; td.dataset.manualValue = manual;
if (res.formula) td.dataset.formula = res.formula; else delete td.dataset.formula; if (res.formula) td.dataset.formula = res.formula; else delete td.dataset.formula;
td.classList.toggle("is-manual", manual !== ""); td.classList.toggle("is-manual", manual !== "");
@@ -897,7 +978,7 @@
td.classList.toggle("has-memo", !!memo); td.classList.toggle("has-memo", !!memo);
} }
async function saveMemo(td, memo) { async function saveMemo(td, memo) {
const res = await api("PUT", "/performance/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" + const res = await api("PUT", BASE + "/api/cell-memos/" + encodeURIComponent(MEMO_KIND) + "/" +
encodeURIComponent(td.dataset.memoCode) + "/" + encodeURIComponent(td.dataset.date), { memo: memo }); encodeURIComponent(td.dataset.memoCode) + "/" + encodeURIComponent(td.dataset.date), { memo: memo });
setCellMemo(td, res.memo || ""); setCellMemo(td, res.memo || "");
} }
@@ -974,7 +1055,7 @@
const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이 const m = openModal(title, { wide: true }); // 넓은 창 + 상품명 줄바꿈 → 가로 스크롤 없이
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>'; m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
try { try {
const res = await api("GET", "/performance/api/events?code=" + encodeURIComponent(code) + const res = await api("GET", BASE + "/api/events?code=" + encodeURIComponent(code) +
"&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to)); "&from=" + encodeURIComponent(from) + "&to=" + encodeURIComponent(to));
const rows = res.rows || []; const rows = res.rows || [];
if (!rows.length) { m.body.innerHTML = '<p class="perf-muted">내역이 없습니다.</p>'; return; } if (!rows.length) { m.body.innerHTML = '<p class="perf-muted">내역이 없습니다.</p>'; return; }
@@ -1072,7 +1153,7 @@
const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7); const x = L + i * bw + bw * 0.15, w = Math.max(1, bw * 0.7);
const y0 = y(0), y1 = y(v); const y0 = y(0), y1 = y(v);
g += '<rect class="bar' + (v < 0 ? " is-neg" : "") + '" x="' + x + '" y="' + Math.min(y0, y1) + g += '<rect class="bar' + (v < 0 ? " is-neg" : "") + '" x="' + x + '" y="' + Math.min(y0, y1) +
'" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + fmt(v) + "원</title></rect>"; '" width="' + w + '" height="' + Math.max(0.5, Math.abs(y1 - y0)) + '"><title>' + esc(p.label) + " " + money(v) + " " + CUR + "</title></rect>";
if (i % every === 0) g += '<text x="' + (L + i * bw + bw / 2) + '" y="' + (H - 8) + '" text-anchor="middle">' + esc(p.label) + "</text>"; if (i % every === 0) g += '<text x="' + (L + i * bw + bw / 2) + '" y="' + (H - 8) + '" text-anchor="middle">' + esc(p.label) + "</text>";
}); });
g += '<line class="axis" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(0) + '" y2="' + y(0) + '"/>'; g += '<line class="axis" x1="' + L + '" x2="' + (W - R) + '" y1="' + y(0) + '" y2="' + y(0) + '"/>';
@@ -1092,8 +1173,8 @@
const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV); const w = Math.max(0, (W - L - R) * Math.max(0, v) / maxV);
const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0"; const pct = total > 0 ? (Math.max(0, v) / total * 100).toFixed(1) : "0.0";
g += '<text x="' + (L - 8) + '" y="' + (y + 14) + '" text-anchor="end">' + esc(r.name) + "</text>" + g += '<text x="' + (L - 8) + '" y="' + (y + 14) + '" text-anchor="end">' + esc(r.name) + "</text>" +
'<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + fmt(v) + "원</title></rect>" + '<rect class="bar" x="' + L + '" y="' + (y + 4) + '" width="' + w + '" height="13"><title>' + esc(r.name) + " " + money(v) + " " + CUR + "</title></rect>" +
'<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + fmt(v) + " (" + pct + "%)</text>"; '<text x="' + (L + w + 6) + '" y="' + (y + 14) + '">' + money(v) + " (" + pct + "%)</text>";
}); });
box.innerHTML = svg(W, H, g); box.innerHTML = svg(W, H, g);
} }
@@ -1138,7 +1219,7 @@
if (pending || asking || document.hidden) return; if (pending || asking || document.hidden) return;
asking = true; asking = true;
try { try {
const st = await api("GET", "/performance/api/update-status?kind=" + encodeURIComponent(w.kind)); const st = await api("GET", BASE + "/api/update-status?kind=" + encodeURIComponent(w.kind));
if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); } if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); }
} catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; } } catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; }
} }
@@ -1277,7 +1358,7 @@
} }
save.disabled = true; save.disabled = true;
try { try {
const res = await api("PUT", "/performance/api/auto-sync-schedule", payload); const res = await api("PUT", BASE + "/api/auto-sync-schedule", payload);
rows.forEach(function (row) { rows.forEach(function (row) {
const r = res[row.dataset.kind]; const r = res[row.dataset.kind];
if (!r) return; if (!r) return;
@@ -1299,7 +1380,7 @@
b.addEventListener("click", async function () { b.addEventListener("click", async function () {
const u = b.dataset.unit; const u = b.dataset.unit;
try { try {
await api("PUT", "/performance/api/display-unit", { unit: u }); await api("PUT", BASE + "/api/display-unit", { unit: u });
} catch (err) { } catch (err) {
alertMsg("저장 실패: " + err.message); alertMsg("저장 실패: " + err.message);
return; return;
@@ -1321,7 +1402,7 @@
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) { root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) {
b.addEventListener("click", function () { b.addEventListener("click", function () {
const v = b.dataset.colw; const v = b.dataset.colw;
document.cookie = "perf_colw=" + v + "; path=/performance; max-age=31536000; SameSite=Lax"; document.cookie = "perf_colw=" + v + "; path=" + BASE + "; max-age=31536000; SameSite=Lax";
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) { root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) {
x.classList.toggle("is-active", x === b); x.classList.toggle("is-active", x === b);
x.setAttribute("aria-checked", x === b ? "true" : "false"); x.setAttribute("aria-checked", x === b ? "true" : "false");
@@ -1344,7 +1425,7 @@
c.addEventListener("change", function () { c.addEventListener("change", function () {
const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; }); const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; });
hideSave = hideSave.then(function () { hideSave = hideSave.then(function () {
return api("PUT", "/performance/api/hidden-marketplaces", { codes: codes }); return api("PUT", BASE + "/api/hidden-marketplaces", { codes: codes });
}).catch(function (err) { }).catch(function (err) {
c.checked = !c.checked; c.checked = !c.checked;
alertMsg("저장 실패: " + err.message); alertMsg("저장 실패: " + err.message);
@@ -1361,7 +1442,7 @@
payload[box.dataset.field] = box.checked; payload[box.dataset.field] = box.checked;
box.disabled = true; box.disabled = true;
try { try {
await api("PUT", "/performance/api/marketplaces/" + tr.dataset.code, payload); await api("PUT", BASE + "/api/marketplaces/" + tr.dataset.code, payload);
} catch (err) { } catch (err) {
box.checked = !box.checked; box.checked = !box.checked;
alertMsg("저장 실패: " + err.message); alertMsg("저장 실패: " + err.message);
@@ -1375,12 +1456,12 @@
const tr = btn.closest("tr"); const tr = btn.closest("tr");
const code = tr.dataset.code, name = tr.dataset.name; const code = tr.dataset.code, name = tr.dataset.name;
// 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰 // 광고 API 연동 줄(data-api="ad-sources")은 /performance/api/ad-sources/…, 나머지는 쇼핑몰
const base = "/performance/api/" + (tr.dataset.api || "marketplaces") + "/"; const base = BASE + "/api/" + (tr.dataset.api || "marketplaces") + "/";
if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1"); if (btn.dataset.act === "rate") openRate(code, name, btn.dataset.hasHistory === "1");
else if (btn.dataset.act === "creds") openCreds(code, name, base); else if (btn.dataset.act === "creds") openCreds(code, name, base);
else if (btn.dataset.act === "test") runTest(code, name, btn, base); else if (btn.dataset.act === "test") runTest(code, name, btn, base);
else if (btn.dataset.act === "rename") openName(tr.dataset.group ? "그룹 이름 변경" : "쇼핑몰 이름 변경", name, function (v) { else if (btn.dataset.act === "rename") openName(tr.dataset.group ? "그룹 이름 변경" : "쇼핑몰 이름 변경", name, function (v) {
return api("PUT", "/performance/api/marketplaces/" + code, { name: v }); return api("PUT", BASE + "/api/marketplaces/" + code, { name: v });
}); });
else if (btn.dataset.act === "delete") deleteCustom(code, name, !!tr.dataset.group); else if (btn.dataset.act === "delete") deleteCustom(code, name, !!tr.dataset.group);
}); });
@@ -1408,22 +1489,22 @@
} }
const addShop = document.getElementById("perf-add-shop"); const addShop = document.getElementById("perf-add-shop");
if (addShop) addShop.addEventListener("click", function () { if (addShop) addShop.addEventListener("click", function () {
openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "shop", name: v }); }); openName("쇼핑몰 추가(수동 입력)", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "shop", name: v }); });
}); });
const addGroup = document.getElementById("perf-add-group"); const addGroup = document.getElementById("perf-add-group");
if (addGroup) addGroup.addEventListener("click", function () { if (addGroup) addGroup.addEventListener("click", function () {
openName("그룹 추가", "", function (v) { return api("POST", "/performance/api/marketplaces", { kind: "group", name: v }); }); openName("그룹 추가", "", function (v) { return api("POST", BASE + "/api/marketplaces", { kind: "group", name: v }); });
}); });
async function deleteCustom(code, name, isGroup) { async function deleteCustom(code, name, isGroup) {
let msg; let msg;
if (isGroup) msg = "그룹 [" + name + "]을 삭제할까요? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다."; if (isGroup) msg = "그룹 [" + name + "]을 삭제할까요? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다.";
else { else {
let days = 0; let days = 0;
try { days = (await api("GET", "/performance/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ } try { days = (await api("GET", BASE + "/api/marketplaces/" + code + "/manual-days")).days || 0; } catch (_) { /* 확인 문구만 */ }
msg = "쇼핑몰 [" + name + "]을 삭제할까요?" + (days ? " 입력해 둔 매출 " + fmt(days) + "일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다." : ""); msg = "쇼핑몰 [" + name + "]을 삭제할까요?" + (days ? " 입력해 둔 매출 " + fmt(days) + "일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다." : "");
} }
if (!(await confirmMsg(msg))) return; if (!(await confirmMsg(msg))) return;
try { await api("DELETE", "/performance/api/marketplaces/" + code); location.reload(); } try { await api("DELETE", BASE + "/api/marketplaces/" + code); location.reload(); }
catch (err) { alertMsg("삭제 실패: " + err.message); } catch (err) { alertMsg("삭제 실패: " + err.message); }
} }
root.querySelectorAll("select[data-act-group]").forEach(function (sel) { root.querySelectorAll("select[data-act-group]").forEach(function (sel) {
@@ -1431,7 +1512,7 @@
sel.addEventListener("change", async function () { sel.addEventListener("change", async function () {
sel.disabled = true; sel.disabled = true;
try { try {
await api("PUT", "/performance/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value }); await api("PUT", BASE + "/api/marketplaces/" + sel.closest("tr").dataset.code, { parent_code: sel.value });
location.reload(); // 행이 그룹 아래로(또는 밖으로) 옮겨 그려진다 location.reload(); // 행이 그룹 아래로(또는 밖으로) 옮겨 그려진다
} catch (err) { sel.value = before; sel.disabled = false; alertMsg("저장 실패: " + err.message); } } catch (err) { sel.value = before; sel.disabled = false; alertMsg("저장 실패: " + err.message); }
}); });
@@ -1469,7 +1550,7 @@
document.body.classList.remove("perf-dragging"); document.body.classList.remove("perf-dragging");
const order = currentOrder(); const order = currentOrder();
if (order.join(",") === start) return; if (order.join(",") === start) return;
try { await api("PUT", "/performance/api/marketplace-order", { codes: order }); } try { await api("PUT", BASE + "/api/marketplace-order", { codes: order }); }
catch (err) { await alertMsg("순서 저장 실패: " + err.message); location.reload(); } catch (err) { await alertMsg("순서 저장 실패: " + err.message); location.reload(); }
} }
document.addEventListener("pointermove", move); document.addEventListener("pointermove", move);
@@ -1514,7 +1595,7 @@
'</td><td><button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-del="' + r.id + '">삭제</button></td></tr>'; '</td><td><button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" data-del="' + r.id + '">삭제</button></td></tr>';
}).join("") + "</tbody></table>"; }).join("") + "</tbody></table>";
} }
try { renderHist((await api("GET", "/performance/api/marketplaces/" + code + "/rates")).rates || []); } try { renderHist((await api("GET", BASE + "/api/marketplaces/" + code + "/rates")).rates || []); }
catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; } catch (err) { m.body.querySelector("#perf-rate-hist").textContent = err.message; }
m.body.addEventListener("click", async function (e) { m.body.addEventListener("click", async function (e) {
@@ -1522,7 +1603,7 @@
if (!b) return; if (!b) return;
if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return; if (!(await confirmMsg("이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다."))) return;
try { try {
renderHist((await api("DELETE", "/performance/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []); renderHist((await api("DELETE", BASE + "/api/marketplaces/" + code + "/rates/" + b.dataset.del)).rates || []);
m.changed = true; m.changed = true;
} catch (err) { alertMsg(err.message); } } catch (err) { alertMsg(err.message); }
}); });
@@ -1530,7 +1611,7 @@
const rate = m.body.querySelector("#perf-rate-in").value.trim(); const rate = m.body.querySelector("#perf-rate-in").value.trim();
if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; } if (!rate) { m.body.querySelector("#perf-rate-in").focus(); return; }
try { try {
const res = await api("POST", "/performance/api/marketplaces/" + code + "/rates", { const res = await api("POST", BASE + "/api/marketplaces/" + code + "/rates", {
rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value, rate_percent: rate, effective_from: all.checked ? "2000-01-01" : from.value,
memo: m.body.querySelector("#perf-rate-memo").value, memo: m.body.querySelector("#perf-rate-memo").value,
}); });
@@ -1546,7 +1627,7 @@
// ── API 인증정보 ── // ── API 인증정보 ──
async function openCreds(code, name, base) { async function openCreds(code, name, base) {
base = base || "/performance/api/marketplaces/"; base = base || BASE + "/api/marketplaces/";
const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } }); const m = openModal(name + " API 설정", { narrow: true, onClose: function () { if (m.changed) location.reload(); } });
m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>'; m.body.innerHTML = '<p class="perf-muted">불러오는 중…</p>';
let info; let info;
@@ -1646,7 +1727,7 @@
const label = btn.textContent; const label = btn.textContent;
btn.textContent = "확인 중…"; btn.textContent = "확인 중…";
try { try {
const res = await api("POST", (base || "/performance/api/marketplaces/") + code + "/test", {}); const res = await api("POST", (base || BASE + "/api/marketplaces/") + code + "/test", {});
await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined); await alertMsg(name + " — " + (res.ok ? "정상 연결\n" : res.label + "\n") + res.message, res.ok ? { tone: "ok" } : undefined);
location.reload(); location.reload();
} catch (err) { } catch (err) {
@@ -1702,7 +1783,7 @@
if (gen) gen.addEventListener("click", async function () { if (gen) gen.addEventListener("click", async function () {
gen.disabled = true; gen.disabled = true;
try { try {
const res = await api("POST", "/performance/api/sample-data", { const res = await api("POST", BASE + "/api/sample-data", {
action: "generate", from: document.getElementById("perf-sample-from").value, action: "generate", from: document.getElementById("perf-sample-from").value,
to: document.getElementById("perf-sample-to").value, to: document.getElementById("perf-sample-to").value,
}); });
@@ -1714,7 +1795,7 @@
if (del) del.addEventListener("click", async function () { if (del) del.addEventListener("click", async function () {
if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return; if (!(await confirmMsg("테스트 데이터만 모두 삭제합니다. 실제 수집한 매출은 지우지 않습니다. 계속할까요?"))) return;
try { try {
const res = await api("POST", "/performance/api/sample-data", { action: "delete" }); const res = await api("POST", BASE + "/api/sample-data", { action: "delete" });
await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다."); await alertMsg("테스트 데이터 " + fmt(res.deleted) + "건을 삭제했습니다.");
location.reload(); location.reload();
} catch (err) { alertMsg(err.message); } } catch (err) { alertMsg(err.message); }
@@ -1723,7 +1804,7 @@
if (rekey) rekey.addEventListener("click", async function () { if (rekey) rekey.addEventListener("click", async function () {
if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return; if (!(await confirmMsg("예전 키로 암호화된 인증정보를 현재 키로 다시 암호화합니다. 계속할까요?"))) return;
try { try {
const res = await api("POST", "/performance/api/rekey"); const res = await api("POST", BASE + "/api/rekey");
await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : "")); await alertMsg("다시 암호화 " + res.reencrypted + "건" + (res.failed ? ", 실패 " + res.failed + "건(다시 입력 필요)" : ""));
location.reload(); location.reload();
} catch (err) { alertMsg(err.message); } } catch (err) { alertMsg(err.message); }
+128 -6
View File
@@ -7,7 +7,8 @@
"nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" }; "nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" };
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"]; const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
const FONT_DEFAULT = "system"; const FONT_DEFAULT = "system";
const SYS_DEFAULTS = { default_view: "board", board_cover: true }; // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게 // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게 — all_view_users null = Pro user 이상(후보 목록의 pro 표시)
const SYS_DEFAULTS = { default_view: "board", board_cover: true, all_view_users: null, daily_alert_times: ["09:00"] };
const form = document.getElementById("pj-options-form"); const form = document.getElementById("pj-options-form");
const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview"); const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview");
const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save"); const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save");
@@ -20,6 +21,15 @@
const cover = document.getElementById("pj-options-cover"); const cover = document.getElementById("pj-options-cover");
const views = form.elements.default_view || null; const views = form.elements.default_view || null;
const sysControls = [cover].concat(Array.from(views || [])).filter(Boolean); const sysControls = [cover].concat(Array.from(views || [])).filter(Boolean);
// "전체 보기" 메뉴 대상자 — 프로젝트 화면 분류(수퍼관리자·Admin 창에만)
const allPicker = document.getElementById("pj-options-allview");
const allBtn = document.getElementById("pj-options-allview-all");
const allCount = document.getElementById("pj-options-allview-count");
// 매일 하는 업무 알림 시각(여러 개) — 알림 분류(수퍼관리자·Admin 창에만)
const timesBox = document.getElementById("pj-options-daily-times");
const timesAdd = document.getElementById("pj-options-daily-add");
const TIMES_MAX = 12; // 서버 store.DAILY_ALERT_TIMES_MAX
let users = null; // 후보(project 권한자) — 못 읽었으면 null(그때는 대상자를 저장하지 않음)
const localControls = [select, cancel, closeX, reset]; const localControls = [select, cancel, closeX, reset];
let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장) let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장)
let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다 let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다
@@ -35,9 +45,88 @@
return data || {}; return data || {};
} }
function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; } function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; }
// 서버 응답 → 비교용 값. 대상자는 지금 후보에 있는 사람만, 설정 전(null)이면 Pro user 이상.
function sysFrom(o) {
return { default_view: o.default_view, board_cover: !!o.board_cover, all_view_users: resolveAllView(o.all_view_users),
daily_alert_times: (o.daily_alert_times || []).slice().sort() };
}
function timeBtns() { return timesBox ? Array.from(timesBox.querySelectorAll(".pj-time-btn")) : []; }
// 고른 시각들 — 빈 칸은 빼고 중복 제거·정렬(서버도 같게 정규화)
function pickedTimes() {
const out = [];
timeBtns().forEach(function (b) { const v = b.dataset.value || ""; if (v && out.indexOf(v) < 0) out.push(v); });
return out.sort();
}
function setTimeBtn(btn, v) {
btn.dataset.value = v || "";
btn.querySelector(".pj-time-text").textContent = v || "시각 선택";
btn.classList.toggle("is-empty", !v);
}
// 시각 고르기 = 프로젝트 공용 날짜 팝업 모양 시각 팝업(project.js openTimePopover — 옵션 창 안에 붙어 휠·클릭이 먹음)
function openTimePop(btn) {
if (!window.PJLib || !window.PJLib.openTimePopover) return;
window.PJLib.openTimePopover(btn, { value: btn.dataset.value || "", onChange: function (v) { setTimeBtn(btn, v); } });
}
function closeTimePop() { if (window.PJLib && window.PJLib.closeTimePopover) window.PJLib.closeTimePopover(); }
function renumberTimes() {
if (!timesBox) return;
Array.from(timesBox.children).forEach(function (li, i) { li.firstChild.textContent = "알림 " + (i + 1); });
timesAdd.disabled = !sys || timesBox.children.length >= TIMES_MAX;
}
function addTimeRow(v) {
const li = document.createElement("li");
li.innerHTML = '<span></span><button type="button" class="pj-time-btn" aria-label="알림 시각" title="시각 바꾸기">' +
'<span class="pj-time-text"></span><span class="material-symbols-outlined">schedule</span></button>' +
'<button type="button" class="pj-time-del" title="이 알림 빼기" aria-label="이 알림 빼기"><span class="material-symbols-outlined">delete</span></button>';
const tb = li.querySelector(".pj-time-btn"), del = li.querySelector(".pj-time-del");
setTimeBtn(tb, v);
tb.disabled = del.disabled = !sys;
tb.addEventListener("click", function () { if (document.querySelector(".pj-timepop")) closeTimePop(); else openTimePop(tb); });
del.addEventListener("click", function () { closeTimePop(); li.remove(); renumberTimes(); });
timesBox.appendChild(li);
renumberTimes();
return li;
}
function fillTimes(list) {
if (!timesBox) return;
closeTimePop();
timesBox.innerHTML = "";
(list || []).forEach(addTimeRow);
renumberTimes();
}
function resolveAllView(list) {
if (!users) return null;
return users.filter(function (u) { return list ? list.indexOf(u.email.toLowerCase()) >= 0 : u.pro; })
.map(function (u) { return u.email.toLowerCase(); }).sort();
}
function allBoxes() { return allPicker ? Array.from(allPicker.querySelectorAll("input[type=checkbox]")) : []; }
function pickedAllView() { return allBoxes().filter(function (b) { return b.checked; }).map(function (b) { return b.value.toLowerCase(); }).sort(); }
function paintAllView() {
if (!allPicker) return;
const boxes = allBoxes(), on = boxes.filter(function (b) { return b.checked; }).length;
const all = boxes.length > 0 && on === boxes.length;
allBtn.textContent = all ? "전체 해제" : "전체 선택";
allCount.textContent = users ? on + "명 / " + boxes.length + "명" : "";
}
function renderAllView() {
if (!allPicker) return;
const pick = window.PJLib && window.PJLib.memberPickHtml;
allPicker.innerHTML = (users || []).map(function (u) {
return pick ? pick(u) : '<label class="pj-member-pick"><input type="checkbox" value="' + u.email.replace(/"/g, "&quot;") + '"> ' +
u.name.replace(/[&<>"]/g, function (c) { return "&#" + c.charCodeAt(0) + ";"; }) + "</label>";
}).join("");
allPicker.querySelectorAll("label").forEach(function (l, i) { l.title = users[i].email; });
}
function fillSys(o) { function fillSys(o) {
if (views) views.value = o.default_view; if (views) views.value = o.default_view;
if (cover) cover.checked = o.board_cover; if (cover) cover.checked = o.board_cover;
fillTimes(o.daily_alert_times);
if (allPicker && users) {
const on = Array.isArray(o.all_view_users) ? o.all_view_users : resolveAllView(null);
allBoxes().forEach(function (b) { b.checked = on.indexOf(b.value.toLowerCase()) >= 0; });
}
paintAllView();
} }
function paint() { function paint() {
const font = names[select.value]; const font = names[select.value];
@@ -57,6 +146,11 @@
save.disabled = on; save.disabled = on;
localControls.forEach(function (c) { c.disabled = on; }); localControls.forEach(function (c) { c.disabled = on; });
sysControls.forEach(function (c) { c.disabled = on || !sys; }); sysControls.forEach(function (c) { c.disabled = on || !sys; });
allBoxes().concat(allBtn ? [allBtn] : []).forEach(function (c) { c.disabled = on || !sys || !users; });
if (timesBox) {
timesBox.querySelectorAll("input, button").forEach(function (c) { c.disabled = on || !sys; });
timesAdd.disabled = on || !sys || timesBox.children.length >= TIMES_MAX;
}
} }
function close() { if (!save.disabled) dialog.close(); } function close() { if (!save.disabled) dialog.close(); }
async function loadSys() { async function loadSys() {
@@ -64,9 +158,15 @@
const seq = ++openSeq; const seq = ++openSeq;
sys = null; busy(false); // 읽는 동안 시스템 칸은 잠금 sys = null; busy(false); // 읽는 동안 시스템 칸은 잠금
try { try {
const data = await request("GET"); // 대상자 후보는 따로 — 못 읽어도 처음 여는 탭·카드 표지는 저장할 수 있게
const people = allPicker ? fetch("/project/api/assignable-users").then(function (r) {
if (!r.ok) throw new Error(r.statusText); return r.json();
}).then(function (d) { return d.users || []; }).catch(function () { return null; }) : Promise.resolve(null);
const [data, list] = await Promise.all([request("GET"), people]);
if (seq !== openSeq) return; if (seq !== openSeq) return;
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover }; users = list; renderAllView();
if (allPicker && !users) setError('"전체 보기" 대상자 후보를 불러오지 못했습니다. 대상자는 저장되지 않습니다.');
sys = sysFrom(data.options);
fillSys(sys); fillSys(sys);
} catch (err) { } catch (err) {
if (seq !== openSeq) return; if (seq !== openSeq) return;
@@ -76,7 +176,7 @@
} }
button.addEventListener("click", function () { button.addEventListener("click", function () {
select.value = currentFont(); fillSys(SYS_DEFAULTS); paint(); setError(""); select.value = currentFont(); users = null; renderAllView(); fillSys(SYS_DEFAULTS); paint(); setError("");
showPane(tabs[0].dataset.pane); dialog.showModal(); tabs[0].focus(); showPane(tabs[0].dataset.pane); dialog.showModal(); tabs[0].focus();
loadSys(); loadSys();
}); });
@@ -92,6 +192,19 @@
showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true); showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true);
}); });
select.addEventListener("change", paint); select.addEventListener("change", paint);
if (timesAdd) timesAdd.addEventListener("click", function () {
if (timesBox.children.length >= TIMES_MAX) return;
const tb = addTimeRow("").querySelector(".pj-time-btn");
tb.focus(); openTimePop(tb);
});
if (allPicker) {
allPicker.addEventListener("change", paintAllView);
allBtn.addEventListener("click", function () {
const boxes = allBoxes(), all = boxes.every(function (b) { return b.checked; });
boxes.forEach(function (b) { b.checked = !all; });
paintAllView();
});
}
reset.addEventListener("click", function () { reset.addEventListener("click", function () {
select.value = FONT_DEFAULT; paint(); select.value = FONT_DEFAULT; paint();
if (sys) fillSys(SYS_DEFAULTS); if (sys) fillSys(SYS_DEFAULTS);
@@ -99,7 +212,7 @@
cancel.addEventListener("click", close); cancel.addEventListener("click", close);
closeX.addEventListener("click", close); closeX.addEventListener("click", close);
dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); }); dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); });
dialog.addEventListener("close", function () { openSeq++; button.focus(); }); dialog.addEventListener("close", function () { closeTimePop(); openSeq++; button.focus(); });
form.addEventListener("submit", async function (e) { form.addEventListener("submit", async function (e) {
e.preventDefault(); if (save.disabled) return; e.preventDefault(); if (save.disabled) return;
const fontValue = select.value, font = names[fontValue]; const fontValue = select.value, font = names[fontValue];
@@ -109,6 +222,14 @@
if (sys) { if (sys) {
if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value; if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value;
if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked; if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked;
if (timesBox) {
const t = pickedTimes();
if (t.join(",") !== sys.daily_alert_times.join(",")) sysChanges.daily_alert_times = t;
}
if (allPicker && users && sys.all_view_users) {
const picked = pickedAllView();
if (picked.join(",") !== sys.all_view_users.join(",")) sysChanges.all_view_users = picked;
}
} }
busy(true); setError(""); busy(true); setError("");
try { try {
@@ -119,12 +240,13 @@
const changed = Object.keys(sysChanges); const changed = Object.keys(sysChanges);
if (changed.length) { if (changed.length) {
const data = await request("PUT", sysChanges); const data = await request("PUT", sysChanges);
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover }; sys = sysFrom(data.options);
} }
if (fontValue !== currentFont()) changed.push("font"); if (fontValue !== currentFont()) changed.push("font");
localStorage.setItem("pj_font", fontValue); localStorage.setItem("pj_font", fontValue);
document.documentElement.dataset.pjFont = fontValue; document.documentElement.dataset.pjFont = fontValue;
// project.js 가 듣는다 — 보드 표지가 바뀌면 보던 보드를 다시 그린다(다른 사용자는 다음에 화면을 열 때부터). // project.js 가 듣는다 — 보드 표지가 바뀌면 보던 보드를 다시 그린다(다른 사용자는 다음에 화면을 열 때부터).
// "전체 보기" 메뉴 대상자는 다음에 화면을 열 때부터(왼쪽 메뉴는 서버가 그린다).
if (changed.length) { if (changed.length) {
window.dispatchEvent(new CustomEvent("pj-options-change", { window.dispatchEvent(new CustomEvent("pj-options-change", {
detail: { options: Object.assign({ font: fontValue }, sys || {}), changed: changed }, detail: { options: Object.assign({ font: fontValue }, sys || {}), changed: changed },
+49 -1
View File
@@ -2021,6 +2021,15 @@ img.pj-person-ic { width: 22px; height: 22px; }
/* 마감일 표기 색 — 오늘·내일 초록, 어제·지남 빨강(아사나) */ /* 마감일 표기 색 — 오늘·내일 초록, 어제·지남 빨강(아사나) */
.pj-card-due.is-soon, .pj-card-sub-due.is-soon, .pj-due-label.is-soon, .pj-due-btn.is-soon { color: #3f8f6b; } .pj-card-due.is-soon, .pj-card-sub-due.is-soon, .pj-due-label.is-soon, .pj-due-btn.is-soon { color: #3f8f6b; }
.pj-card-due.is-overdue, .pj-card-sub-due.is-overdue, .pj-due-label.is-overdue { color: #c22b10; } .pj-card-due.is-overdue, .pj-card-sub-due.is-overdue, .pj-due-label.is-overdue { color: #c22b10; }
/* 매일 하는 업무(033) — 마감일 자리에 반복 아이콘 + "매일"(업무 창 버튼은 JS 가 아이콘을 repeat 로) */
.pj-card-due.is-daily, .pj-card-sub-due.is-daily, .pj-due-label.is-daily, .pj-subtask-due.is-daily, .pj-due-btn.is-daily { color: #b07a00; }
.pj-card-due.is-daily::before, .pj-card-sub-due.is-daily::before, .pj-due-label.is-daily::before, .pj-subtask-due.is-daily::before {
content: "repeat"; font-family: "Material Symbols Outlined"; font-size: 1.15em; line-height: 1; vertical-align: -0.2em; margin-right: 2px;
font-feature-settings: "liga"; -webkit-font-smoothing: antialiased;
}
.pj-dp-daily { display: inline-flex; align-items: center; gap: 2px; }
.pj-dp-daily .material-symbols-outlined { font-size: 17px; }
.pj-dp-daily.is-on { background: #fff5d6; color: #b07a00; }
/* ── 멘션(@태그) ── */ /* ── 멘션(@태그) ── */
.pj-mention { .pj-mention {
@@ -3166,6 +3175,12 @@ input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
.pj-alert-kind { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 700; } .pj-alert-kind { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 700; }
.pj-alert-kind.is-mention { background: #eef2ff; color: #4053c8; } .pj-alert-kind.is-mention { background: #eef2ff; color: #4053c8; }
.pj-alert-kind.is-assigned { background: #e7f6ec; color: #1f8a4c; } .pj-alert-kind.is-assigned { background: #e7f6ec; color: #1f8a4c; }
/* 매일 하는 업무(033) 알림 — 줄 배경을 따로(노랑) */
.pj-alert-item.is-daily { background: #fff5d6; box-shadow: inset 3px 0 0 #f0a800; }
.pj-alert-item.is-daily + .pj-alert-item.is-daily { margin-top: 4px; }
.pj-alert-item.is-daily:hover { background: #ffedb8; }
.pj-alert-kind.is-daily { display: inline-flex; align-items: center; gap: 2px; background: #f0a800; color: #fff; }
.pj-alert-kind.is-daily .material-symbols-outlined { font-size: 14px; }
.pj-alert-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; } .pj-alert-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
.pj-alert-text b { font-size: 14.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pj-alert-text b { font-size: 14.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-alert-text small { color: var(--pj-ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pj-alert-text small { color: var(--pj-ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -3240,7 +3255,8 @@ html[data-pj-font="nanum-square"] { --pj-font: "NanumSquare", var(--pj-system-fo
html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); } html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); }
html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); } html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); }
/* ── Project 옵션 대화창(_options.html) — 데스크톱 프로그램 설정 창처럼 왼쪽 분류 | 오른쪽 설정 ── */ /* ── Project 옵션 대화창(_options.html) — 데스크톱 프로그램 설정 창처럼 왼쪽 분류 | 오른쪽 설정 ── */
.pj-options-dialog { width: min(720px, calc(100vw - 40px)); max-height: min(600px, calc(100vh - 40px)); box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; } /* 크기 고정 800×750(2026-11-11) — 화면이 그보다 작을 때만 줄어든다 */
.pj-options-dialog { width: min(800px, calc(100vw - 40px)); height: min(750px, calc(100vh - 40px)); max-width: none; max-height: none; box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; }
.pj-options-dialog[open] { display: flex; } .pj-options-dialog[open] { display: flex; }
.pj-options-dialog::backdrop { background: #0005; } .pj-options-dialog::backdrop { background: #0005; }
.pj-options-dialog form { display: flex; flex-direction: column; width: 100%; min-height: 0; } .pj-options-dialog form { display: flex; flex-direction: column; width: 100%; min-height: 0; }
@@ -3282,6 +3298,38 @@ label.pj-options-row[for] { cursor: pointer; }
.pj-options-views label:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; box-shadow: 0 0 0 1px var(--pj-accent) inset; } .pj-options-views label:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; box-shadow: 0 0 0 1px var(--pj-accent) inset; }
.pj-options-views label:has(input:checked) .material-symbols-outlined { color: var(--pj-accent); } .pj-options-views label:has(input:checked) .material-symbols-outlined { color: var(--pj-accent); }
.pj-options-views label:has(input:focus-visible) { outline: 2px solid var(--pj-accent); outline-offset: 2px; } .pj-options-views label:has(input:focus-visible) { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
/* 프로젝트 화면 — "전체 보기" 메뉴 대상자(아이콘+이름 체크, 멤버 배정 창과 같은 모양) */
.pj-options-allview-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.pj-options-allview-all { flex: none; white-space: nowrap; }
.pj-options-allview { max-height: 220px; margin-top: 0; }
/* 알림 — 매일 하는 업무 알림 시각(여러 개) */
.pj-options-times { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; }
.pj-options-times li { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.pj-options-times li > span:first-child { min-width: 52px; color: var(--pj-ink-soft); }
.pj-time-btn { display: inline-flex; align-items: center; gap: 8px; height: 36px; padding: 0 10px; border: 1px solid #d8dce2; border-radius: 8px; background: #fff; color: var(--pj-ink); font: inherit; font-size: 13.5px; font-variant-numeric: tabular-nums; cursor: pointer; }
.pj-time-btn:hover:not(:disabled) { border-color: #4573d2; }
.pj-time-btn:disabled { opacity: .6; cursor: default; }
.pj-time-btn .material-symbols-outlined { font-size: 18px; color: #6d6e6f; }
.pj-time-btn.is-empty .pj-time-text { color: #9aa1a9; }
.pj-options-times .pj-time-del { display: inline-flex; padding: 4px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; }
.pj-options-times .pj-time-del:hover { background: #fdecec; color: #b42318; }
/* 시각 고르기 팝업 — 날짜 팝업(.pj-datepop) 모양 그대로 + 시·분 두 열(돌아가지 않는 목록). popover(top layer) 기본값을 지운다. */
.pj-timepop { width: 200px; }
.pj-timepop[popover] { inset: auto; margin: 0; overflow: visible; }
.pj-tp-value { display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
.pj-tp-heads, .pj-tp-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.pj-tp-heads span { text-align: center; font-size: 12px; font-weight: 600; color: #6d6e6f; padding: 2px 0 4px; }
.pj-tp-col { height: 238px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; display: flex; flex-direction: column; gap: 2px; }
.pj-tp-item { flex: none; height: 32px; border: 0; border-radius: 16px; background: transparent; font: inherit; font-size: 13.5px; font-variant-numeric: tabular-nums; color: var(--pj-ink); cursor: pointer; }
.pj-tp-item:hover { background: #f1f2f4; }
.pj-tp-item.is-selected { background: #4573d2; color: #fff; font-weight: 600; }
.pj-timepop .pj-dp-link { transition: background .12s, color .12s; }
.pj-timepop .pj-dp-link[data-tp="clear"]:hover { background: #fdecec; color: #b42318; }
.pj-timepop .pj-dp-link[data-tp="ok"] { color: #4573d2; }
.pj-timepop .pj-dp-link[data-tp="ok"]:hover { background: #4573d2; color: #fff; }
.pj-timepop .pj-dp-link:active { transform: translateY(1px); }
.pj-options-times:empty::before { content: "알림 없음"; font-size: 12px; color: var(--pj-ink-soft); }
.pj-options-allview:empty::before { content: "불러오는 중…"; padding: 6px; font-size: 12px; color: var(--pj-ink-soft); }
/* 켜기/끄기 스위치 */ /* 켜기/끄기 스위치 */
.pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; } .pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; }
.pj-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; } .pj-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
+211 -45
View File
@@ -448,7 +448,9 @@
const a = new Date(String(iso).slice(0, 10) + "T00:00:00"), b = new Date(baseIso + "T00:00:00"); const a = new Date(String(iso).slice(0, 10) + "T00:00:00"), b = new Date(baseIso + "T00:00:00");
return Math.round((a - b) / 86400000); return Math.round((a - b) / 86400000);
} }
function dueInfo(iso, done) { // daily = 매일 하는 업무(033 repeat_daily) — 마감일 대신 반복 아이콘(CSS .is-daily::before) + "매일".
function dueInfo(iso, done, daily) {
if (daily) return { text: "매일", cls: "is-daily" };
if (!iso) return null; if (!iso) return null;
const diff = dayDiff(iso, isoToday()); const diff = dayDiff(iso, isoToday());
let text, cls = ""; let text, cls = "";
@@ -460,10 +462,11 @@
return { text: text, cls: cls }; return { text: text, cls: cls };
} }
// 마감일 칸 말풍선 — 지난 날짜(빨강)면 "마감일 지남", 아니면 "마감일 변경". // 마감일 칸 말풍선 — 지난 날짜(빨강)면 "마감일 지남", 아니면 "마감일 변경".
function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : "마감일 변경"; } function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : di && di.cls === "is-daily" ? "매일 하는 업무(눌러서 변경)" : "마감일 변경"; }
// ── 아사나식 날짜 팝업 — 마감일(과 선택적으로 시작일)을 월 달력에서 고른다. // ── 아사나식 날짜 팝업 — 마감일(과 선택적으로 시작일)을 월 달력에서 고른다.
// opts: { start, due, allowStart, onChange(patch) }. 날짜를 누를 때마다 // opts: { start, due, allowStart, daily, allowDaily, onChange(patch) }. allowDaily = 아래 [매일] 버튼(매일 하는 업무,
// 033) — 누르면 onChange({due_date: null, repeat_daily: true}) 하고 닫힘, 날짜를 고르면 repeat_daily: false. 날짜를 누를 때마다
// onChange({due_date[, start_date]}) 로 바로 저장하고, 마감일을 고르면 팝업을 // onChange({due_date[, start_date]}) 로 바로 저장하고, 마감일을 고르면 팝업을
// 닫는다(시작일을 고른 땐 마감일을 이어서 고르게 열어 둠). 바깥 클릭·Esc 로 닫힘. "지우기" = 둘 다 비우고 닫기. 앵커 아래(자리가 // 닫는다(시작일을 고른 땐 마감일을 이어서 고르게 열어 둠). 바깥 클릭·Esc 로 닫힘. "지우기" = 둘 다 비우고 닫기. 앵커 아래(자리가
// 없으면 위)에 뜨고 꼬리가 앵커를 가리킨다. 한 번에 하나만. // 없으면 위)에 뜨고 꼬리가 앵커를 가리킨다. 한 번에 하나만.
@@ -504,6 +507,7 @@
let start = opts.start ? String(opts.start).slice(0, 10) : ""; let start = opts.start ? String(opts.start).slice(0, 10) : "";
let due = opts.due ? String(opts.due).slice(0, 10) : ""; let due = opts.due ? String(opts.due).slice(0, 10) : "";
let showStart = !!(opts.allowStart && start); let showStart = !!(opts.allowStart && start);
let daily = !!(opts.allowDaily && opts.daily);
let active = "due"; let active = "due";
const base = new Date((due || start || today) + "T00:00:00"); const base = new Date((due || start || today) + "T00:00:00");
let viewY = base.getFullYear(), viewM = base.getMonth(); let viewY = base.getFullYear(), viewM = base.getMonth();
@@ -518,6 +522,7 @@
function emit() { function emit() {
const patch = { due_date: due || null }; const patch = { due_date: due || null };
if (opts.allowStart) patch.start_date = start || null; if (opts.allowStart) patch.start_date = start || null;
if (opts.allowDaily) patch.repeat_daily = daily;
if (opts.onChange) opts.onChange(patch); if (opts.onChange) opts.onChange(patch);
} }
function field(kind, val, ph) { function field(kind, val, ph) {
@@ -554,7 +559,7 @@
(opts.allowStart (opts.allowStart
? (showStart ? field("start", start, "시작일") : '<button type="button" class="pj-dp-addstart">+ 시작일</button>') ? (showStart ? field("start", start, "시작일") : '<button type="button" class="pj-dp-addstart">+ 시작일</button>')
: "") + : "") +
field("due", due, "마감일") + field("due", due, daily ? "매일 하는 업무" : "마감일") +
"</div>" + "</div>" +
'<div class="pj-dp-nav">' + '<div class="pj-dp-nav">' +
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' + '<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' +
@@ -569,6 +574,10 @@
"</div>" + "</div>" +
'<div class="pj-dp-foot">' + '<div class="pj-dp-foot">' +
'<button type="button" class="pj-dp-link pj-dp-today">오늘</button>' + '<button type="button" class="pj-dp-link pj-dp-today">오늘</button>' +
(opts.allowDaily
? '<button type="button" class="pj-dp-link pj-dp-daily' + (daily ? " is-on" : "") + '" title="마감일 없이 매일 하는 업무' +
(daily ? "(다시 누르면 해제)" : "") + '"><span class="material-symbols-outlined">repeat</span>매일</button>'
: "") +
'<button type="button" class="pj-dp-link pj-dp-clear">지우기</button>' + '<button type="button" class="pj-dp-link pj-dp-clear">지우기</button>' +
"</div>"; "</div>";
wire(); wire();
@@ -587,6 +596,7 @@
return; return;
} }
due = iso; due = iso;
daily = false;
if (start && start > iso) start = iso; if (start && start > iso) start = iso;
emit(); emit();
closeDatePopover(); closeDatePopover();
@@ -636,7 +646,13 @@
pick(today); pick(today);
}); });
pop.querySelector(".pj-dp-clear").addEventListener("click", function () { pop.querySelector(".pj-dp-clear").addEventListener("click", function () {
start = ""; due = ""; emit(); closeDatePopover(); start = ""; due = ""; daily = false; emit(); closeDatePopover();
});
const dailyBtn = pop.querySelector(".pj-dp-daily");
if (dailyBtn) dailyBtn.addEventListener("click", function () {
daily = !daily;
if (daily) due = "";
emit(); closeDatePopover();
}); });
} }
function focusActive() { function focusActive() {
@@ -741,6 +757,135 @@
sync(); sync();
} }
// ── 시각 고르기 팝업(2026-11-11, 프로젝트 공용 — Project 옵션 알림 시각·긴급 공지 띄울 시각) ──
// 날짜 팝업(.pj-datepop)과 같은 카드·꼬리·파란 선택. 시(00~23)·분(00~55, 5분 단위) 두 열 — 브라우저 기본
// 시계처럼 돌아가지 않고 끝에서 멈춘다. 시 = 바꾸고 열어 둠, 분 = 바꾸고 닫음, [확인] = 지금 값 넣고 닫기,
// [지우기] = 비우고 닫기. opts: { value: "HH:MM"|"", onChange(v) }.
// 모달 대화창(dialog[open]) 안의 칸이면 그 창 **안에** popover(top layer)로 붙인다 — 창 밖(body)에 붙이면
// 모달 때문에 inert 라 휠·마우스 오버·클릭이 안 먹는다. 그 밖에는 body(배율 .pj-ui-scale 밖).
let timePopEl = null, timePopCleanup = null;
function closeTimePopover() {
if (timePopCleanup) timePopCleanup();
timePopCleanup = null;
if (timePopEl) {
try { if (timePopEl.matches(":popover-open")) timePopEl.hidePopover(); } catch (_) {}
timePopEl.remove(); timePopEl = null;
}
}
function openTimePopover(anchor, opts) {
closeTimePopover();
const pad2 = function (n) { return (n < 10 ? "0" : "") + n; };
const cur = /^\d{2}:\d{2}/.test(opts.value || "") ? opts.value.slice(0, 5) : "";
let h = cur ? cur.slice(0, 2) : "", m = cur ? cur.slice(3, 5) : "";
const hours = [], mins = [];
for (let i = 0; i < 24; i++) hours.push(pad2(i));
for (let i = 0; i < 60; i += 5) mins.push(pad2(i));
function col(kind, list, sel) {
return '<div class="pj-tp-col" data-kind="' + kind + '">' + list.map(function (v) {
return '<button type="button" class="pj-tp-item' + (v === sel ? " is-selected" : "") + '" data-v="' + v + '">' + v + "</button>";
}).join("") + "</div>";
}
const pop = document.createElement("div");
pop.className = "pj-datepop pj-timepop";
pop.innerHTML = '<div class="pj-dp-fields"><span class="pj-dp-field is-active pj-tp-value"></span></div>' +
'<div class="pj-tp-heads"><span>시</span><span>분</span></div>' +
'<div class="pj-tp-cols">' + col("h", hours, h) + col("m", mins, m) + "</div>" +
'<div class="pj-dp-foot"><button type="button" class="pj-dp-link" data-tp="clear">지우기</button>' +
'<button type="button" class="pj-dp-link" data-tp="ok">확인</button></div>';
function paintHead() { pop.querySelector(".pj-tp-value").textContent = (h || "--") + ":" + (m || "--"); }
paintHead();
const host = anchor.closest("dialog[open]");
if (host) { pop.setAttribute("popover", "manual"); host.appendChild(pop); try { pop.showPopover(); } catch (_) {} }
else document.body.appendChild(pop);
function emit(v) { if (opts.onChange) opts.onChange(v); }
function commit() { if (h) emit(h + ":" + (m || "00")); }
pop.addEventListener("click", function (e) {
const it = e.target.closest(".pj-tp-item");
if (it) {
const kind = it.parentNode.dataset.kind;
it.parentNode.querySelectorAll(".is-selected").forEach(function (x) { x.classList.remove("is-selected"); });
it.classList.add("is-selected");
if (kind === "h") { h = it.dataset.v; if (!m) m = "00"; } else { m = it.dataset.v; if (!h) h = "09"; }
paintHead(); commit();
if (kind === "m") { closeTimePopover(); anchor.focus(); }
return;
}
const act = e.target.closest("[data-tp]");
if (!act) return;
if (act.dataset.tp === "clear") emit(""); else commit();
closeTimePopover(); anchor.focus();
});
// 자리 — 앵커 아래(자리 없으면 위), 꼬리가 앵커 가운데(openDatePopover place 와 같음).
// 배율(zoom) 안의 dialog 에 붙었으면 left/top 값도 배율만큼 줄어 보이므로 나눠 준다(currentCSSZoom).
const z = pop.currentCSSZoom || 1;
const r = anchor.getBoundingClientRect();
const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight;
const w = pop.offsetWidth * z, ph = pop.offsetHeight * z, ax = r.left + r.width / 2;
const left = Math.min(Math.max(8, ax - w / 2), vw - w - 8);
const below = r.bottom + 10 + ph <= vh - 8 || r.top - 10 - ph < 8;
pop.classList.toggle("is-above", !below);
pop.style.left = left / z + "px";
pop.style.top = (below ? r.bottom + 10 : r.top - 10 - ph) / z + "px";
pop.style.setProperty("--pj-dp-tail", Math.min(Math.max(ax - left, 16), w - 16) / z + "px");
// 고른 값이 보이게 — 열 안에서만 스크롤(맨 위 00 부터, 끝에서 멈춤)
pop.querySelectorAll(".pj-tp-col").forEach(function (c) {
const sel = c.querySelector(".is-selected");
if (sel) c.scrollTop = sel.offsetTop - c.offsetTop - (c.clientHeight - sel.offsetHeight) / 2;
});
function onDown(e) { if (!pop.contains(e.target) && !anchor.contains(e.target)) closeTimePopover(); }
function onKey(e) { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeTimePopover(); anchor.focus(); } }
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("keydown", onKey, true);
window.addEventListener("resize", closeTimePopover);
timePopEl = pop;
timePopCleanup = function () {
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("keydown", onKey, true);
window.removeEventListener("resize", closeTimePopover);
};
}
// <input type="time"> 를 시각 버튼으로 — 브라우저 기본 시계 대신 openTimePopover. input 은 숨긴 값 저장소
// (value 읽기/쓰기·change 이벤트 그대로, value 를 쓰면 버튼 글자도 바뀜 — enhanceDateInput 과 같은 방식).
function enhanceTimeInput(input, opts) {
if (!input || input.dataset.pjTime) return;
opts = opts || {};
input.dataset.pjTime = "1";
input.style.display = "none";
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pj-time-btn";
btn.innerHTML = '<span class="pj-time-text"></span><span class="material-symbols-outlined">schedule</span>';
if (input.getAttribute("aria-label")) btn.setAttribute("aria-label", input.getAttribute("aria-label"));
input.after(btn);
const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
Object.defineProperty(input, "value", {
configurable: true,
get: function () { return desc.get.call(this); },
set: function (v) { desc.set.call(this, v); sync(); },
});
function sync() {
const v = (input.value || "").slice(0, 5);
btn.querySelector(".pj-time-text").textContent = v || opts.placeholder || "시각 선택";
btn.classList.toggle("is-empty", !v);
btn.disabled = input.disabled;
btn.title = v ? "시각 변경" : "시각 지정";
}
btn.addEventListener("click", function (e) {
e.preventDefault();
if (timePopEl) { closeTimePopover(); return; }
openTimePopover(btn, {
value: input.value,
onChange: function (v) {
if ((input.value || "").slice(0, 5) === v) return;
input.value = v;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
},
});
});
sync();
}
// ── 탭 그룹(뷰 탭/스코프 토글, 둘 다 .pj-view-tabs 마크업 공유)에 슬라이드 // ── 탭 그룹(뷰 탭/스코프 토글, 둘 다 .pj-view-tabs 마크업 공유)에 슬라이드
// 하이라이트를 붙인다 — is-active 를 단순 배경색 대신, 실제 위치가 움직이는 // 하이라이트를 붙인다 — is-active 를 단순 배경색 대신, 실제 위치가 움직이는
// 절대배치 요소 하나로 표현한다. 탭 클릭·초기 렌더·리사이즈마다 위치 재계산. // 절대배치 요소 하나로 표현한다. 탭 클릭·초기 렌더·리사이즈마다 위치 재계산.
@@ -3230,8 +3375,8 @@
{ {
key: "due", label: "마감", cls: "pj-mtk-date", key: "due", label: "마감", cls: "pj-mtk-date",
html: function (t) { html: function (t) {
if (!t.due_date) return "-"; if (!t.due_date && !t.repeat_daily) return "-";
const di = dueInfo(t.due_date, !!t.completed_at); const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
return '<span class="pj-due-label ' + di.cls + (di.cls === "is-overdue" ? " pj-mtk-overdue" : "") + '">' + return '<span class="pj-due-label ' + di.cls + (di.cls === "is-overdue" ? " pj-mtk-overdue" : "") + '">' +
escapeHtml(di.text) + "</span>"; escapeHtml(di.text) + "</span>";
}, },
@@ -3479,6 +3624,8 @@
// 등급(2026-10-12) — isPro = Pro user 이상(프로젝트 수정·멤버 배정·전체 보기·담당자별 합계·남의 댓글 수정), // 등급(2026-10-12) — isPro = Pro user 이상(프로젝트 수정·멤버 배정·전체 보기·담당자별 합계·남의 댓글 수정),
// isPAdmin = Admin 이상(남이 만든 섹션도 삭제). // isPAdmin = Admin 이상(남이 만든 섹션도 삭제).
const isPro = root.dataset.isPro === "true"; const isPro = root.dataset.isPro === "true";
const canAllView = root.dataset.allView === "true";
const dailyReady = root.dataset.dailyReady === "1"; // 033 — 새 업무·세부 업무 추가 칸 날짜 팝업에도 [매일] // 왼쪽 "전체 보기" 메뉴 — Project 옵션 대상자(서버 pj_all_view)
const isPAdmin = root.dataset.isPadmin === "true"; const isPAdmin = root.dataset.isPadmin === "true";
// 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔. // 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔.
// 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래). // 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래).
@@ -3653,7 +3800,7 @@
const saved = localStorage.getItem(VIEW_KEY); const saved = localStorage.getItem(VIEW_KEY);
const preferred = root.dataset.defaultView; // 시스템 옵션(서버가 넣어 줌) const preferred = root.dataset.defaultView; // 시스템 옵션(서버가 넣어 줌)
if ((qs.has("y") || qs.has("m")) && saved && VIEWS.indexOf(saved) >= 0) currentView = saved; if ((qs.has("y") || qs.has("m")) && saved && VIEWS.indexOf(saved) >= 0) currentView = saved;
else if (isPro && qs.get("scope") === "all") currentView = "dashboard"; else if (canAllView && qs.get("scope") === "all") currentView = "dashboard";
else if (qs.get("embed") !== "1" && VIEWS.indexOf(preferred) >= 0) currentView = preferred; // 업무 창 패널(iframe)은 그대로 보드 else if (qs.get("embed") !== "1" && VIEWS.indexOf(preferred) >= 0) currentView = preferred; // 업무 창 패널(iframe)은 그대로 보드
} catch (_) {} } catch (_) {}
@@ -3815,7 +3962,7 @@
}); });
} }
if (moveScopeHighlight) moveScopeHighlight(false); if (moveScopeHighlight) moveScopeHighlight(false);
// 전체 보기(2026-10-08) — 오른쪽 위 토글 대신 왼쪽 메뉴 "전체 보기"(관리자만, ?scope=all). 토글은 숨겨 두고 상태만 쓴다. // 전체 보기(2026-10-08) — 오른쪽 위 토글 대신 왼쪽 메뉴 "전체 보기"(Project 옵션 대상자만, ?scope=all). 토글은 숨겨 두고 상태만 쓴다.
const allViewLink = el("pj-side-allview"); const allViewLink = el("pj-side-allview");
function applyAllScope(on) { function applyAllScope(on) {
viewScope = on ? "all" : "project"; viewScope = on ? "all" : "project";
@@ -3829,8 +3976,8 @@
r.classList.toggle("is-active", !on); r.classList.toggle("is-active", !on);
}); });
} }
if (isPro && new URLSearchParams(location.search).get("scope") === "all") applyAllScope(true); // 첫 그리기 전에 if (canAllView && new URLSearchParams(location.search).get("scope") === "all") applyAllScope(true); // 첫 그리기 전에
if (allViewLink && isPro) { if (allViewLink && canAllView) {
allViewLink.addEventListener("click", function (e) { allViewLink.addEventListener("click", function (e) {
if (e.ctrlKey || e.metaKey || e.shiftKey || e.button === 1) return; if (e.ctrlKey || e.metaKey || e.shiftKey || e.button === 1) return;
e.preventDefault(); // 같은 화면 안에서 바로 전환 e.preventDefault(); // 같은 화면 안에서 바로 전환
@@ -5101,9 +5248,10 @@
av.title = draft.assignee ? idOf(draft.assignee) : "담당자 지정"; av.title = draft.assignee ? idOf(draft.assignee) : "담당자 지정";
} }
function paintDue() { function paintDue() {
const di = dueInfo(draft.due, false); const di = dueInfo(draft.due, false, draft.daily);
due.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG; due.innerHTML = !di ? DUE_EMPTY_ICON_SVG
due.title = draft.due || "마감일 지정"; : draft.daily ? '<span class="pj-due-label is-daily">' + escapeHtml(di.text) + "</span>" : escapeHtml(di.text);
due.title = draft.daily ? "매일 하는 업무" : draft.due || "마감일 지정";
} }
function paintFol() { function paintFol() {
fol.innerHTML = followerIconHtml(draft.followers); fol.innerHTML = followerIconHtml(draft.followers);
@@ -5154,8 +5302,12 @@
}); });
due.addEventListener("click", function () { due.addEventListener("click", function () {
openDatePopover(due, { openDatePopover(due, {
due: draft.due, allowStart: false, due: draft.due, allowStart: false, daily: !!draft.daily, allowDaily: dailyReady,
onChange: function (patch) { if (!current()) return; draft.due = patch.due_date || null; paintDue(); refocus(); }, onChange: function (patch) {
if (!current()) return;
draft.due = patch.due_date || null; draft.daily = !!patch.repeat_daily;
paintDue(); refocus();
},
}); });
}); });
function close() { function close() {
@@ -5177,6 +5329,7 @@
assignee_email: draft.assignee, assignee_name: draft.assignee ? idOf(draft.assignee) : "", assignee_email: draft.assignee, assignee_name: draft.assignee ? idOf(draft.assignee) : "",
due_date: draft.due || null, due_date: draft.due || null,
followers: draft.followers, followers: draft.followers,
...(draft.daily ? { repeat_daily: true } : {}),
}); });
if (!current()) return; if (!current()) return;
mergeTask(res.task); mergeTask(res.task);
@@ -5715,7 +5868,8 @@
// 없으면 applyTaskPatch 로 업무에 저장. // 없으면 applyTaskPatch 로 업무에 저장.
function openDuePicker(t, anchorEl, onPick) { function openDuePicker(t, anchorEl, onPick) {
const save = onPick || function (patch) { applyTaskPatch(t, patch, "마감일 변경 실패"); }; const save = onPick || function (patch) { applyTaskPatch(t, patch, "마감일 변경 실패"); };
openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true, onChange: save }); openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true,
daily: !!t.repeat_daily, allowDaily: "repeat_daily" in t, onChange: save }); // repeat_daily 키 = 033 적용됨
} }
// ── 카드 세부 업무 펼치기(아사나처럼) — 카드의 "N ⤷ ▾" 버튼을 누르면 카드 // ── 카드 세부 업무 펼치기(아사나처럼) — 카드의 "N ⤷ ▾" 버튼을 누르면 카드
@@ -5735,7 +5889,7 @@
}); });
} }
function cardSubRowHtml(sub) { function cardSubRowHtml(sub) {
const di = dueInfo(sub.due_date, !!sub.completed_at); const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily);
return '<div class="pj-card-sub' + (sub.completed_at ? " is-done" : "") + '" data-sub-id="' + sub.id + '">' + return '<div class="pj-card-sub' + (sub.completed_at ? " is-done" : "") + '" data-sub-id="' + sub.id + '">' +
'<button type="button" class="pj-card-sub-check" title="' + (sub.completed_at ? "완료 취소" : "완료로 표시") + '">' + '<button type="button" class="pj-card-sub-check" title="' + (sub.completed_at ? "완료 취소" : "완료로 표시") + '">' +
'<span class="material-symbols-outlined">check_circle</span></button>' + '<span class="material-symbols-outlined">check_circle</span></button>' +
@@ -5743,7 +5897,7 @@
subMetaHtml(sub, "pj-card-sub-nsubs") + subMetaHtml(sub, "pj-card-sub-nsubs") +
// 마감일 — 있으면 날짜, 없으면 아사나처럼 점선 원 달력 아이콘(줄에 마우스를 // 마감일 — 있으면 날짜, 없으면 아사나처럼 점선 원 달력 아이콘(줄에 마우스를
// 올리면 보임). 둘 다 누르면 날짜 선택. // 올리면 보임). 둘 다 누르면 날짜 선택.
(sub.due_date (di
? '<span class="pj-card-sub-due ' + di.cls + '" data-tip="' + dueTip(di) + '">' + escapeHtml(di.text) + "</span>" ? '<span class="pj-card-sub-due ' + di.cls + '" data-tip="' + dueTip(di) + '">' + escapeHtml(di.text) + "</span>"
: '<span class="pj-card-sub-due is-empty" data-tip="마감일 추가">' + DUE_EMPTY_ICON_SVG + "</span>") + : '<span class="pj-card-sub-due is-empty" data-tip="마감일 추가">' + DUE_EMPTY_ICON_SVG + "</span>") +
// 담당자 — 있으면 아바타, 없으면 아사나처럼 점선 원 사람 아이콘(줄에 // 담당자 — 있으면 아바타, 없으면 아사나처럼 점선 원 사람 아이콘(줄에
@@ -6013,7 +6167,7 @@
if (!draft.followers) draft.followers = []; if (!draft.followers) draft.followers = [];
inp.value = draft.title; inp.value = draft.title;
function paintDue() { function paintDue() {
const di = dueInfo(draft.due, false); const di = dueInfo(draft.due, false, draft.daily);
dueEl.className = "pj-card-sub-due pj-card-subnew-due" + (di ? " " + di.cls : " is-empty"); dueEl.className = "pj-card-sub-due pj-card-subnew-due" + (di ? " " + di.cls : " is-empty");
dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG; dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG;
dueEl.dataset.tip = di ? dueTip(di) : "마감일 지정"; dueEl.dataset.tip = di ? dueTip(di) : "마감일 지정";
@@ -6040,7 +6194,7 @@
draft.focused = document.activeElement === inp; draft.focused = document.activeElement === inp;
// 날짜 팝업·담당자 메뉴를 쓰는 중이면 닫지 않는다. // 날짜 팝업·담당자 메뉴를 쓰는 중이면 닫지 않는다.
if (draft.focused || datePopEl || ctxMenuEl) return; if (draft.focused || datePopEl || ctxMenuEl) return;
if (!draft.title.trim() && !draft.due && !draft.assignee && !draft.followers.length) closeDraft(); if (!draft.title.trim() && !draft.due && !draft.daily && !draft.assignee && !draft.followers.length) closeDraft();
}, 150); }, 150);
}); });
inp.addEventListener("keydown", function (e) { inp.addEventListener("keydown", function (e) {
@@ -6050,9 +6204,9 @@
}); });
dueEl.addEventListener("click", function () { dueEl.addEventListener("click", function () {
openDatePopover(dueEl, { openDatePopover(dueEl, {
due: draft.due, allowStart: false, due: draft.due, allowStart: false, daily: !!draft.daily, allowDaily: dailyReady,
// 날짜를 고르면 팝업이 닫히므로 이어서 이름을 칠 수 있게 입력칸으로 돌아간다. // 날짜를 고르면 팝업이 닫히므로 이어서 이름을 칠 수 있게 입력칸으로 돌아간다.
onChange: function (patch) { draft.due = patch.due_date || null; paintDue(); refocus(); }, onChange: function (patch) { draft.due = patch.due_date || null; draft.daily = !!patch.repeat_daily; paintDue(); refocus(); },
}); });
}); });
// 바깥을 누르면 Enter 와 같다 — 이름이 있으면 만들고 줄을 닫는다(아사나). 이름이 없으면 // 바깥을 누르면 Enter 와 같다 — 이름이 있으면 만들고 줄을 닫는다(아사나). 이름이 없으면
@@ -6071,7 +6225,7 @@
if (subDrafts[t.id] !== draft) return; if (subDrafts[t.id] !== draft) return;
if (inp.isConnected) draft.title = inp.value; if (inp.isConnected) draft.title = inp.value;
if (draft.title.trim()) createFromDraft(false); if (draft.title.trim()) createFromDraft(false);
else if (!draft.due && !draft.assignee && !draft.followers.length) closeDraft(); else if (!draft.due && !draft.daily && !draft.assignee && !draft.followers.length) closeDraft();
}, 0); }, 0);
} }
if (subOutsideDown[t.id]) document.removeEventListener("pointerdown", subOutsideDown[t.id], true); if (subOutsideDown[t.id]) document.removeEventListener("pointerdown", subOutsideDown[t.id], true);
@@ -6120,6 +6274,7 @@
assignee_email: draft.assignee || "", assignee_email: draft.assignee || "",
assignee_name: draft.assignee ? idOf(draft.assignee) : "", assignee_name: draft.assignee ? idOf(draft.assignee) : "",
followers: draft.followers, followers: draft.followers,
...(draft.daily ? { repeat_daily: true } : {}),
}); });
const subs = subsCache[t.id] || (subsCache[t.id] = []); const subs = subsCache[t.id] || (subsCache[t.id] = []);
// 새 줄 협업자 아이콘 — 서버 자동 협업자와 같은 규칙(만든 사람·담당자·고른 협업자) // 새 줄 협업자 아이콘 — 서버 자동 협업자와 같은 규칙(만든 사람·담당자·고른 협업자)
@@ -6269,9 +6424,9 @@
// 누르면 서버에서 받아 멤버 메뉴. 한 번 받은(고른) 협업자는 이 화면에 머무는 동안 카드에 보인다(cardFollowers). // 누르면 서버에서 받아 멤버 메뉴. 한 번 받은(고른) 협업자는 이 화면에 머무는 동안 카드에 보인다(cardFollowers).
(canManage ? cardFolHtml(cardFollowers[t.id]) : "") + (canManage ? cardFolHtml(cardFollowers[t.id]) : "") +
(function () { (function () {
const di = dueInfo(t.due_date, !!t.completed_at); const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
return '<span class="pj-card-due pj-card-edit-hit' + (di ? " " + di.cls : " is-empty") + return '<span class="pj-card-due pj-card-edit-hit' + (di ? " " + di.cls : " is-empty") +
'" title="' + (t.due_date ? dueTip(di) : "마감일 추가") + '">' + '" title="' + (di ? dueTip(di) : "마감일 추가") + '">' +
// 마감일 없음 — 세부 업무 줄과 같은 점선 원 달력 아이콘만(카드에 마우스를 올리면 보임). // 마감일 없음 — 세부 업무 줄과 같은 점선 원 달력 아이콘만(카드에 마우스를 올리면 보임).
(di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG) + "</span>"; (di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG) + "</span>";
})() + })() +
@@ -6455,7 +6610,7 @@
{ key: "stage", label: "섹션", text: function (t) { return t.stage_name || "-"; }, sort: function (t) { return t.stage_name || ""; } }, { key: "stage", label: "섹션", text: function (t) { return t.stage_name || "-"; }, sort: function (t) { return t.stage_name || ""; } },
{ key: "priority", label: "우선순위", text: function (t) { return priorityLabels[t.priority] || t.priority || "-"; }, sort: function (t) { return ({ low: 0, normal: 1, high: 2 })[t.priority]; } }, { key: "priority", label: "우선순위", text: function (t) { return priorityLabels[t.priority] || t.priority || "-"; }, sort: function (t) { return ({ low: 0, normal: 1, high: 2 })[t.priority]; } },
{ key: "start", label: "시작", text: function (t) { return t.start_date || "-"; }, sort: function (t) { return t.start_date || ""; } }, { key: "start", label: "시작", text: function (t) { return t.start_date || "-"; }, sort: function (t) { return t.start_date || ""; } },
{ key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } }, { key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } },
]; ];
// "이 프로젝트" 스코프 — 아사나 리스트 뷰처럼 세션이 컬럼이 아니라 그룹 // "이 프로젝트" 스코프 — 아사나 리스트 뷰처럼 세션이 컬럼이 아니라 그룹
// 구분선이 된다(renderListGrouped). 그래서 세션 컬럼은 뺀다. // 구분선이 된다(renderListGrouped). 그래서 세션 컬럼은 뺀다.
@@ -6528,9 +6683,9 @@
tr.innerHTML = cols.map(function (c) { tr.innerHTML = cols.map(function (c) {
let inner = escapeHtml(String(c.text(t))); let inner = escapeHtml(String(c.text(t)));
if (c.key === "title") inner += cmtBadge(t); if (c.key === "title") inner += cmtBadge(t);
if (c.key === "due" && t.due_date) { if (c.key === "due" && (t.due_date || t.repeat_daily)) {
const di = dueInfo(t.due_date, !!t.completed_at); const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
inner = '<span class="pj-due-label ' + di.cls + '" title="' + t.due_date + '">' + escapeHtml(di.text) + "</span>"; inner = '<span class="pj-due-label ' + di.cls + '" title="' + (t.due_date || "매일 하는 업무") + '">' + escapeHtml(di.text) + "</span>";
} }
if (c.key === "assignee" && t.assignee_email) { if (c.key === "assignee" && t.assignee_email) {
inner = '<span class="pj-assignee">' + avatarHtml(t.assignee_email, "pj-gicon-sm") + escapeHtml(idOf(t.assignee_email)) + "</span>"; inner = '<span class="pj-assignee">' + avatarHtml(t.assignee_email, "pj-gicon-sm") + escapeHtml(idOf(t.assignee_email)) + "</span>";
@@ -7351,6 +7506,7 @@
body = { priority: el("pj-t-priority").value }; body = { priority: el("pj-t-priority").value };
} else if (key === "due") { } else if (key === "due") {
body = { due_date: el("pj-t-due").value || null }; body = { due_date: el("pj-t-due").value || null };
if (el("pj-t-due").dataset.daily) body.repeat_daily = el("pj-t-due").dataset.daily === "1";
} }
if (!body) return Promise.resolve(true); if (!body) return Promise.resolve(true);
setAutoState("saving"); setAutoState("saving");
@@ -7756,6 +7912,8 @@
: (presetStageId != null ? presetStageId : (stages[0] ? stages[0].id : "")); : (presetStageId != null ? presetStageId : (stages[0] ? stages[0].id : ""));
el("pj-t-priority").value = task ? (task.priority || "normal") : "normal"; el("pj-t-priority").value = task ? (task.priority || "normal") : "normal";
el("pj-t-due").value = task ? (task.due_date || "") : ""; el("pj-t-due").value = task ? (task.due_date || "") : "";
// 매일 하는 업무(033) — "" = 열 없음(미적용, [매일] 숨김), "0"/"1" = 꺼짐/켜짐
el("pj-t-due").dataset.daily = task && "repeat_daily" in task ? (task.repeat_daily ? "1" : "0") : "";
currentTaskData = task || null; currentTaskData = task || null;
syncDueBtn(); // 완료 여부(지남 표시)를 보려면 currentTaskData 다음에 syncDueBtn(); // 완료 여부(지남 표시)를 보려면 currentTaskData 다음에
el("pj-delete-task").hidden = !task; el("pj-delete-task").hidden = !task;
@@ -7872,12 +8030,16 @@
const v = el("pj-t-due").value; const v = el("pj-t-due").value;
const btn = el("pj-t-due-btn"); const btn = el("pj-t-due-btn");
if (!btn) return; if (!btn) return;
const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at)); const daily = el("pj-t-due").dataset.daily === "1";
const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at), daily);
el("pj-t-due-text").textContent = di ? di.text : ""; el("pj-t-due-text").textContent = di ? di.text : "";
btn.classList.toggle("has-date", !!v); btn.classList.toggle("has-date", !!di);
btn.classList.toggle("is-daily", daily);
const ic = btn.querySelector(".material-symbols-outlined");
if (ic) ic.textContent = daily ? "repeat" : "calendar_month";
btn.classList.toggle("is-overdue", !!di && di.cls === "is-overdue"); btn.classList.toggle("is-overdue", !!di && di.cls === "is-overdue");
btn.classList.toggle("is-soon", !!di && di.cls === "is-soon"); btn.classList.toggle("is-soon", !!di && di.cls === "is-soon");
btn.title = v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정"; btn.title = daily ? "매일 하는 업무 (눌러서 변경)" : v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정";
} }
if (el("pj-t-due-btn")) { if (el("pj-t-due-btn")) {
// 아사나식 날짜 팝업 — 숨긴 #pj-t-due 값을 바꾸고 change 를 보내면 // 아사나식 날짜 팝업 — 숨긴 #pj-t-due 값을 바꾸고 change 를 보내면
@@ -7885,9 +8047,10 @@
el("pj-t-due-btn").addEventListener("click", function () { el("pj-t-due-btn").addEventListener("click", function () {
const inp = el("pj-t-due"); const inp = el("pj-t-due");
openDatePopover(el("pj-t-due-btn"), { openDatePopover(el("pj-t-due-btn"), {
due: inp.value, allowStart: false, due: inp.value, allowStart: false, daily: inp.dataset.daily === "1", allowDaily: !!inp.dataset.daily,
onChange: function (patch) { onChange: function (patch) {
inp.value = patch.due_date || ""; inp.value = patch.due_date || "";
if ("repeat_daily" in patch) inp.dataset.daily = patch.repeat_daily ? "1" : "0";
inp.dispatchEvent(new Event("change", { bubbles: true })); inp.dispatchEvent(new Event("change", { bubbles: true }));
}, },
}); });
@@ -9546,10 +9709,10 @@
checkBtn.title = sub.completed_at ? "완료 취소" : "완료로 표시"; checkBtn.title = sub.completed_at ? "완료 취소" : "완료로 표시";
} }
function renderDue() { function renderDue() {
const di = dueInfo(sub.due_date, !!sub.completed_at); const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily);
dueEl.className = "pj-subtask-due" + (di ? " " + di.cls : " is-empty"); dueEl.className = "pj-subtask-due" + (di ? " " + di.cls : " is-empty");
dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG; dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG;
dueEl.title = sub.due_date ? dueTip(di) : "마감일 추가"; dueEl.title = di ? dueTip(di) : "마감일 추가";
} }
function renderAv() { function renderAv() {
const e = sub.assignee_email || ""; const e = sub.assignee_email || "";
@@ -9598,12 +9761,14 @@
dueEl.addEventListener("click", function (e) { dueEl.addEventListener("click", function (e) {
e.stopPropagation(); e.stopPropagation();
openDatePopover(dueEl, { openDatePopover(dueEl, {
due: sub.due_date, allowStart: false, due: sub.due_date, allowStart: false, daily: !!sub.repeat_daily, allowDaily: "repeat_daily" in sub,
onChange: async function (p) { onChange: async function (p) {
const prev = sub.due_date; const prev = { due_date: sub.due_date, repeat_daily: sub.repeat_daily };
sub.due_date = p.due_date || null; const body = { due_date: p.due_date || null };
if ("repeat_daily" in p) body.repeat_daily = p.repeat_daily;
Object.assign(sub, body);
renderDue(); renderDue();
if (!(await patch({ due_date: sub.due_date }))) { sub.due_date = prev; renderDue(); } if (!(await patch(body))) { Object.assign(sub, prev); renderDue(); }
}, },
}); });
}); });
@@ -13547,14 +13712,14 @@
"<b>새 알림 " + items.length + "건</b>" + "<b>새 알림 " + items.length + "건</b>" +
'<button type="button" class="pj-btn pj-btn-sm" data-alert-close>닫기</button></div>' + '<button type="button" class="pj-btn pj-btn-sm" data-alert-close>닫기</button></div>' +
'<div class="pj-alert-list">' + items.map(function (n) { '<div class="pj-alert-list">' + items.map(function (n) {
const isMention = n.type === "mention"; const isMention = n.type === "mention", isDaily = n.type === "daily"; // daily = 매일 하는 업무(033) — 줄 배경 따로
// 서버가 준 주소(작업 = /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 작업도 열린다) // 서버가 준 주소(작업 = /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 작업도 열린다)
const href = n.href || (n.task_id ? "/project/t/" + n.task_id const href = n.href || (n.task_id ? "/project/t/" + n.task_id
: n.project_id ? "/project/p/" + n.project_id : "/project/inbox"); : n.project_id ? "/project/p/" + n.project_id : "/project/inbox");
return '<a class="pj-alert-item" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' + return '<a class="pj-alert-item' + (isDaily ? " is-daily" : "") + '" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' +
'<span class="pj-alert-kind ' + (isMention ? "is-mention" : "is-assigned") + '">' + '<span class="pj-alert-kind ' + (isDaily ? "is-daily" : isMention ? "is-mention" : "is-assigned") + '">' +
(isMention ? "나를 태그" : "업무 배정") + "</span>" + (isDaily ? '<span class="material-symbols-outlined">repeat</span>매일 업무' : isMention ? "나를 태그" : "업무 배정") + "</span>" +
'<span class="pj-alert-text"><b>' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정):\s*/, "")) + "</b>" + '<span class="pj-alert-text"><b>' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정|매일 업무):\s*/, "")) + "</b>" +
"<small>" + escapeHtml((n.body || "") + (n.actor_email ? " · " + capName(idOf(n.actor_email)) : "")) + "</small></span>" + "<small>" + escapeHtml((n.body || "") + (n.actor_email ? " · " + capName(idOf(n.actor_email)) : "")) + "</small></span>" +
'<span class="pj-alert-go">열기 ›</span></a>'; '<span class="pj-alert-go">열기 ›</span></a>';
}).join("") + "</div>"; }).join("") + "</div>";
@@ -13573,6 +13738,7 @@
// 공용 말풍선만 켠다(프로젝트 알림 팝업 확인·실시간 동기화 등이 그 화면에서 돌지 않게). // 공용 말풍선만 켠다(프로젝트 알림 팝업 확인·실시간 동기화 등이 그 화면에서 돌지 않게).
window.PJLib = { window.PJLib = {
createDescEditor: createDescEditor, enhanceDateInput: enhanceDateInput, createDescEditor: createDescEditor, enhanceDateInput: enhanceDateInput,
enhanceTimeInput: enhanceTimeInput, openTimePopover: openTimePopover, closeTimePopover: closeTimePopover,
memberPickHtml: memberPickHtml, showToast: showToast, memberPickHtml: memberPickHtml, showToast: showToast,
}; };
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {
+1
View File
@@ -36,6 +36,7 @@ MODULE_KEYS: tuple[str, ...] = (
"project", "project",
"cafe24", "cafe24",
"performance", "performance",
"malaysia_performance",
"asset", "asset",
"inout", "inout",
"outreach", "outreach",
+6 -4
View File
@@ -225,13 +225,15 @@ namespace DbxNotifier
private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover) private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover)
{ {
float s = _s; float s = _s;
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8")); // 매일 하는 업무 = 노란 줄 배경(웹 팝업 .pj-alert-item.is-daily 와 같은 색)
if (a.IsDaily) Fill(g, r, 10 * s, Gfx.Hex(hover ? "#ffedb8" : "#fff5d6"));
else if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
string kind = a.IsMention ? "나를 태그" : "업무 배정"; string kind = a.IsDaily ? "매일 업무" : a.IsMention ? "나를 태그" : "업무 배정";
SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic); SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic);
var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s); var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s);
Fill(g, kr, 11 * s, a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec")); Fill(g, kr, 11 * s, a.IsDaily ? Gfx.Hex("#f0a800") : a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec"));
DrawText(g, kind, _fBadge, a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center); DrawText(g, kind, _fBadge, a.IsDaily ? Color.White : a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center);
const string go = "열기 ›"; const string go = "열기 ›";
SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic); SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic);
+2 -1
View File
@@ -20,13 +20,14 @@ namespace DbxNotifier
public long ProjectId; public long ProjectId;
public bool IsMention => Type == "mention"; public bool IsMention => Type == "mention";
public bool IsDaily => Type == "daily"; // 매일 하는 업무(project_db 033) — 줄 배경을 따로
/// <summary>제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary> /// <summary>제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle public string CleanTitle
{ {
get get
{ {
foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:" }) foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:", "매일 업무:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim(); if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title; return Title;
} }
+19 -1
View File
@@ -243,10 +243,20 @@ Admin API(OAuth)로는 스킨 파일을 읽거나 쓸 방법이 없다(`config.p
| 항목 | 값 | | 항목 | 값 |
| --- | --- | | --- | --- |
| 대표 이미지(썸네일) | 파일을 고르면 그 시각에 교체 / 안 고르면 변경 없음 (마이그레이션 006) |
| 상세페이지 HTML | 편집기 내용을 적용 / 적용 안 함 | | 상세페이지 HTML | 편집기 내용을 적용 / 적용 안 함 |
| 진열 | 진열 · 미진열 · 변경 없음 | | 진열 | 진열 · 미진열 · 변경 없음 |
| 판매 | 판매 · 중지 · 변경 없음 | | 판매 | 판매 · 중지 · 변경 없음 |
- **대표 이미지 예약**(2026-11-09): 예약 폼의 파일 칸(`name="image"`, 폼은 multipart). 검증은 즉시
교체와 같은 `_read_image`(JPG·PNG·GIF·WEBP, 10MB). 파일은 `cafe24_schedule_images`(BYTEA,
예약 삭제 시 CASCADE)에, 형식·파일명은 `cafe24_product_schedules.image_type/image_name` 에 둔다 —
worker 는 web 과 다른 컨테이너라 로컬 파일을 공유하지 않기 때문. worker 는 **이미지를 먼저**
`products.set_main_image`(즉시 교체와 같은 A 타입) 로 올리고 스냅샷을 남긴 뒤 상세페이지·진열/판매를
쓴다 — 뒤 단계 실패로 재시도되면 같은 이미지를 한 번 더 올릴 뿐이라 안전하다. 예약 목록에
`GET /cafe24/schedules/{id}/image` 미리보기 썸네일. 이미지 없는 예약 INSERT 는 006 컬럼을 쓰지
않아 마이그레이션 전에도 기존 예약 등록은 깨지지 않는다.
- **등록**은 편집기 아래 「예약 적용」에서 한다. HTML 을 적용하는 예약이면 그 시점의 - **등록**은 편집기 아래 「예약 적용」에서 한다. HTML 을 적용하는 예약이면 그 시점의
편집기 내용을 **DRAFT revision 으로 저장해 고정**한다 — 이후 편집기를 더 고쳐도 편집기 내용을 **DRAFT revision 으로 저장해 고정**한다 — 이후 편집기를 더 고쳐도
예약된 내용은 바뀌지 않는다(예약해둔 것이 조용히 달라지면 안 된다). 예약된 내용은 바뀌지 않는다(예약해둔 것이 조용히 달라지면 안 된다).
@@ -277,7 +287,7 @@ Admin API(OAuth)로는 스킨 파일을 읽거나 쓸 방법이 없다(`config.p
서버(`store.parse_schedule_at`)는 예전과 같은 형식을 받으므로 백엔드는 그대로다. 서버(`store.parse_schedule_at`)는 예전과 같은 형식을 받으므로 백엔드는 그대로다.
- **시각은 KST 로 해석**한다. 과거 시각은 거부하되 - **시각은 KST 로 해석**한다. 과거 시각은 거부하되
폼을 채우는 동안 시간이 흐른 경우를 위해 1분 여유를 둔다. 폼을 채우는 동안 시간이 흐른 경우를 위해 1분 여유를 둔다.
- **실행은 `app/modules/cafe24/worker.py`** — compose 서비스 `dbx-cafe24-worker` 가 - **실행은 `app/modules/cafe24/worker.py`** — compose 서비스 `cafe24-worker`(컨테이너 `dbx-cafe24-worker`)가
`--loop 60` 으로 돈다. 웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에 `--loop 60` 으로 돈다. 웹 요청 안에서 기다리는 방식은 프록시 타임아웃·재기동에
무너지므로 별도 프로세스여야 한다. 무너지므로 별도 프로세스여야 한다.
- worker 는 `claim_due_schedule` 로 **한 건씩 `FOR UPDATE SKIP LOCKED`** 로 잠그고 - worker 는 `claim_due_schedule` 로 **한 건씩 `FOR UPDATE SKIP LOCKED`** 로 잠그고
@@ -472,6 +482,13 @@ cafe24_oauth_tokens 저장
`quantity`, `image`…). `PUT /admin/products/{no}/variants` body `{"shop_no":1, `quantity`, `image`…). `PUT /admin/products/{no}/variants` body `{"shop_no":1,
"requests":[{variant_code, custom_variant_code, additional_amount, display, selling…}]}` "requests":[{variant_code, custom_variant_code, additional_amount, display, selling…}]}`
1회 100건(초과 시 나눠 보냄). 재고(`quantity`)는 이 화면에서 건드리지 않는다. 1회 100건(초과 시 나눠 보냄). 재고(`quantity`)는 이 화면에서 건드리지 않는다.
- **멀티쇼핑몰 진열·판매**(2026-11-10): 품목 진열·판매는 쇼핑몰(`shop_no`)마다 따로다. 화면은
기본몰(1) 값을 보여 주고, 저장하면 기본몰에 반영된 행의 **진열·판매만** `CAFE24_SHOP_NOS`
(예 `1,2,3`)의 다른 쇼핑몰에도 같은 값으로 PUT 한다. 추가금액(통화가 다름)·자체코드·순서는
기본몰만. 다른 쇼핑몰 실패는 응답 `shop_failed`·감사 기록에 남기고 화면에 경고(기본몰 반영은 유지).
쇼핑몰 목록 API(`/admin/shops`)는 `mall.read_store` 권한이 필요해 쓰지 않고 번호를 환경변수로 받는다.
기존 상품 일괄 맞춤(일회성): `docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags
--shops 3,4 [--apply]` — 없으면 미리보기, 출력 `BEFORE` 줄 = 원래 값(되돌리기용), 감사 actor `SYNC_SHOPS`.
- "옵션별 상품 이름" 은 옵션값(`option_text`)이고, "옵션별 썸네일" 은 `option_image_file` - "옵션별 상품 이름" 은 옵션값(`option_text`)이고, "옵션별 썸네일" 은 `option_image_file`
(+ `option_link_image` 에도 같은 경로) 이며, (+ `option_link_image` 에도 같은 경로) 이며,
화면의 옵션값 썸네일은 **`option_image_file` → `option_link_image` → 그 옵션값을 가진 화면의 옵션값 썸네일은 **`option_image_file` → `option_link_image` → 그 옵션값을 가진
@@ -559,6 +576,7 @@ CAFE24_REDIRECT_URI=https://dbx.no1king.freeddns.org/cafe24/oauth/callback
CAFE24_API_VERSION=2026-03-01 CAFE24_API_VERSION=2026-03-01
CAFE24_TOKEN_SECRET=<openssl rand -hex 32> CAFE24_TOKEN_SECRET=<openssl rand -hex 32>
CAFE24_SHOP_URL=https://www.miras.co.kr # 선택 — 다이렉트 주소용 커스텀 도메인 CAFE24_SHOP_URL=https://www.miras.co.kr # 선택 — 다이렉트 주소용 커스텀 도메인
CAFE24_SHOP_NOS=1,2,3 # 선택 — 품목 진열·판매를 같이 맞출 멀티쇼핑몰 번호(기본 1)
# 디자인 보관함 FTP (OAuth 와 별개 계정) — 모바일 스와이프 / PC·모바일 상품상세 # 디자인 보관함 FTP (OAuth 와 별개 계정) — 모바일 스와이프 / PC·모바일 상품상세
CAFE24_FTP_HOST=miraskitchen.ftp.cafe24.com # 선택 — 미설정 시 {mall_id}.ftp.cafe24.com CAFE24_FTP_HOST=miraskitchen.ftp.cafe24.com # 선택 — 미설정 시 {mall_id}.ftp.cafe24.com
+8 -2
View File
@@ -12,6 +12,7 @@
| `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 | | `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 |
| `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 | | `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 |
| `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 | | `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 |
| `malaysia_performance_db` | 말레이시아 실적(2026-11-20) — performance_db 와 **같은 표 구조**(구조만 복사), 틱톡·쇼피·라자다 쇼핑몰·라이브커머스 수동 매출·광고비. 금액 = 센(0.01 RM) 정수. 역할 `performance_app` 공유 |
| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004)/모듈 설정(물류센터 이메일)·입고 요청 메일 기록(005) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) | | `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004)/모듈 설정(물류센터 이메일)·입고 요청 메일 기록(005) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) |
--- ---
@@ -361,7 +362,8 @@ DDL: `scripts/sql/cafe24_db_init.sql` (멱등). DB·역할(`cafe24_app`)·테이
| `cafe24_oauth_tokens` | 쇼핑몰별 OAuth 토큰(`mall_id` UNIQUE). access/refresh 는 **Fernet 암호문**으로 저장. 상품관리 + 향후 주문관리가 공유 | | `cafe24_oauth_tokens` | 쇼핑몰별 OAuth 토큰(`mall_id` UNIQUE). access/refresh 는 **Fernet 암호문**으로 저장. 상품관리 + 향후 주문관리가 공유 |
| `cafe24_products` | 상품 캐시(`product_no` UNIQUE). 목록/검색 속도용이며 source of truth 는 언제나 카페24. `last_write_snapshot`(JSONB, 마이그레이션 004) 에 카페24 PUT 응답을 섹션별(`product`/`options`/`variants`)로 남겨 **읽기 지연**(PUT 뒤 GET 이 한동안 예전 값을 돌려줌) 동안 화면 기준으로 쓴다 | | `cafe24_products` | 상품 캐시(`product_no` UNIQUE). 목록/검색 속도용이며 source of truth 는 언제나 카페24. `last_write_snapshot`(JSONB, 마이그레이션 004) 에 카페24 PUT 응답을 섹션별(`product`/`options`/`variants`)로 남겨 **읽기 지연**(PUT 뒤 GET 이 한동안 예전 값을 돌려줌) 동안 화면 기준으로 쓴다 |
| `cafe24_product_revisions` | 상세페이지 HTML 버전(append-only). `revision_type` SYNC/DRAFT/**BACKUP**/MANUAL/SCHEDULED/ROLLBACK | | `cafe24_product_revisions` | 상세페이지 HTML 버전(append-only). `revision_type` SYNC/DRAFT/**BACKUP**/MANUAL/SCHEDULED/ROLLBACK |
| `cafe24_product_schedules` | 예약 작업. `status` PENDING/PROCESSING/SUCCESS/FAILED/CANCELLED, 재시도·자동종료·복원 대상 포함 | | `cafe24_product_schedules` | 예약 작업. `status` PENDING/PROCESSING/SUCCESS/FAILED/CANCELLED, 재시도·자동종료·복원 대상 포함. `image_type`/`image_name`(006) = 대표 이미지 교체 예약 |
| `cafe24_schedule_images` | 대표 이미지 예약 파일(BYTEA, 10MB 이하, 예약 삭제 시 CASCADE) — 마이그레이션 006 |
| `cafe24_audit_logs` | 누가 무엇을 바꿨나. worker 수행분은 `actor='SCHEDULER'` | | `cafe24_audit_logs` | 누가 무엇을 바꿨나. worker 수행분은 `actor='SCHEDULER'` |
| `cafe24_api_logs` | 카페24 API 호출 기록. **토큰/Authorization/client_secret 미기록** | | `cafe24_api_logs` | 카페24 API 호출 기록. **토큰/Authorization/client_secret 미기록** |
@@ -371,7 +373,7 @@ DDL: `scripts/sql/cafe24_db_init.sql` (멱등). DB·역할(`cafe24_app`)·테이
- 예약의 `restore_revision_id` 는 **예약 실행 순간** 만든 BACKUP 을 가리킨다(예약 생성 시점 값이 아님). - 예약의 `restore_revision_id` 는 **예약 실행 순간** 만든 BACKUP 을 가리킨다(예약 생성 시점 값이 아님).
- 일괄 예약은 상품 1건당 1행 + 공통 `parent_job_id` — 한 상품 실패가 나머지를 막지 않는다. - 일괄 예약은 상품 1건당 1행 + 공통 `parent_job_id` — 한 상품 실패가 나머지를 막지 않는다.
- 토큰 암호화 키는 `.env` 의 `CAFE24_TOKEN_SECRET`. **값을 바꾸면 기존 토큰을 복호화할 수 없어 카페24 재연결이 필요하다.** - 토큰 암호화 키는 `.env` 의 `CAFE24_TOKEN_SECRET`. **값을 바꾸면 기존 토큰을 복호화할 수 없어 카페24 재연결이 필요하다.**
- 기존 운영 DB 에는 마이그레이션 002·003·004 를 순서대로 적용한다(전부 멱등): - 기존 운영 DB 에는 마이그레이션 002·003·004·005·006 을 순서대로 적용한다(전부 멱등):
`docker exec -i postgres-db psql -U postgres -d cafe24_db < scripts/sql/cafe24_db_004_write_snapshot.sql` `docker exec -i postgres-db psql -U postgres -d cafe24_db < scripts/sql/cafe24_db_004_write_snapshot.sql`
### 운영 서버 초기화 (1회, 사용자 승인 후) ### 운영 서버 초기화 (1회, 사용자 승인 후)
@@ -394,6 +396,10 @@ cd /opt/www/main && docker compose up -d --build web
## performance_db 스키마 / 초기화 ## performance_db 스키마 / 초기화
> **012(2026-11-20) 틱톡 데이터 삭제** — `scripts/sql/performance_db_012_drop_tiktok.sql`(틱톡 탭 삭제, 백업 후·승인 후).
> **malaysia_performance_db** — 이 DB 구조를 `pg_dump --schema-only` 로 복사 + `scripts/sql/malaysia_performance_db_seed.sql`(쇼핑몰 9행).
> 앞으로 performance_db 마이그레이션(013~)은 **두 DB 모두에** 적용한다(같은 코드가 두 DB 를 읽음).
DDL: `scripts/sql/performance_db_init.sql` (멱등). DB·역할(`performance_app`)·테이블·인덱스·트리거·쇼핑몰 10곳 seed 를 DDL: `scripts/sql/performance_db_init.sql` (멱등). DB·역할(`performance_app`)·테이블·인덱스·트리거·쇼핑몰 10곳 seed 를
한 번에 생성. **JSON 폴백 없음** — `PERFORMANCE_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상세는 `docs/PERFORMANCE_MODULE.md`. 한 번에 생성. **JSON 폴백 없음** — `PERFORMANCE_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상세는 `docs/PERFORMANCE_MODULE.md`.
+11
View File
@@ -426,6 +426,16 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_032_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_032_link_sort_order.sql && docker compose up --build -d --no-deps web cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_032_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_032_link_sort_order.sql && docker compose up --build -d --no-deps web
``` ```
## 매일 하는 업무 마이그레이션 (project_db 033)
033은 `tasks` 에 `repeat_daily` 열(기본 false)과 부분 인덱스 하나만 추가한다(다시 실행 가능, 기존 값 변경 없음, 새 환경변수 없음).
날짜 팝업 [매일]·마감 칸 반복 아이콘·매일 업무 알림(Project 옵션 → 알림 시각, 영업일) — 미적용이면 앱은 예전 그대로([매일] 숨김, 알림 skip).
되돌리기 = `ALTER TABLE tasks DROP COLUMN repeat_daily;`(앱은 열이 없으면 예전 방식).
```bash
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_033_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_033_repeat_daily.sql && docker compose up --build -d --no-deps web
```
## 안내문 발송 DM 본문 저장 마이그레이션 (outreach_db 002) ## 안내문 발송 DM 본문 저장 마이그레이션 (outreach_db 002)
002는 `outreach_dm_bodies` 표 하나만 추가한다(다시 실행 가능, 기존 표·값 변경 없음, 새 환경변수 없음, `outreach_app` 에 CRUD·시퀀스 권한). 002는 `outreach_dm_bodies` 표 하나만 추가한다(다시 실행 가능, 기존 표·값 변경 없음, 새 환경변수 없음, `outreach_app` 에 CRUD·시퀀스 권한).
@@ -615,6 +625,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
| `ITEMCODE_DB_URL` | 상품 검색용 itemcode_db 읽기 전용 DSN. 미설정 시 검색 비활성(수동 입력). 테이블/컬럼은 `ITEMCODE_TABLE`/`ITEMCODE_CODE_COL`/`ITEMCODE_NAME_COL`/`ITEMCODE_TYPE_COL` 또는 `ITEMCODE_SEARCH_SQL` 로 지정 | | `ITEMCODE_DB_URL` | 상품 검색용 itemcode_db 읽기 전용 DSN. 미설정 시 검색 비활성(수동 입력). 테이블/컬럼은 `ITEMCODE_TABLE`/`ITEMCODE_CODE_COL`/`ITEMCODE_NAME_COL`/`ITEMCODE_TYPE_COL` 또는 `ITEMCODE_SEARCH_SQL` 로 지정 |
| `DATA_DIR` | 영구 데이터 경로 (Docker 볼륨 마운트). 첨부파일은 `$DATA_DIR/uploads/expense/{item_id}/` 에 저장 | | `DATA_DIR` | 영구 데이터 경로 (Docker 볼륨 마운트). 첨부파일은 `$DATA_DIR/uploads/expense/{item_id}/` 에 저장 |
| `PERFORMANCE_DB_URL` | 실적 DB DSN (예: `postgresql://performance_app:<pwd>@postgres-db:5432/performance_db`). **필수** — 미설정 시 실적 모듈 비활성(설정 필요 안내). 권한키 `performance` | | `PERFORMANCE_DB_URL` | 실적 DB DSN (예: `postgresql://performance_app:<pwd>@postgres-db:5432/performance_db`). **필수** — 미설정 시 실적 모듈 비활성(설정 필요 안내). 권한키 `performance` |
| `MALAYSIA_PERFORMANCE_DB_URL` | 말레이시아 실적 DB DSN (예: `postgresql://performance_app:<pwd>@postgres-db:5432/malaysia_performance_db`, 역할은 실적과 공유). 미설정 시 말레이시아 실적만 "설정 필요" 안내. 만들기 = `scripts/sql/malaysia_performance_db_seed.sql` 머리말. 권한키 `malaysia_performance` |
| `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 | | `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 |
| `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) | | `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) |
| `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) | | `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) |
+3 -1
View File
@@ -26,6 +26,7 @@
| 안내문 발송 | 리스트(이메일·인스타 주소 + 이름)에 `{이름}`을 넣은 안내문 — 메일 일괄 발송(보내는 사람 본인 Gmail)·인스타 DM 반자동(문구 복사 + DM 창) (`app/modules/outreach/`, `outreach_db`) | | 안내문 발송 | 리스트(이메일·인스타 주소 + 이름)에 `{이름}`을 넣은 안내문 — 메일 일괄 발송(보내는 사람 본인 Gmail)·인스타 DM 반자동(문구 복사 + DM 창) (`app/modules/outreach/`, `outreach_db`) |
| 라이브 커머스 | 말레이시아 라이브 방송의 호스트 정보(설정)와 스케줄표(호스트·날짜·시간·판매금액·장소·결과 이미지) (`app/modules/live/`, `live_db`) | | 라이브 커머스 | 말레이시아 라이브 방송의 호스트 정보(설정)와 스케줄표(호스트·날짜·시간·판매금액·장소·결과 이미지) (`app/modules/live/`, `live_db`) |
| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` | | 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
| 말레이시아 실적 | 틱톡·쇼피·라자다 쇼핑몰·라이브커머스 매출(RM)·광고비 수동 입력 (`app/modules/malaysia_performance/` — 실적 코드를 `/malaysia/performance` 에 한 번 더 붙임, `performance/variant.py`) → `malaysia_performance_db` |
### 권한 키 (`MODULE_KEYS`) ### 권한 키 (`MODULE_KEYS`)
@@ -36,7 +37,7 @@
| 키 | 종류 | 설명 | | 키 | 종류 | 설명 |
| --- | --- | --- | | --- | --- | --- |
| `corm` / `order` | 접근 | 외부 모듈 진입 | | `corm` / `order` | 접근 | 외부 모듈 진입 |
| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) | | `expense` / `vacation` / `cupang` / `malaysia` / `performance` / `malaysia_performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) |
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 | | `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
| `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 | | `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 |
| `outreach` | 접근 | 안내문 발송 — 리스트·메일 발송·DM·설정 | | `outreach` | 접근 | 안내문 발송 — 리스트·메일 발송·DM·설정 |
@@ -118,6 +119,7 @@ app/modules/<name>/
| `outreach_db` | 안내문 발송 — 리스트·보낸 기록·제목/본문 설정·사진 (`OUTREACH_DB_URL` 필수, JSON 폴백 없음) | | `outreach_db` | 안내문 발송 — 리스트·보낸 기록·제목/본문 설정·사진 (`OUTREACH_DB_URL` 필수, JSON 폴백 없음) |
| `live_db` | 라이브 커머스 — 호스트 정보·방송 스케줄·결과 이미지 (`LIVE_DB_URL` 필수, JSON 폴백 없음) | | `live_db` | 라이브 커머스 — 호스트 정보·방송 스케줄·결과 이미지 (`LIVE_DB_URL` 필수, JSON 폴백 없음) |
| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) | | `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
| `malaysia_performance_db` | 말레이시아 실적 — performance_db 와 같은 표 구조, 금액 = 센 정수 (`MALAYSIA_PERFORMANCE_DB_URL`) |
> 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`. > 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`.
@@ -0,0 +1,54 @@
-- =====================================================================
-- cafe24_db 006 — 예약에 대표 이미지 교체 추가 (2026-11-09)
-- =====================================================================
-- 멱등(idempotent): 여러 번 실행해도 안전. DROP TABLE/TRUNCATE 없음.
--
-- 실행:
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d cafe24_db \
-- < scripts/sql/cafe24_db_006_schedule_image.sql
--
-- 배경:
-- 지정 시각에 상품 대표 이미지(썸네일)를 교체하는 예약. 등록 때 올린 파일을
-- 그 시각까지 보관해야 하므로 바이트를 DB 에 둔다(worker 는 web 과 다른
-- 컨테이너라 로컬 파일을 공유하지 않는다). 예약 목록(s.*)이 무거워지지 않게
-- 바이트는 별도 테이블에 둔다.
-- cafe24_product_schedules.image_type = '' → 이미지 교체 없음
-- 'image/png' 등 → 그 시각에 교체
--
-- 롤백(이미지 예약을 쓰지 않을 때만):
-- ALTER TABLE cafe24_product_schedules DROP CONSTRAINT chk_cafe24_schedule_has_action;
-- ALTER TABLE cafe24_product_schedules ADD CONSTRAINT chk_cafe24_schedule_has_action CHECK (
-- revision_id IS NOT NULL OR set_display IS NOT NULL OR set_selling IS NOT NULL);
-- DROP TABLE cafe24_schedule_images;
-- ALTER TABLE cafe24_product_schedules DROP COLUMN image_type, DROP COLUMN image_name;
-- =====================================================================
\set ON_ERROR_STOP on
ALTER TABLE cafe24_product_schedules
ADD COLUMN IF NOT EXISTS image_type TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS image_name TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN cafe24_product_schedules.image_type IS
'예약 시각에 교체할 대표 이미지의 형식(image/png 등). 빈 값이면 이미지 교체 없음';
COMMENT ON COLUMN cafe24_product_schedules.image_name IS
'등록 때 올린 대표 이미지 파일명(표시용)';
CREATE TABLE IF NOT EXISTS cafe24_schedule_images (
schedule_id BIGINT PRIMARY KEY REFERENCES cafe24_product_schedules(id) ON DELETE CASCADE,
data BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
COMMENT ON TABLE cafe24_schedule_images IS '예약 대표 이미지 파일(10MB 이하)';
-- 아무것도 하지 않는 예약은 만들 수 없게 한다 — 이미지 교체도 "할 일"로 센다.
ALTER TABLE cafe24_product_schedules
DROP CONSTRAINT IF EXISTS chk_cafe24_schedule_has_action;
ALTER TABLE cafe24_product_schedules
ADD CONSTRAINT chk_cafe24_schedule_has_action CHECK (
revision_id IS NOT NULL OR set_display IS NOT NULL OR set_selling IS NOT NULL OR image_type <> ''
);
GRANT SELECT, INSERT, UPDATE, DELETE ON cafe24_schedule_images TO cafe24_app;
SELECT 'cafe24_db 006 applied' AS status;
@@ -0,0 +1,38 @@
-- =====================================================================
-- malaysia_performance_db 쇼핑몰 seed — [말레이시아 실적](2026-11-20)
-- =====================================================================
-- 말레이시아 실적은 실적 모듈 코드를 그대로 쓰므로 표 구조 = performance_db(마이그레이션 012 까지)와 같다.
-- 그래서 DB 를 만들 때 performance_db 의 **구조만**(데이터 없이) 복사하고, 이 파일로 쇼핑몰만 넣는다.
-- 멱등(ON CONFLICT DO NOTHING). DROP/DELETE 없음. 역할은 실적과 같은 performance_app 을 쓴다.
--
-- 실행 순서(운영 PostgreSQL 컨테이너 postgres-db, 경로 /opt/www/main — 사용자 승인 후):
-- 1) 빈 DB 만들기 + 접속 권한
-- docker exec -i postgres-db psql -U postgres -c "CREATE DATABASE malaysia_performance_db ENCODING 'UTF8' TEMPLATE template0"
-- docker exec -i postgres-db psql -U postgres -c "GRANT CONNECT ON DATABASE malaysia_performance_db TO performance_app"
-- 2) performance_db 구조만 복사(표·인덱스·트리거·권한, 데이터 없음)
-- docker exec postgres-db pg_dump -U postgres --schema-only performance_db \
-- | docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d malaysia_performance_db
-- 3) 이 파일
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d malaysia_performance_db < scripts/sql/malaysia_performance_db_seed.sql
-- 4) .env 에 MALAYSIA_PERFORMANCE_DB_URL=postgresql://performance_app:<실적과 같은 비밀번호>@postgres-db:5432/malaysia_performance_db
--
-- 코드는 app/modules/performance/variant.py MY 와 같아야 한다(광고비 ROAS·매출 칸 아래 광고비 줄이 이 코드로 찾음).
-- group_<쇼핑몰> = 합계 열(매출 없음), custom_<쇼핑몰>_shop = 쇼핑몰 매출, custom_<쇼핑몰>_live = 라이브커머스 매출.
-- 금액은 센(0.01 RM) 정수로 저장된다(화면 = RM 소수 2자리).
-- =====================================================================
\set ON_ERROR_STOP on
INSERT INTO perf_marketplaces (code, name, sort_order, manual_input, include_in_sales, is_custom, is_group, parent_code) VALUES
('group_tiktok', '틱톡', 10, FALSE, FALSE, TRUE, TRUE, NULL),
('custom_tiktok_shop', '틱톡 쇼핑몰', 11, TRUE, TRUE, TRUE, FALSE, 'group_tiktok'),
('custom_tiktok_live', '틱톡 라이브커머스', 12, TRUE, TRUE, TRUE, FALSE, 'group_tiktok'),
('group_shopee', '쇼피', 20, FALSE, FALSE, TRUE, TRUE, NULL),
('custom_shopee_shop', '쇼피 쇼핑몰', 21, TRUE, TRUE, TRUE, FALSE, 'group_shopee'),
('custom_shopee_live', '쇼피 라이브커머스', 22, TRUE, TRUE, TRUE, FALSE, 'group_shopee'),
('group_lazada', '라자다', 30, FALSE, FALSE, TRUE, TRUE, NULL),
('custom_lazada_shop', '라자다 쇼핑몰', 31, TRUE, TRUE, TRUE, FALSE, 'group_lazada'),
('custom_lazada_live', '라자다 라이브커머스', 32, TRUE, TRUE, TRUE, FALSE, 'group_lazada')
ON CONFLICT (code) DO NOTHING;
SELECT 'malaysia_performance_db seed ready' AS status;
@@ -0,0 +1,17 @@
-- ════════════════════════════════════════════════════════════
-- 마이그레이션: 신규 세트 MY-1007 등록
-- malaysia_items 에 세트 MY-1007(kind='set')을 추가한다 — 재고 화면 세트 목록 노출용.
-- BOM(MT-1800·MT-2200·MT-3200 각 1개)은 itemcode_db.set_components 에 이미 있음(확인됨).
-- 구성 낱개 MT-1800/2200/3200 은 malaysia_items 에 이미 있음(확인됨).
-- 이름은 psql 변수 name 으로 받는다(itemcode_db.set_items.name). 비면 코드로.
-- NAME=$(docker exec postgres-db psql -U postgres -d itemcode_db -tAc "SELECT name FROM set_items WHERE item_code='MY-1007'")
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -v name="$NAME" -U postgres -d malaysia_stock_db < scripts/sql/malaysia_stock_db_add_my1007.sql
-- superuser/owner 로 실행. 멱등(재실행 시 이름·활성만 갱신, 순서 유지).
-- ════════════════════════════════════════════════════════════
INSERT INTO malaysia_items (item_code, item_name, kind, sort_order)
SELECT 'MY-1007', COALESCE(NULLIF(trim(:'name'), ''), 'MY-1007'), 'set',
(SELECT COALESCE(MAX(sort_order), 0) + 1 FROM malaysia_items)
ON CONFLICT (item_code) DO UPDATE
SET item_name = EXCLUDED.item_name,
kind = EXCLUDED.kind,
active = TRUE;
@@ -0,0 +1,28 @@
-- =====================================================================
-- performance_db 012 — 틱톡 탭 삭제(2026-11-20)에 따른 틱톡 광고 데이터 삭제
-- =====================================================================
-- ⚠️ 데이터 삭제 — 사용자 승인 + 백업 확인 후 실행. 되돌릴 수 없다(백업에서만 복구).
-- 틱톡 광고 API 로 받은 일 광고비·매출(perf_ad_spend channel_code='tiktok'), 틱톡 광고 API 인증정보(암호문)·연결 상태,
-- 틱톡 칸 메모만 지운다. 다른 채널·쇼핑몰은 건드리지 않는다. 표(테이블)는 지우지 않는다.
--
-- 1) 지울 행 수 확인(읽기만)
-- docker exec -i postgres-db psql -U postgres -d performance_db -c "SELECT
-- (SELECT count(*) FROM perf_ad_spend WHERE channel_code='tiktok') AS spend,
-- (SELECT count(*) FROM perf_ad_credentials WHERE channel_code='tiktok') AS creds,
-- (SELECT count(*) FROM perf_ad_source_status WHERE channel_code='tiktok') AS status,
-- (SELECT count(*) FROM perf_cell_memos WHERE kind='ad' AND code='tiktok') AS memos;"
-- 2) 백업
-- docker exec postgres-db pg_dump -U postgres performance_db > ~/performance_db_before_012_$(date +%Y%m%d%H%M).sql
-- 3) 실행
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d performance_db < scripts/sql/performance_db_012_drop_tiktok.sql
-- 4) 1) 을 다시 실행해 모두 0 인지 확인
-- =====================================================================
BEGIN;
DELETE FROM perf_ad_spend WHERE channel_code = 'tiktok';
DELETE FROM perf_ad_credentials WHERE channel_code = 'tiktok';
DELETE FROM perf_ad_source_status WHERE channel_code = 'tiktok';
DELETE FROM perf_cell_memos WHERE kind = 'ad' AND code = 'tiktok';
COMMIT;
SELECT 'performance_db 012 tiktok data removed' AS status;
@@ -0,0 +1,19 @@
-- =====================================================================
-- project_db 마이그레이션 033 — 매일 하는 업무(마감일 없이 매일 반복)
-- =====================================================================
-- 멱등(idempotent). tasks 에 repeat_daily 열 하나만 추가(기존 값 변경 없음, 새 환경변수 없음).
-- 운영: /opt/www/main 에서 기존 project_db 에 적용(적용 전 pg_dump 백업).
--
-- 날짜 팝업 [매일]로 켠다 — 켜면 마감일·마감 시각은 비운다(마감일을 고르면 다시 꺼짐).
-- 마감일 칸에는 반복 아이콘, 알림 데몬(reminders.py)이 Project 옵션 daily_alert_times 시각마다(영업일)
-- 담당자(없으면 협업자)에게 "매일 업무" 알림(type=daily)을 만든다 — 중복 방지는 기존 task_reminders
-- (kind = 'daily@HH:MM', due_date = 그날).
-- 미적용이면 앱은 예전 그대로(날짜 팝업에 [매일] 없음, 매일 알림 skip).
-- 되돌리기: ALTER TABLE tasks DROP COLUMN repeat_daily;
-- =====================================================================
BEGIN;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS repeat_daily BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS idx_tasks_repeat_daily_open ON tasks (id) WHERE repeat_daily AND completed_at IS NULL;
COMMIT;
+105
View File
@@ -0,0 +1,105 @@
// 실적 일자별 표 열 접기(2026-11-06) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_colfold.browser.test.js
// 머리글 위 버튼(.perf-cfold)으로 열 하나 접기/펴기(날짜 열 빼고) → 26px 띠, 칸 내용 숨김, PUT /api/my-col-fold {kind, cols}.
// 서버가 그린 data-col-fold(그 사람 저장값)로 처음부터 접힘. 수동 열 너비 표에서도 같은 26px. 매출 실적·광고비 둘 다.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
function route(p, file, folded, puts) {
return p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
return r.fulfill({ status: 200, contentType: f.endsWith(".css") ? "text/css" : "application/javascript", body: fs.readFileSync(f) });
}
if (url.includes("/api/")) {
if (url.endsWith("/api/my-col-fold")) puts.push(JSON.parse(r.request().postData()));
return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
}
const html = fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
.replace('data-col-fold="[]"', 'data-col-fold="' + JSON.stringify(folded).replace(/"/g, "&#34;") + '"');
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: html });
});
}
function state(p, col) {
return p.evaluate(function (col) {
const t = document.querySelector("table.perf-main"), th = t.querySelector('thead th[data-col="' + col + '"]');
const i = th.cellIndex, cells = Array.from(t.tBodies[0].rows).map(function (r) { return r.cells[i]; });
const btn = th.querySelector(".perf-cfold");
return { w: Math.round(th.getBoundingClientRect().width), folded: th.classList.contains("is-cfold"),
allCells: cells.every(function (c) { return c.classList.contains("is-cfold"); }),
cellW: Math.round(cells[1].getBoundingClientRect().width), text: cells[1].innerText.trim(),
expanded: btn && btn.getAttribute("aria-expanded"), buttons: t.querySelectorAll(".perf-cfold").length,
labelBtn: !!t.querySelector('th[data-col="label"] .perf-cfold'), heads: t.tHead.rows[0].cells.length };
}, col);
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
for (const [file, kind] of [["perf_dash_shell.html", "sales"], ["perf_ads_shell.html", "ads"], ["perf_dash_colw_shell.html", "sales"]]) {
const tag = "[" + file + "] ";
const puts = [];
const ctx = await browser.newContext({ viewport: { width: 1400, height: 800 } });
const p = await ctx.newPage();
await route(p, file, [], puts);
await p.goto("http://perf.test/performance/");
await p.waitForTimeout(150);
const col = await p.evaluate(function () { // 접어 볼 열 = 일 합계 다음 첫 열
return document.querySelector("table.perf-main").tHead.rows[0].cells[2].dataset.col;
});
const s0 = await state(p, col);
check(tag + "날짜 열 빼고 열마다 버튼, 처음엔 펼침", s0.buttons === s0.heads - 1 && !s0.labelBtn && !s0.folded && s0.expanded === "true", s0);
// 말풍선 — 버튼 위에 올리면 커서 바로 위에 열 이름(제목 글자 크기 12px), 커서 따라 움직임, 머리글 기본 말풍선(title) 없음
const bb = await p.locator('thead th[data-col="' + col + '"] .perf-cfold').boundingBox();
await p.mouse.move(bb.x + 4, bb.y + bb.height / 2);
await p.mouse.move(bb.x + bb.width - 4, bb.y + bb.height / 2);
const tip = await p.evaluate(function (col) {
const t = document.querySelector(".perf-cfold-tip"), b = document.querySelector('thead th[data-col="' + col + '"] .perf-cfold');
const head = document.querySelector('thead th[data-col="' + col + '"]');
if (!t) return null;
const r = t.getBoundingClientRect();
return { text: t.textContent, name: head.textContent.replace(/[✎\s]+/g, " ").trim(), size: getComputedStyle(t).fontSize,
headSize: getComputedStyle(head).fontSize, cx: Math.round(r.left + r.width / 2), bottom: Math.round(r.bottom), title: b.getAttribute("title") };
}, col);
const cursorX = Math.round(bb.x + bb.width - 4), cursorY = bb.y + bb.height / 2;
check(tag + "말풍선 = 열 이름, 제목 글자 크기, 커서 위를 따라감", tip && tip.text === tip.name && tip.text !== "" && tip.size === tip.headSize &&
Math.abs(tip.cx - cursorX) <= 1 && tip.bottom < cursorY && tip.title === "", tip);
await p.mouse.move(5, 5);
check(tag + "벗어나면 말풍선 닫힘", (await p.locator(".perf-cfold-tip").count()) === 0);
await p.click('thead th[data-col="' + col + '"] .perf-cfold');
await p.waitForTimeout(100);
const s1 = await state(p, col);
check(tag + "누르면 26px 띠로 접힘(칸 내용 숨김)", s1.folded && s1.allCells && s1.w === 26 && s1.cellW === 26 && s1.text === "" && s1.expanded === "false", s1);
check(tag + "PUT /api/my-col-fold {kind, cols}", puts.length === 1 && puts[0].kind === kind && JSON.stringify(puts[0].cols) === JSON.stringify([col]), puts);
await p.click('thead th[data-col="' + col + '"] .perf-cfold');
await p.waitForTimeout(100);
const s2 = await state(p, col);
check(tag + "다시 누르면 원래 너비로", !s2.folded && Math.abs(s2.w - s0.w) <= 1 && s2.text !== "", { s0: s0, s2: s2 });
check(tag + "펼친 것도 저장(빈 목록)", puts.length === 2 && puts[1].cols.length === 0, puts);
await ctx.close();
// 서버가 그린 저장값(data-col-fold)으로 처음부터 접힘
const ctx2 = await browser.newContext({ viewport: { width: 1400, height: 800 } });
const q = await ctx2.newPage();
await route(q, file, [col, "total"], []);
await q.goto("http://perf.test/performance/");
await q.waitForTimeout(150);
const s3 = await state(q, col), t3 = await state(q, "total");
check(tag + "저장값대로 처음부터 접힘(일 합계 포함)", s3.folded && s3.w === 26 && t3.folded && t3.w === 26, { s3: s3, t3: t3 });
if (file === "perf_dash_shell.html") await q.screenshot({ path: path.join(__dirname, ".out", "perf_colfold.png") });
await ctx2.close();
}
} finally {
await browser.close();
}
console.log(fails.length ? "\n" + fails.length + " FAIL" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
+79
View File
@@ -0,0 +1,79 @@
// 말레이시아 실적(2026-11-20) — 실제 브라우저. 같은 performance.js 가 data-base(/malaysia/performance)로 저장하고
// 금액을 RM 소수 2자리로 보이는지(저장 단위 = 센).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_malaysia.browser.test.js
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
function load(file) {
const css = fs.readFileSync(path.join(ROOT, "app", "static", "performance.css"), "utf8");
const js = fs.readFileSync(path.join(ROOT, "app", "static", "performance.js"), "utf8");
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + css + "</style>"; })
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + js + "</script>"; });
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
try {
// 매출 실적 — 틱톡 라이브커머스 10/5 칸(RM 100.05)을 12.34 로
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const calls = [];
await page.route("**/*", function (r) {
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_dash.html") });
calls.push({ url: r.request().url(), body: r.request().postData() });
r.fulfill({ status: 200, contentType: "application/json",
body: JSON.stringify({ ok: true, manual: 1234, amount: 1234, commission: 0, net: 1234, formula: null }) });
});
await page.goto("http://perf.test/malaysia/performance/");
const sel = 'td.is-manual-cell[data-manual-code="custom_tiktok_live"][data-date="2026-10-05"]';
await page.click(sel);
const prefill = await page.$eval(sel + " .perf-manual-input", function (i) { return i.value; });
check("편집창 = RM 값(100.05)", prefill === "100.05", prefill);
await page.keyboard.press("Control+A");
await page.keyboard.type("RM 12.34");
await page.keyboard.press("Escape"); // 저장 뒤 새로고침(합계 다시 계산) 전에 칸 값을 본다 — Enter 는 다음 칸 편집으로 넘어감
await page.click(sel);
await page.keyboard.press("Control+A");
await page.keyboard.type("RM 12.34");
await page.keyboard.press("Enter");
await page.waitForTimeout(300);
const put = calls.find(function (c) { return /manual-sales/.test(c.url); });
check("저장 주소 = /malaysia/performance/api/manual-sales/…", put && /\/malaysia\/performance\/api\/manual-sales\/custom_tiktok_live\/2026-10-05$/.test(put.url), put);
check("보낸 값 = 12.34(RM 글자 지움)", put && JSON.parse(put.body).amount === "12.34", put);
const cell = await page.$eval(sel, function (td) { return { gross: td.querySelector(".v-gross").textContent, v: td.dataset.manualValue }; });
check("저장 뒤 칸 = 12.34, 편집값 12.34", cell.gross === "12.34" && cell.v === "12.34", cell);
const head = await page.$eval("#perf-chart-daily svg", function (s) { return s.querySelector("title").textContent; });
check("그래프 말풍선 = RM", / RM$/.test(head) && /\d\.\d\d RM$/.test(head), head);
await page.close();
// 광고비 — 쇼피 10/5 칸에 계산식
const ap = await browser.newPage({ viewport: { width: 1400, height: 900 } });
const acalls = [];
await ap.route("**/*", function (r) {
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load("perf_my_ads.html") });
acalls.push({ url: r.request().url(), body: r.request().postData() });
r.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, manual: 300, amount: 300, formula: "1.5*2" }) });
});
await ap.goto("http://perf.test/malaysia/performance/ads");
const heads = await ap.$$eval(".perf-main thead th", function (ths) { return ths.map(function (t) { return t.textContent.trim(); }); });
check("광고비 열 = 틱톡·쇼피·라자다", /틱톡/.test(heads[2]) && /쇼피/.test(heads[3]) && /라자다/.test(heads[4]) && heads.length === 5, heads);
const asel = 'td.is-manual-cell[data-manual-code="shopee"][data-date="2026-10-05"]';
await ap.click(asel);
await ap.keyboard.type("1.5*2");
await ap.keyboard.press("Enter");
await ap.waitForTimeout(300);
const aput = acalls.find(function (c) { return /ad-spend/.test(c.url); });
check("광고비 저장 주소 = /malaysia/performance/api/ad-spend/shopee/…", aput && /\/malaysia\/performance\/api\/ad-spend\/shopee\/2026-10-05$/.test(aput.url), aput);
const av = await ap.$eval(asel + " .v-gross", function (s) { return s.textContent; });
check("광고비 칸 = 3.00", av === "3.00", av);
await ap.close();
} finally { await browser.close(); }
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
+115
View File
@@ -0,0 +1,115 @@
// 말레이시아 실적 영문 화면(2026-11-20) — 실제 브라우저. performance-en.js 번역 뒤 화면·창·메뉴·알림에 한글이 하나도 없는지.
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_malaysia_en.browser.test.js
// 한글이 남으면 그 글을 모두 찍는다 — performance-en.js EN·RULES·PHRASES 에 넣으면 된다.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra, null, 1) : "")); fails.push(name); }
}
const S = function (f) { return fs.readFileSync(path.join(ROOT, "app", "static", f), "utf8"); };
function load(file) {
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + S("performance.css") + "</style>"; })
.replace(/<script src="\/static\/performance-en\.js[^"]*" defer><\/script>/, function () { return "<script>" + S("performance-en.js") + "</script>"; })
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + S("performance.js") + "</script>"; });
}
// 화면에 남은 한글 — .perf 안 + 실적 창·메뉴·말풍선 + 알림 창(글자·title·aria-label·placeholder), 한영 토글(translate=no) 빼고
function leftovers() {
const H = /[가-힣]/, out = [];
const roots = Array.from(document.querySelectorAll('.perf, [class*="perf-"], .erp-dialog-backdrop')).filter(function (r) {
return !r.parentElement || !r.parentElement.closest('.perf, [class*="perf-"], .erp-dialog-backdrop');
});
roots.forEach(function (r) {
const tw = document.createTreeWalker(r, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
for (let n = r; n; n = tw.nextNode()) {
const el = n.nodeType === 1 ? n : n.parentElement;
if (!el || el.closest("[translate='no'], script, style")) continue;
if (n.nodeType === 3 && H.test(n.nodeValue)) out.push(n.nodeValue.trim());
if (n.nodeType === 1) ["title", "aria-label", "placeholder"].forEach(function (a) { const v = n.getAttribute(a); if (v && H.test(v)) out.push("@" + a + ": " + v); });
}
});
return Array.from(new Set(out.concat(window.__perfI18nMissing || [])));
}
(async function () {
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
const dialogs = [];
async function open(file, url, api) {
const p = await browser.newPage({ viewport: { width: 1400, height: 900 } });
p.on("dialog", function (d) { dialogs.push(d.message()); d.accept().catch(function () {}); });
await p.route("**/*", function (r) {
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load(file) });
const res = api ? api(r.request()) : { status: 200, body: {} };
r.fulfill({ status: res.status || 200, contentType: "application/json", body: JSON.stringify(res.body) });
});
await p.goto("http://perf.test" + url);
return p;
}
try {
// 매출 실적 — 표·그래프·업로드 창·메모 메뉴·메모 창·잘못된 입력 알림
let p = await open("perf_my_dash_en.html", "/malaysia/performance/");
check("번역 끝나면 화면 보임(is-i18n)", await p.$eval(".perf", function (r) { return r.classList.contains("is-i18n") && getComputedStyle(r).visibility === "visible"; }));
check("탭·KPI 영문", /Sales/.test(await p.textContent(".perf-tabs")) && /last week/.test(await p.textContent(".perf-kpi-line")));
await p.click("#perf-manual-upload");
await p.waitForTimeout(150);
let left = await p.evaluate(leftovers);
check("매출 실적 + 업로드 창 — 한글 없음", left.length === 0, left);
await p.keyboard.press("Escape");
await p.click('td.is-manual-cell[data-manual-code="custom_tiktok_live"][data-date="2026-10-05"]', { button: "right" });
await p.waitForTimeout(100);
const ctx = await p.$$eval(".perf-ctx button", function (bs) { return bs.map(function (b) { return b.textContent.trim(); }); });
check("메모 메뉴 영문", ctx.length > 0 && ctx.every(function (t) { return !/[가-힣]/.test(t); }), ctx);
await p.click(".perf-ctx button");
await p.waitForTimeout(150);
left = await p.evaluate(leftovers);
check("메모 창 — 한글 없음", left.length === 0, left);
await p.keyboard.press("Escape");
await p.click('td.is-manual-cell[data-manual-code="custom_shopee_live"][data-date="2026-10-06"]');
await p.keyboard.type("12a");
await p.keyboard.press("Enter");
await p.waitForTimeout(300);
await p.close();
p = await open("perf_my_dash_year_en.html", "/malaysia/performance/?period=year");
left = await p.evaluate(leftovers);
check("연간 보기 — 한글 없음", left.length === 0, left);
await p.close();
// 광고비
p = await open("perf_my_ads_en.html", "/malaysia/performance/ads");
left = await p.evaluate(leftovers);
check("광고비 — 한글 없음", left.length === 0, left);
await p.close();
// 설정 — 수수료율 창·쇼핑몰 추가 창·삭제 확인
p = await open("perf_my_settings_en.html", "/malaysia/performance/settings", function (req) {
if (/manual-days/.test(req.url())) return { body: { days: 3 } };
if (/rates/.test(req.url())) return { body: { rates: [{ id: 1, effective_from: "2026-10-01", rate: "5" }] } };
return { status: 400, body: { detail: "기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요)." } };
});
left = await p.evaluate(leftovers);
check("설정 — 한글 없음", left.length === 0, left);
await p.click('tr[data-code="custom_tiktok_shop"] [data-act="rate"]');
await p.waitForTimeout(250);
left = await p.evaluate(leftovers);
check("수수료율 창 — 한글 없음", left.length === 0, left);
await p.keyboard.press("Escape");
await p.click("#perf-add-shop");
await p.waitForTimeout(150);
left = await p.evaluate(leftovers);
check("쇼핑몰 추가 창 — 한글 없음", left.length === 0, left);
await p.keyboard.press("Escape");
await p.click('tr[data-code="custom_tiktok_shop"] [data-act="delete"]');
await p.waitForTimeout(300);
await p.close();
const bad = dialogs.filter(function (m) { return /[가-힣]/.test(m); });
check("알림·확인 창 문구 영문(" + dialogs.length + "개)", dialogs.length >= 2 && bad.length === 0, { bad: bad, all: dialogs });
} finally { await browser.close(); }
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
process.exit(fails.length ? 1 : 0);
})();
-63
View File
@@ -1,63 +0,0 @@
// 실적 틱톡 탭(2026-11-05) — 실제 브라우저(Chromium).
// python tests/js/render_performance.py
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_tiktok.browser.test.js
// 광고비 오른쪽 탭, ROAS·광고비·매출 열, 매출·광고비 그래프 둘, 합계 줄 스크롤 고정, 칸 입력 없음, 스크립트 오류 없음.
const fs = require("fs"), path = require("path");
const { chromium } = require("playwright");
const ROOT = path.join(__dirname, "..", "..");
const fails = [];
function check(name, cond, extra) {
if (cond) console.log("PASS " + name);
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
}
(async function () {
const exe = process.env.PJ_TEST_BROWSER;
const browser = await chromium.launch(exe ? { executablePath: exe } : {});
try {
const p = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();
const errors = [];
p.on("pageerror", function (e) { errors.push(String(e)); });
await p.route("**/*", function (r) {
const url = new URL(r.request().url()).pathname;
if (url.startsWith("/static/")) {
const f = path.join(ROOT, "app", url);
if (!fs.existsSync(f)) return r.fulfill({ status: 404, body: "" });
const type = f.endsWith(".css") ? "text/css" : f.endsWith(".js") ? "application/javascript" : "font/woff2";
return r.fulfill({ status: 200, contentType: type, body: fs.readFileSync(f) });
}
if (!url.endsWith(".html")) return r.fulfill({ status: 200, contentType: "application/json", body: "{}" });
r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fs.readFileSync(path.join(__dirname, ".out", url.slice(1)), "utf8") });
});
await p.goto("http://erp.test/perf_tiktok_shell.html");
await p.waitForTimeout(300);
const tabs = await p.locator(".perf-tabs-main .perf-tab").allInnerTexts();
check("탭 순서 = 매출 실적·광고비·틱톡", tabs.map(function (t) { return t.replace(/^[a-z_]+\s*/, "").trim(); }).join() === "매출 실적,광고비,틱톡", tabs);
check("틱톡 탭이 켜짐", await p.locator(".perf-tab-tiktok.is-active").count() === 1);
const head = await p.locator("table.perf-main thead th").allInnerTexts();
check("열 = 날짜·ROAS·광고비·매출", head.join() === "날짜,ROAS,광고비,매출", head);
const total = await p.locator("table.perf-main tbody tr").first().innerText();
check("맨 위 기간 합계", total.includes("합계") && total.includes("210,000") && total.includes("630,000") && total.includes("300%"), total);
const day = await p.locator("table.perf-main tbody tr", { hasText: "400%" }).first().innerText();
check("일자 줄 값", day.includes("120,000") && day.includes("480,000"), day);
check("매출 그래프", await p.locator("#perf-chart-daily svg rect.bar").count() > 0);
check("광고비 그래프", await p.locator("#perf-chart-daily2 svg rect.bar").count() > 0);
check("칸 입력 없음", await p.locator("[data-manual-code]").count() === 0);
check("업데이트 버튼", (await p.locator("#perf-ad-sync-btn").innerText()).includes("광고비 업데이트"));
await p.screenshot({ path: path.join(__dirname, ".out", "perf_tiktok.png") });
await p.locator("table.perf-main").hover();
await p.mouse.wheel(0, 500);
await p.waitForTimeout(250);
const stuck = await p.evaluate(function () {
const first = document.querySelector("table.perf-main tbody tr.perf-row-total:first-child th");
const top = first.getBoundingClientRect().top;
return document.querySelector("table.perf-main thead th").getBoundingClientRect().bottom <= top + 2 && top >= 0 && top < 300;
});
check("스크롤해도 제목·합계 줄 고정", stuck);
check("스크립트 오류 없음", errors.length === 0, errors);
} finally {
await browser.close();
}
if (fails.length) { console.log("\n" + fails.length + " FAILED"); process.exit(1); }
console.log("\nALL OK");
})();
+2 -2
View File
@@ -46,7 +46,7 @@ def board() -> dict:
def goals_ctx(admin: bool) -> dict: def goals_ctx(admin: bool) -> dict:
return { return {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026], "user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "pj_all_view": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"], "goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(), "project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
"months": list(range(1, 13)), "months": list(range(1, 13)),
@@ -106,7 +106,7 @@ def meeting_view(err: bool) -> dict:
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict: def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
view = meeting_view(err) view = meeting_view(err)
ctx = { ctx = {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026], "user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "pj_all_view": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"], "goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True, "project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False, "weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
+39 -14
View File
@@ -19,9 +19,10 @@ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)
sys.path.insert(0, ROOT) sys.path.insert(0, ROOT)
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out") OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
from app.modules.performance.ad_spend import build_ad_dashboard, build_tiktok_dashboard # noqa: E402 from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402 from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402 from app.modules.performance.router import _auto_sync_settings_ctx # noqa: E402
from app.modules.performance import variant # noqa: E402
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>" BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
"{% block scripts %}{% endblock %}</body>") "{% block scripts %}{% endblock %}</body>")
@@ -84,17 +85,11 @@ def env() -> jinja2.Environment:
return e return e
class TiktokStore:
def ad_details(self, code, start, end):
rows = [("2026-10-02", 120000, 480000), ("2026-10-05", 90000, 150000), ("2026-09-20", 50000, 100000)]
return [{"date": d, "amount": a, "roas": None, "metrics": {"매출": b}, "source": "api"} for d, a, b in rows]
def main() -> None: def main() -> None:
os.makedirs(OUT_DIR, exist_ok=True) os.makedirs(OUT_DIR, exist_ok=True)
e = env() e = env()
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "", base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "",
"unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto"} "unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v), "colw": "auto", **variant.template_ctx()}
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7)) ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
# 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다 # 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다
# 일정 = 실적 설정 "자동 업데이트"(2026-10-26) — 화면이 schedule 로 다음 회차를 계산 # 일정 = 실적 설정 "자동 업데이트"(2026-10-26) — 화면이 schedule 로 다음 회차를 계산
@@ -123,12 +118,6 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx) html = shell.get_template("performance/ads.html").render(**sbase, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f: with open(os.path.join(OUT_DIR, "perf_ads_shell.html"), "w", encoding="utf-8") as f:
f.write(html) f.write(html)
# 틱톡 탭(2026-11-05) — 가상의 광고 API 값
tk = build_tiktok_dashboard(TiktokStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays={"2026-10-03": "개천절"})
tk.update(auto_sync=ctx["auto_sync"], update_watch={"kind": "ads", "seen": "job-old"}, tiktok_configured=True, ad_running=False,
ad_last_update_at=None, ad_sync_sources=[{"code": "tiktok", "name": "틱톡"}])
with open(os.path.join(OUT_DIR, "perf_tiktok_shell.html"), "w", encoding="utf-8") as f:
f.write(shell.get_template("performance/tiktok.html").render(**sbase, active_tab="tiktok", **tk))
actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), actx =build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24", "coupang"]) sales_codes=["cafe24", "coupang"])
actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기] actx["ad_sync_sources"] = [{"code": "google", "name": "구글 광고"}] # [구글 광고 불러오기]
@@ -171,9 +160,45 @@ def main() -> None:
html = shell.get_template("performance/ads.html").render(**{**sbase, "colw": "manual"}, active_tab="ads", **sactx) html = shell.get_template("performance/ads.html").render(**{**sbase, "colw": "manual"}, active_tab="ads", **sactx)
with open(os.path.join(OUT_DIR, "perf_ads_colw_shell.html"), "w", encoding="utf-8") as f: with open(os.path.join(OUT_DIR, "perf_ads_colw_shell.html"), "w", encoding="utf-8") as f:
f.write(html) f.write(html)
render_malaysia(e, base)
print("ok") print("ok")
def render_malaysia(e: jinja2.Environment, base: dict) -> None:
"""말레이시아 실적(2026-11-20) — perf_my_dash.html · perf_my_ads.html (perf_malaysia.browser.test.js). 금액 = 센."""
from app.modules.performance.tests.test_malaysia_variant import _Store # noqa: WPS433
from app.modules.live.holidays import holiday_names # noqa: WPS433
token = variant._current.set(variant.MY)
try:
# 한글(perf_my_*.html) + 영문(perf_my_*_en.html, perf_malaysia_en.browser.test.js — 그룹 하나·연간 보기도)
for lang, sfx in (("ko", ""), ("en", "_en")):
ltoken = variant._lang.set(lang)
try:
mb = {**base, **variant.template_ctx(), "unit": "rm", "unit_label": "RM", "amt": lambda v: amount_text(v, "rm")}
hol = holiday_names(lang)
for kind, name in (("week", "dash"), ("year", "dash_year")):
ctx = build_dashboard(_Store(), kind=kind, anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays=hol)
ctx.update(auto_sync=None, update_watch=None)
if kind == "year" and not sfx:
continue
with open(os.path.join(OUT_DIR, f"perf_my_{name}{sfx}.html"), "w", encoding="utf-8") as f:
f.write(e.get_template("performance/index.html").render(**mb, active_tab="dashboard", metric="gross", **ctx))
actx = build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=[],
holidays=hol)
actx.update(auto_sync=None, update_watch=None)
with open(os.path.join(OUT_DIR, f"perf_my_ads{sfx}.html"), "w", encoding="utf-8") as f:
f.write(e.get_template("performance/ads.html").render(**mb, active_tab="ads", **actx))
sctx = build_settings(_Store(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
with open(os.path.join(OUT_DIR, f"perf_my_settings{sfx}.html"), "w", encoding="utf-8") as f:
f.write(e.get_template("performance/settings.html").render(**mb, active_tab="settings", **sctx))
finally:
variant._lang.reset(ltoken)
finally:
variant._current.reset(token)
class GroupStore(FakeStore): class GroupStore(FakeStore):
"""카페24·네이버 + 그룹 '오프라인'(매장A·매장B) + 그룹 없는 직접 추가 '행사'.""" """카페24·네이버 + 그룹 '오프라인'(매장A·매장B) + 그룹 없는 직접 추가 '행사'."""
+1 -1
View File
@@ -105,7 +105,7 @@ def render_inbox(env) -> None:
def render_one(env, name: str, admin: bool, sup: bool = False) -> None: def render_one(env, name: str, admin: bool, sup: bool = False) -> None:
html = env.get_template("project/project.html").render( html = env.get_template("project/project.html").render(
user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True, user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, pj_all_view=admin, can_manage=True,
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS, project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}], members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"], projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
+93
View File
@@ -492,6 +492,55 @@ def test_route_09_variants_partial_success():
assert resp.status_code == 502 assert resp.status_code == 502
def test_route_09b_display_selling_to_all_shops(monkeypatch):
monkeypatch.setenv("CAFE24_SHOP_NOS", "1,2,3")
no, cafe = _new_product()
created = _create_options(no, ["A", "B"])
a, b = (v["variant_code"] for v in created["variants"])
cafe.calls.clear()
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [
{"variant_code": a, "display": "off", "additional_amount": "500"},
{"variant_code": b, "custom_variant_code": "X1"}]})
assert resp.status_code == 200, resp.text
assert resp.json()["shop_failed"] == {}
puts = [c[2] for c in cafe.calls if c[0] == "PUT" and c[1].endswith("/variants")]
assert [p["shop_no"] for p in puts] == [1, 2, 3]
# 다른 쇼핑몰엔 진열·판매만, 진열/판매를 안 바꾼 행(b)은 안 보낸다
assert puts[1]["requests"] == puts[2]["requests"] == [{"variant_code": a, "display": "F"}]
# 다른 쇼핑몰 실패는 경고로만(기본몰 반영은 성공)
cafe._variant_puts = 0
cafe.fail_variant_chunk = 2
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [{"variant_code": a, "selling": "off"}]})
cafe.fail_variant_chunk = 0
assert resp.status_code == 200 and resp.json()["ok"]
assert list(resp.json()["shop_failed"]) == ["2"]
def test_sync_variant_flags_script(monkeypatch, capsys):
from app.integrations import cafe24 as integ
from app.integrations.cafe24 import products as cp
from app.modules.cafe24 import sync_variant_flags
no, cafe = _new_product()
created = _create_options(no, ["A", "B"])
a = created["variants"][0]["variant_code"]
before = [dict(v) for v in cafe.variants]
assert req("PUT", f"/cafe24/products/{no}/variants",
json={"rows": [{"variant_code": a, "display": "off"}]}).status_code == 200
cafe.stale_variants = before # 다른 쇼핑몰(과 지연된 GET)은 아직 진열함
monkeypatch.setenv("CAFE24_DB_URL", os.environ["CAFE24_TEST_DB_URL"])
monkeypatch.setattr(integ, "build_cafe24_api", lambda st, **kw: fakes.FakeApi(MULTI))
monkeypatch.setattr(cp, "list_all_products", lambda client: ([{"product_no": no}], False))
cafe.calls.clear()
assert sync_variant_flags.main(["--shops", "3"]) == 0
assert not [c for c in cafe.calls if c[0] == "PUT"] # 미리보기는 쓰지 않음
assert sync_variant_flags.main(["--shops", "3", "--apply"]) == 0
puts = [c[2] for c in cafe.calls if c[0] == "PUT"]
assert puts == [{"shop_no": 3, "requests": [{"variant_code": a, "display": "F"}]}]
assert "BEFORE" in capsys.readouterr().out
def test_route_10_rename_with_lagging_variants_keeps_rows(): def test_route_10_rename_with_lagging_variants_keeps_rows():
no, cafe = _new_product() no, cafe = _new_product()
created = _create_options(no, ["Black", "Red"]) created = _create_options(no, ["Black", "Red"])
@@ -583,6 +632,50 @@ def test_worker_real_db_success_and_needs_review():
assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED" assert q("SELECT status FROM cafe24_write_attempts WHERE schedule_id=%s", sid2)[0]["status"] == "RECORDED"
def test_schedule_main_image_route_and_worker():
"""대표 이미지 예약(006): 등록 → 파일 DB 보관 → 그 시각에 worker 가 교체 → 목록 미리보기."""
no, cafe = _new_product("<p>A</p>")
at = (now_kst() + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M")
png = b"\x89PNG\r\n\x1a\n" + b"x" * 64
form = {"product_no": str(no), "scheduled_at": at, "set_display": "", "set_selling": ""}
# 내용 없는 예약(이미지도 안 고름 — 이름 없는 빈 파트) 거부
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("", b"", "application/octet-stream")})
assert "하나 이상" in _location(resp).get("err", ""), resp.headers
# 이미지 아닌 파일 거부
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("a.txt", b"hi", "text/plain")})
assert "이미지만" in _location(resp).get("err", ""), resp.headers
resp = req("POST", "/cafe24/schedules", data=form, files={"image": ("가을.png", png, "image/png")})
assert "대표이미지" in _location(resp).get("msg", ""), resp.headers
sid = q("SELECT id FROM cafe24_product_schedules WHERE product_no=%s", no)[0]["id"]
row = ST.get_schedule(sid)
assert row["image_type"] == "image/png" and row["image_name"] == "가을.png" and row["revision_id"] is None
got = req("GET", f"/cafe24/schedules/{sid}/image")
assert got.status_code == 200 and got.content == png and got.headers["content-type"] == "image/png"
listed = json.loads(req("GET", "/cafe24/schedules").text.split("\n", 1)[1])["rows"]
mine = [r for r in listed if r["id"] == sid][0]
assert mine["image_type"] == "image/png" and mine["action_label"] == "대표이미지", mine
q("UPDATE cafe24_product_schedules SET scheduled_at = now() - interval '3000 days' WHERE id=%s RETURNING id", sid)
worker.process_once(ST, fakes.FakeApi(MULTI))
row = ST.get_schedule(sid)
assert row["status"] == "SUCCESS", row
posts = [c for c in cafe.calls if c[0] == "POST" and c[1].endswith("/images")]
assert len(posts) == 1 and posts[0][2]["request"]["detail_image"].startswith("data:image/png;base64,")
assert cafe.state["detail_image"] == f"/web/product/detail/{no}_1.png"
assert [c for c in cafe.calls if c[0] == "PUT"] == [] # 이미지만 — 상세설명·진열 PUT 없음
assert ST.get_write_snapshot(no)["product"]["data"]["detail_image"] == cafe.state["detail_image"]
# 이미지 + 진열을 한 예약에: 이미지 먼저, 그다음 진열 PUT
no2, cafe2 = _new_product("<p>A</p>")
sid2 = ST.create_schedule(product_no=no2, scheduled_at=now_kst() - timedelta(days=3000), revision_id=None,
set_display=False, set_selling=None, image=png, image_type="image/png", image_name="b.png")
worker.process_once(ST, fakes.FakeApi(MULTI))
assert ST.get_schedule(sid2)["status"] == "SUCCESS"
kinds = [(c[0], c[1].rsplit("/", 1)[-1]) for c in cafe2.calls if c[0] in ("POST", "PUT")]
assert kinds == [("POST", "images"), ("PUT", str(no2))], kinds
assert cafe2.state["display"] == "F" and cafe2.state["detail_image"].endswith(f"{no2}_1.png")
def test_worker_real_db_recovers_crash_after_remote_ok(): def test_worker_real_db_recovers_crash_after_remote_ok():
no, cafe = _new_product("<p>A</p>") no, cafe = _new_product("<p>A</p>")
rid = _draft(no, "<p>R</p>") rid = _draft(no, "<p>R</p>")
+62
View File
@@ -0,0 +1,62 @@
"""매일 하는 업무(033 tasks.repeat_daily) 알림 — 시각 고르기·수신자·중복. DB 없이 가짜 저장소로.
실제 DB(열·update_task 규칙)는 tests/test_project_module.py test_repeat_daily_* 가 본다.
"""
import importlib
import unittest
from datetime import date
from unittest.mock import patch
rem = importlib.import_module("app.modules.project.reminders")
class FakeStore:
def __init__(self, tasks):
self.tasks = tasks
self.sent = set()
self.made = []
def list_open_daily_tasks(self):
return list(self.tasks)
def add_reminder_notification(self, **kw):
key = (kw["task_id"], kw["kind"], kw["due_date"], kw["recipient_email"])
if key in self.sent:
return False
self.sent.add(key)
self.made.append(kw)
return True
def _visible(st, task, wanted, lookup=None):
return [e for e in wanted if e != "gone@x.kr"] # 권한 잃은 사람은 뺀다
class DailyAlertTests(unittest.TestCase):
def test_slot_is_latest_passed_time(self):
self.assertIsNone(rem.daily_slot(["09:00", "14:00"], "08:59"))
self.assertEqual(rem.daily_slot(["09:00", "14:00"], "09:00"), "09:00")
self.assertEqual(rem.daily_slot(["09:00", "14:00"], "23:59"), "14:00")
self.assertIsNone(rem.daily_slot([], "12:00"))
def test_assignee_else_followers_once_per_slot(self):
st = FakeStore([
{"id": 1, "title": "청소", "assignee_email": "A@x.kr", "followers": ["b@x.kr"], "project_id": 7, "project_name": "P"},
{"id": 2, "title": "보고", "assignee_email": "", "followers": ["b@x.kr", "gone@x.kr"], "project_id": 7},
])
with patch.object(rem.access, "filter_recipients", side_effect=_visible):
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 2)
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 0) # 같은 시각은 한 번
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="14:00"), 2) # 다음 시각은 또
first = st.made[0]
self.assertEqual((first["recipient_email"], first["kind"], first["ntype"]), ("a@x.kr", "daily@09:00", "daily"))
self.assertEqual(first["title"], "매일 업무: 청소")
self.assertEqual({m["recipient_email"] for m in st.made if m["task_id"] == 2}, {"b@x.kr"})
def test_daily_is_popup_alert_type(self):
api = importlib.import_module("app.modules.project.router")
self.assertIn("daily", api._ALERT_TYPES)
if __name__ == "__main__":
unittest.main()
+36
View File
@@ -1653,6 +1653,42 @@ def test_reorder_keeps_linked_card_position():
assert ST.get_task(task_id=lk["id"])["sort_order"] == lk["sort_order"] assert ST.get_task(task_id=lk["id"])["sort_order"] == lk["sort_order"]
def test_repeat_daily_task_and_alerts():
"""매일 하는 업무(2026-11-11, 마이그레이션 033) — [매일]이면 마감일을 비우고, 마감일을 고르면 꺼짐.
알림 데몬은 미완료 매일 업무의 담당자에게 시각마다 한 번(type=daily, 큰 팝업)."""
from datetime import date as _d
from app.modules.project import reminders
a = _project("P-daily", ADMIN, (ALICE,))
sa = _stage(a["id"], by=ADMIN)
t = ST.create_task(project_id=a["id"], title="매일 청소", stage_id=sa["id"], assignee_email=ALICE,
due_date="2026-12-01", created_by=ALICE)
r = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": None, "repeat_daily": True})
assert r.status_code == 200, r.text
got = r.json()["task"]
assert got["repeat_daily"] is True and got["due_date"] is None, got
assert req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"repeat_daily": "yes"}).status_code == 400
assert t["id"] in [x["id"] for x in ST.list_open_daily_tasks()]
today = _d(2026, 11, 11)
assert reminders.run_daily_alerts(ST, today=today, slot="09:00") >= 1
assert reminders.run_daily_alerts(ST, today=today, slot="09:00") == 0 # 같은 시각은 한 번
alerts = req("GET", "/project/api/notifications/alerts?after=0", ALICE).json()["alerts"]
assert any(n["type"] == "daily" and n["task_id"] == t["id"] for n in alerts), alerts
# 마감일을 고르면 매일 반복은 꺼진다(repeat_daily 를 안 보내도)
got = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": "2026-12-05"}).json()["task"]
assert got["repeat_daily"] is False and got["due_date"] == "2026-12-05", got
assert t["id"] not in [x["id"] for x in ST.list_open_daily_tasks()]
# 추가 칸(보드 새 업무·세부 업무)에서 [매일]로 만들기 — POST repeat_daily
r = req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE,
json={"title": "매일 점검", "stage_id": sa["id"], "due_date": None, "repeat_daily": True})
assert r.status_code == 201, r.text
assert r.json()["task"]["repeat_daily"] is True and "_newly_assigned" not in r.json()["task"]
r = req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE,
json={"title": "세부 매일", "parent_task_id": t["id"], "repeat_daily": True})
assert r.status_code == 201 and r.json()["task"]["repeat_daily"] is True, r.text
assert req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE, json={"title": "x", "repeat_daily": 1}).status_code == 400
assert ST.daily_ready() is True
def test_move_stage_to_other_project(): def test_move_stage_to_other_project():
"""섹션째 다른 프로젝트로(2026-10-26) — 섹션 + 업무 + 세부 업무(모든 단계), 섹션은 맨 끝, 연결 정리, 권한.""" """섹션째 다른 프로젝트로(2026-10-26) — 섹션 + 업무 + 세부 업무(모든 단계), 섹션은 맨 끝, 연결 정리, 권한."""
a = _project("P-smA", ADMIN, (ALICE, BOB)) a = _project("P-smA", ADMIN, (ALICE, BOB))

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