Compare commits
189 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 39d730faa0 | |||
| c3d3b5e8f3 | |||
| 137f6e4d98 | |||
| a29854b2cb | |||
| cc3e702204 | |||
| d4e4bc5dbf | |||
| 52e21a3a68 | |||
| 971666532e | |||
| 9cc508dc50 | |||
| 2a2c436013 | |||
| f486e6f263 | |||
| 90af8a8486 | |||
| 2237e2e799 | |||
| 96438d5078 | |||
| 038007c34e | |||
| 08fe894d1b | |||
| b95d3909a4 | |||
| cb69b086d7 | |||
| 86720d073e | |||
| 7540bc5610 | |||
| 96d33c668b | |||
| c1b3d7af59 | |||
| e64612a8d9 | |||
| 62c345bbb5 | |||
| ee728ed006 | |||
| 619f95b7f4 | |||
| fa7c55dee5 | |||
| 215b937f1e | |||
| f1e8dd5bf5 | |||
| fde37515c8 | |||
| f3b33d4084 | |||
| 86ea9a11d4 | |||
| b5bdf99069 | |||
| a475f0b2f6 | |||
| dcc6cd27b6 | |||
| 12f1d455b9 | |||
| 9429485236 | |||
| 451b37955e | |||
| 2ed275cd80 | |||
| 5d7862515f | |||
| 6121a27454 | |||
| 4c17158753 | |||
| 586a14f7f9 | |||
| 65a1fd1991 | |||
| e722d8ba1b | |||
| 6f3bffd840 | |||
| 80b7becd45 | |||
| 8051e7f207 | |||
| 7933f163b4 | |||
| 0836d6a926 | |||
| 36b1f49340 | |||
| b2710a0831 | |||
| 8bbb1f9ab2 | |||
| 8a597007cb | |||
| dc54553d2f | |||
| 527ec83b30 | |||
| abf03f0a80 | |||
| b397bdf83b | |||
| 32457e4ce8 | |||
| 94fac65238 | |||
| 1cabad8e3b | |||
| e753e55aa1 | |||
| 31db917eb8 | |||
| 59dd7e2ef9 | |||
| 30b0366818 | |||
| d6b15a6aec | |||
| ed7b2ef3ca | |||
| 70743394d8 | |||
| c7cc94a09c | |||
| edd5a97a9b | |||
| 5a4ceead3e | |||
| fa6bb33f11 | |||
| 5eaeee2f57 | |||
| 2e428aa07f | |||
| 4eda10df00 | |||
| 42d2671f80 | |||
| 66a99e2733 | |||
| 3ead7aa9f6 | |||
| e7b1e17579 | |||
| cd33c67df9 | |||
| 0bb23c32de | |||
| f0aae513af | |||
| 8ad8242c41 | |||
| 32877b1ce8 | |||
| 1550b5bb51 | |||
| 35c05e1b81 | |||
| 8b5498bc19 | |||
| bdd03a9ea4 | |||
| 0396cd6639 | |||
| f1f0db1bbe | |||
| 3061d44236 | |||
| 5e70ec1819 | |||
| e5d6a1188c | |||
| c23d1e3ce5 | |||
| bab495d9f2 | |||
| bbe27eac8b | |||
| 53896f0425 | |||
| db73faf270 | |||
| e3bc9d518d | |||
| 15a5eddf20 | |||
| e9fb1c3407 | |||
| 240d61c903 | |||
| e645f4beef | |||
| 4466601c58 | |||
| c3cab212b6 | |||
| b61c0897cc | |||
| 5c05f471b3 | |||
| 4e159e94e7 | |||
| db05538664 | |||
| ea7817752d | |||
| 67001f0a6e | |||
| c30ef72c6e | |||
| 581e0cf325 | |||
| e6b2812624 | |||
| 30fd2c5470 | |||
| 2df86983da | |||
| 90332bcb59 | |||
| 1c42ed5dd3 | |||
| 779cc79a87 | |||
| 1ba494dab8 | |||
| ef38140673 | |||
| 099271fdb2 | |||
| e6d38f342f | |||
| f8245b4499 | |||
| 9a8aea6435 | |||
| eab6b836d2 | |||
| deb5bfb9a1 | |||
| 4d3b747ab7 | |||
| 5471cbc32b | |||
| 4c94bf1293 | |||
| f36f7d3ad4 | |||
| 5bd0a5c406 | |||
| c317d7bb5d | |||
| 941b35a7a6 | |||
| ecc6405299 | |||
| 028831694a | |||
| 542e7fb7d1 | |||
| ac0f48bfce | |||
| 68bf43ea2f | |||
| cf7c44ce49 | |||
| db3b7d500d | |||
| d5fd617425 | |||
| bed3d4fc89 | |||
| 822c955bb6 | |||
| 20a79f5719 | |||
| b4edc16785 | |||
| 66db501170 | |||
| ac01a33c47 | |||
| 513aece27e | |||
| 1d3573a44a | |||
| 410d4fe05c | |||
| c15a746ae4 | |||
| da46abd678 | |||
| d38d00b4d2 | |||
| 8201fde606 | |||
| 70bf263a80 | |||
| 5a2c6ba2ad | |||
| 6ebf705e27 | |||
| 22490664d6 | |||
| 0c6dacb824 | |||
| 6345b69816 | |||
| 3882836fd5 | |||
| 59add598fa | |||
| ca2821464f | |||
| 24950c94ce | |||
| 454b3cc700 | |||
| dd1bc310dc | |||
| 53bead6691 | |||
| 36283ae265 | |||
| 89d204b2fe | |||
| 724b590868 | |||
| e130bbe577 | |||
| bc62e53270 | |||
| 6fd01314d5 | |||
| 1bdcd59287 | |||
| b7c0f28ad2 | |||
| 4320766abd | |||
| e934dd6abf | |||
| 18ac8f0761 | |||
| b5be26089d | |||
| 3a9a94f97b | |||
| c69bc0e9f3 | |||
| 833dbb5fdf | |||
| 2aa6b6efae | |||
| 1759e00213 | |||
| fa6e7066ae | |||
| 7cdca852bd | |||
| ee09e8bfd1 | |||
| ae6b6ec603 |
@@ -144,6 +144,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
|
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
|
||||||
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
|
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
|
||||||
|
|
||||||
|
# ─── 입출고 관리 모듈 (inout_db) — app/modules/inout ───
|
||||||
|
# 본사 → 공장 발주, 물류 입고, 미입고 관리. 미설정 시 "설정 필요" 안내만.
|
||||||
|
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
|
||||||
|
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
|
||||||
|
|
||||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||||
@@ -169,6 +174,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
|||||||
# APP_ENCRYPTION_KEY_V1=
|
# APP_ENCRYPTION_KEY_V1=
|
||||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||||
# PERFORMANCE_SYNC_DAYS=7
|
# PERFORMANCE_SYNC_DAYS=7
|
||||||
|
# 매출 자동 업데이트(웹 프로세스 안 스레드) — 기본 켜짐, 매일 09:00~19:00 정각·30분마다 오늘 포함 최근 10일.
|
||||||
|
# PERFORMANCE_AUTO_SYNC=false # 끄기
|
||||||
|
# PERFORMANCE_AUTO_SYNC_DAYS=10 # 가져올 기간(1~90일)
|
||||||
|
# PERFORMANCE_AUTO_SYNC_HOURS=9-19 # 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
|
||||||
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||||
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||||
|
|||||||
@@ -27,3 +27,11 @@ tests/js/.out/
|
|||||||
|
|
||||||
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||||
KING-DESKTOP.XML
|
KING-DESKTOP.XML
|
||||||
|
|
||||||
|
# Excel 가 파일을 열 때 만드는 잠금 파일
|
||||||
|
~$*
|
||||||
|
|
||||||
|
# 테스트 도구(docs/TESTING.md)
|
||||||
|
.pytest_cache/
|
||||||
|
tests/js/node_modules/
|
||||||
|
tests/js/package-lock.json
|
||||||
|
|||||||
+31
-1
@@ -24,8 +24,12 @@ from .modules.dispatch import build_dispatch_store
|
|||||||
from .modules.dispatch import router as dispatch_router
|
from .modules.dispatch import router as dispatch_router
|
||||||
from .modules.expense import CategoryStore, build_expense_store
|
from .modules.expense import CategoryStore, build_expense_store
|
||||||
from .modules.expense import router as expense_router
|
from .modules.expense import router as expense_router
|
||||||
|
from .modules.inout import build_inout_items, build_inout_store
|
||||||
|
from .modules.inout import router as inout_router
|
||||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||||
from .modules.malaysia import router as malaysia_router
|
from .modules.malaysia import router as malaysia_router
|
||||||
|
from .modules.notice import build_notice_store
|
||||||
|
from .modules.notice import router as notice_router
|
||||||
from .modules.performance import build_performance_store
|
from .modules.performance import build_performance_store
|
||||||
from .modules.performance import router as performance_router
|
from .modules.performance import router as performance_router
|
||||||
from .modules.project import build_project_store
|
from .modules.project import build_project_store
|
||||||
@@ -57,6 +61,7 @@ MODULE_LABELS: dict[str, str] = {
|
|||||||
"cafe24": "카페24 상품관리",
|
"cafe24": "카페24 상품관리",
|
||||||
"performance": "실적",
|
"performance": "실적",
|
||||||
"asset": "자산관리",
|
"asset": "자산관리",
|
||||||
|
"inout": "입출고 관리",
|
||||||
"expense_approver": "개인경비",
|
"expense_approver": "개인경비",
|
||||||
"vacation_approver": "휴가",
|
"vacation_approver": "휴가",
|
||||||
}
|
}
|
||||||
@@ -115,10 +120,14 @@ def build_google_oauth() -> OAuth:
|
|||||||
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
async def _lifespan(app_: FastAPI): # noqa: ANN201
|
||||||
"""앱 시작 시 백그라운드 작업 시작.
|
"""앱 시작 시 백그라운드 작업 시작.
|
||||||
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
- 프로젝트 업무 마감 알림(매일 1회, 기본 09시 KST) 스레드.
|
||||||
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py."""
|
PROJECT_REMINDERS=false 면 안 돈다. 상세는 app/modules/project/reminders.py.
|
||||||
|
- 실적 매출 자동 업데이트(09~19시 정각·30분, 최근 10일) 스레드.
|
||||||
|
PERFORMANCE_AUTO_SYNC=false 면 안 돈다. 상세는 app/modules/performance/auto_sync.py."""
|
||||||
|
from .modules.performance.auto_sync import start_auto_sync_thread # noqa: WPS433
|
||||||
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
from .modules.project.reminders import start_reminder_thread # noqa: WPS433
|
||||||
|
|
||||||
start_reminder_thread(getattr(app_.state, "project_store", None))
|
start_reminder_thread(getattr(app_.state, "project_store", None))
|
||||||
|
start_auto_sync_thread(app_.state)
|
||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
@@ -146,6 +155,8 @@ _MODULE_TEMPLATE_DIRS = [
|
|||||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||||
BASE_DIR / "modules" / "performance" / "templates",
|
BASE_DIR / "modules" / "performance" / "templates",
|
||||||
BASE_DIR / "modules" / "asset" / "templates",
|
BASE_DIR / "modules" / "asset" / "templates",
|
||||||
|
BASE_DIR / "modules" / "notice" / "templates",
|
||||||
|
BASE_DIR / "modules" / "inout" / "templates",
|
||||||
]
|
]
|
||||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||||
templates.env.loader = ChoiceLoader(
|
templates.env.loader = ChoiceLoader(
|
||||||
@@ -209,6 +220,12 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or 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)
|
||||||
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).
|
||||||
|
app.state.notice_store = build_notice_store(app.state.project_store)
|
||||||
|
# 입출고 관리(본사 → 공장 발주, 물류 입고, 미입고): INOUT_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||||
|
# 제품은 itemcode_db 단품(single_items) 읽기 전용 — ITEMCODE_DB_URL 재사용.
|
||||||
|
app.state.inout_store = build_inout_store(dsn=env("INOUT_DB_URL") or None)
|
||||||
|
app.state.inout_items = build_inout_items()
|
||||||
|
|
||||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||||
app.include_router(expense_router)
|
app.include_router(expense_router)
|
||||||
@@ -220,6 +237,8 @@ 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(asset_router)
|
app.include_router(asset_router)
|
||||||
|
app.include_router(notice_router)
|
||||||
|
app.include_router(inout_router)
|
||||||
|
|
||||||
|
|
||||||
def public_url_for(request: Request, route_name: str) -> str:
|
def public_url_for(request: Request, route_name: str) -> str:
|
||||||
@@ -412,6 +431,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
"status": "ready",
|
"status": "ready",
|
||||||
"category": "관리",
|
"category": "관리",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "inout",
|
||||||
|
"title": "입출고 관리",
|
||||||
|
"subtitle": "Inbound",
|
||||||
|
"description": "본사에서 공장으로 넣은 제작 발주와 물류 입고 수량을 맞춰 보고, 미입고·초과 입고를 관리합니다.",
|
||||||
|
"url": "/inout/",
|
||||||
|
"health_url": "/inout/health",
|
||||||
|
"status": "ready",
|
||||||
|
"category": "운영",
|
||||||
|
},
|
||||||
]
|
]
|
||||||
items.append({
|
items.append({
|
||||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||||
@@ -427,6 +456,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|||||||
def _icon_svg(name: str) -> str:
|
def _icon_svg(name: str) -> str:
|
||||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||||
paths = {
|
paths = {
|
||||||
|
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# [자산] 자산관리 모듈 — `app/modules/asset/`, `asset_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/ASSET_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/asset.css`, `app/static/asset.js`. 템플릿: `templates/`.
|
||||||
|
|
||||||
|
- 진입 `/asset/`, 권한키 `asset`. 사무집기·전산장비 개별 자산번호 등록.
|
||||||
|
- 배정/반납/상태·구매/보증·활동 이력, HWiNFO XML 사양/보고서 보존(`hwinfo.py`), 사진 갤러리(`media.py`), 보고서 모니터 자산(`monitors.py`).
|
||||||
|
- 삭제는 수퍼관리자(`SUPER_ADMIN_EMAIL`)만 — 이력/원본 보존.
|
||||||
|
- `ASSET_DB_URL` 미설정 시 저장 비활성, XML 분석 미리보기는 가능.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# [카페24] 카페24 상품관리 모듈 — `app/modules/cafe24/`, `cafe24_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/CAFE24_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
||||||
|
> 정적 파일: `app/static/cafe24.css`, `cafe24-options.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
|
> 공통 API 계층: `app/integrations/cafe24/` — **실적 모듈 카페24 어댑터도 같은 토큰을 씀**, 바꾸면 실적 영향 확인.
|
||||||
|
> 배포 시 이 모듈 변경이면 `dbx-cafe24-worker` 도 같이 재빌드.
|
||||||
|
|
||||||
|
## 기능
|
||||||
|
|
||||||
|
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||||
|
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널).
|
||||||
|
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||||
|
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||||
|
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
||||||
|
- 권한키 `cafe24`(연결/해제는 admin 전용).
|
||||||
|
|
||||||
|
## 규칙
|
||||||
|
|
||||||
|
- 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지.
|
||||||
|
- 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력.
|
||||||
|
- 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지).
|
||||||
|
- 예약은 DB 저장 + 별도 worker(`worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다.
|
||||||
|
|
||||||
|
## 읽기 지연 ("마지막 쓰기가 권위")
|
||||||
|
|
||||||
|
- **카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전 값을 돌려준다(읽기 지연)** — 우리 캐시 문제가 아니다.
|
||||||
|
- 상세설명: 카페24 값이 최근 revision 중 하나와 같으면 지연으로 보고 마지막 MANUAL/SCHEDULED 를 표시·지문 기준으로 씀(`store.resolve_description`).
|
||||||
|
- 스칼라(상품명·가격·이미지·진열/판매): PUT 응답 스냅샷(`cafe24_products.last_write_snapshot`, 마이그레이션 004)과 GET 의 `updated_date` 를 비교해 덮어씌움(`store.overlay_recent_write`).
|
||||||
|
- 유예시간 `CAFE24_READ_LAG_GRACE_MIN`(기본 360분).
|
||||||
|
- 쓰기 후 화면은 PUT 응답으로 그리고 다시 GET 하지 않는다.
|
||||||
|
- API 문서 예제는 apidocs.cafe24.com 청크 JS 에서 추출(예전 `/docs/code` JSON 은 404).
|
||||||
@@ -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=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||||
{% 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=20260918e" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||||
{% 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=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||||
{% 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=20260819c" />
|
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@@ -25,8 +25,25 @@ SECRET = "unit-test-secret"
|
|||||||
# wait_for_description 은 실물 카페24 API 의 쓰기 직후 읽기 지연을 흡수하려고
|
# wait_for_description 은 실물 카페24 API 의 쓰기 직후 읽기 지연을 흡수하려고
|
||||||
# 실제로 sleep 한다. 가짜 클라이언트는 그 지연을 재현하지 않으므로(항상 같은
|
# 실제로 sleep 한다. 가짜 클라이언트는 그 지연을 재현하지 않으므로(항상 같은
|
||||||
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
# 값을 돌려줌) 재시도 예산을 다 채우게 되는데, 테스트에서까지 그 시간을 그대로
|
||||||
# 기다릴 필요는 없다.
|
# 기다릴 필요는 없다. products.time 은 공유 time 모듈이라 import 때 바꾸면 다른 테스트의
|
||||||
products.time.sleep = lambda *_a, **_k: None
|
# time.sleep 까지 바뀐다 — 이 파일 테스트 동안만 바꾼다(pytest fixture / 직접 실행은 _run_all, 검토 F10).
|
||||||
|
_NO_SLEEP = lambda *_a, **_k: None # noqa: E731
|
||||||
|
|
||||||
|
try:
|
||||||
|
import pytest
|
||||||
|
except ImportError: # 직접 실행은 pytest 없이도 돈다
|
||||||
|
pytest = None
|
||||||
|
|
||||||
|
if pytest is not None:
|
||||||
|
@pytest.fixture(autouse=True, scope="module")
|
||||||
|
def _no_sleep_in_this_file():
|
||||||
|
prev = products.time.sleep
|
||||||
|
products.time.sleep = _NO_SLEEP
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
products.time.sleep = prev
|
||||||
|
|
||||||
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
# 장애 주입 테스트가 남기는 logger.exception 출력은 결과와 무관하다 — 조용히.
|
||||||
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
logging.getLogger("cafe24").setLevel(logging.CRITICAL)
|
||||||
|
|
||||||
@@ -1725,6 +1742,7 @@ def test_client_maybe_applied_classification():
|
|||||||
|
|
||||||
|
|
||||||
def _run_all():
|
def _run_all():
|
||||||
|
products.time.sleep = _NO_SLEEP # 직접 실행 = 이 프로세스는 이 파일 테스트만
|
||||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||||
for fn in fns:
|
for fn in fns:
|
||||||
fn()
|
fn()
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# [쿠팡] 쿠팡 밀크런 모듈 — `app/modules/cupang/`, `cupang_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 이 파일이 기준.
|
||||||
|
> 정적 파일: `app/static/cupang.css`, `app/static/cupang.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`).
|
||||||
|
|
||||||
|
## 출고 달력 / 상자 계산
|
||||||
|
|
||||||
|
- 출고 달력·상자 계산이 중심.
|
||||||
|
- 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다. 신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트.
|
||||||
|
- 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택.
|
||||||
|
- 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일 = 출고일 + 1일).
|
||||||
|
- 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷(혼합 상자 내용물·상자 종류 표시용).
|
||||||
|
- 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD).
|
||||||
|
- 양식 생성은 `export.py` 한 곳에서 만들어 xlsx·구글시트가 공유.
|
||||||
|
- 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기.
|
||||||
|
|
||||||
|
## 구글 시트 동기화
|
||||||
|
|
||||||
|
- `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시
|
||||||
|
확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip).
|
||||||
|
- 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제
|
||||||
|
(문서에 시트가 하나뿐이면 내용만 비움).
|
||||||
|
|
||||||
|
## 제품 포장무게
|
||||||
|
|
||||||
|
- 설정(제품명)에서 제품별 포장무게(g, `cupang_products.weight_g`, 마이그레이션 007 + 시드) 입력·표시·정렬.
|
||||||
|
- 출고 상세 상자 목록에 상자별 무게 합계(수량 × 지금 포장무게, `router._attach_box_weights`).
|
||||||
|
- 무게 없는 제품은 "일부 미입력".
|
||||||
|
- 화면은 kg 소수 첫째 자리 사사오입(`router._g_to_kg`) + 맨 아래 수량·무게 합계 행(앞 3열 병합).
|
||||||
|
- 표 칸 모두 가운데 정렬, 요약 카드와 20px 간격.
|
||||||
|
- 상자 목록 엑셀에도 무게(g) 열.
|
||||||
|
|
||||||
|
## 쿠팡 발주 엑셀 업로드
|
||||||
|
|
||||||
|
- 다중 업로드(`POST /cupang/api/box-calc/upload`, openpyxl).
|
||||||
|
- F13 입고예정일의 하루 전 = 출고일.
|
||||||
|
- 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 → 센터별 합산
|
||||||
|
→ 센터 단위로 상자 계산·자동 배분.
|
||||||
|
|
||||||
|
## 쿠팡 로켓 매출 (`/cupang/sales`)
|
||||||
|
|
||||||
|
- 테이블 `cupang_sales`·`cupang_sales_weekly`. 발주 라인별 공급가·원가·물류비·마진 표.
|
||||||
|
- 기간/센터/유형/검색 조회, 행 CRUD, 엑셀 다운로드.
|
||||||
|
- 구글 시트 양식 xlsx·csv 업로드(`sales_import.py`) — 같은 발주번호+SKU+출고일+센터+수량은 덮어씀.
|
||||||
|
- 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관, 순마진은 화면에서 계산.
|
||||||
|
- 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`.
|
||||||
@@ -11,6 +11,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import calendar as _calendar
|
import calendar as _calendar
|
||||||
import json
|
import json
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
from fractions import Fraction
|
from fractions import Fraction
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -413,6 +414,17 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
total_qty = sum(it["quantity"] for it in items)
|
total_qty = sum(it["quantity"] for it in items)
|
||||||
box_list = _expand_box_list(ship, calc, items)
|
box_list = _expand_box_list(ship, calc, items)
|
||||||
box_weight = _attach_box_weights(store, box_list)
|
box_weight = _attach_box_weights(store, box_list)
|
||||||
|
# 상자 목록 합계 행 — 수량 합계와 무게 합계(kg, 소수 첫째 자리)
|
||||||
|
box_qty_total = sum(int(it.get("quantity") or 0) for b in box_list for it in (b.get("items") or []))
|
||||||
|
box_weight_total = None
|
||||||
|
box_weight_partial = False
|
||||||
|
if box_weight:
|
||||||
|
for b in box_list:
|
||||||
|
b["weight_kg"] = _g_to_kg(b.get("weight_g"))
|
||||||
|
if b.get("weight_g") is not None:
|
||||||
|
box_weight_total = (box_weight_total or 0) + int(b["weight_g"])
|
||||||
|
if b.get("weight_missing"):
|
||||||
|
box_weight_partial = True
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
@@ -429,6 +441,9 @@ def detail(request: Request, shipment_id: int) -> HTMLResponse:
|
|||||||
"box_list": box_list,
|
"box_list": box_list,
|
||||||
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
# 상자별 무게 합계(g) 칸 — 포장무게(마이그레이션 007) 가 있을 때만
|
||||||
"box_weight": box_weight,
|
"box_weight": box_weight,
|
||||||
|
"box_qty_total": box_qty_total,
|
||||||
|
"box_weight_total_kg": _g_to_kg(box_weight_total),
|
||||||
|
"box_weight_partial": box_weight_partial,
|
||||||
"total_qty": total_qty,
|
"total_qty": total_qty,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -1190,6 +1205,14 @@ def _compute_boxes(store: Any, raw_items: list[Any]) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _g_to_kg(grams: Any) -> str | None:
|
||||||
|
"""g → kg 표시 글자 — 소수 둘째 자리에서 반올림(사사오입)해 첫째 자리까지. 예: 1,250g → "1.3"."""
|
||||||
|
if grams is None:
|
||||||
|
return None
|
||||||
|
kg = (Decimal(int(grams)) / 1000).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
|
||||||
|
return f"{kg:,.1f}"
|
||||||
|
|
||||||
|
|
||||||
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
def _attach_box_weights(store: Any, box_list: list[dict[str, Any]]) -> bool:
|
||||||
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
"""상자마다 무게 합계(g) — 상자에 든 제품마다 수량 × 포장무게(설정(제품명)의 지금 값, cupang_products.weight_g).
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<section class="cpg">
|
<section class="cpg">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
{# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261002x" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/cupang.css?v=20261013b" />{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
{# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #}
|
||||||
@@ -73,7 +73,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="cpg-sum-scroll">
|
<div class="cpg-sum-scroll cpg-boxno-scroll">
|
||||||
<table class="erp-table cpg-boxno-table">
|
<table class="erp-table cpg-boxno-table">
|
||||||
<colgroup>
|
<colgroup>
|
||||||
<col class="cpg-boxno-c-no" />
|
<col class="cpg-boxno-c-no" />
|
||||||
@@ -101,7 +101,7 @@
|
|||||||
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
<td class="cpg-boxno-weight" rowspan="{{ b['items']|length }}"
|
||||||
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
{% if miss %}title="포장무게 미입력: {{ miss|join(', ') }}{% if b.weight_g is not none %} — 이 제품을 뺀 합계{% endif %} (설정(제품명)에서 입력)"{% endif %}>
|
||||||
{%- if b.weight_g is not none -%}
|
{%- if b.weight_g is not none -%}
|
||||||
{{ "{:,}".format(b.weight_g) }}<span class="cpg-weight-unit">g</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
{{ b.weight_kg }}<span class="cpg-weight-unit">kg</span>{% if miss %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
</td>
|
</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -112,6 +112,23 @@
|
|||||||
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
<tr><td colspan="{{ 5 if box_weight else 4 }}" class="erp-muted">상자 정보가 없습니다.</td></tr>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
{% if box_list %}
|
||||||
|
{# 합계 행 — 수량 합계, 무게 합계(kg). 무게 없는 제품이 있으면 아는 무게만 더한 값 #}
|
||||||
|
<tfoot>
|
||||||
|
<tr class="cpg-boxno-total">
|
||||||
|
<td class="cpg-boxno-cell" colspan="3">합계</td>
|
||||||
|
<td class="cpg-calc-num">{{ "{:,}".format(box_qty_total) }}</td>
|
||||||
|
{% if box_weight %}
|
||||||
|
<td class="cpg-boxno-weight"
|
||||||
|
{% if box_weight_partial %}title="포장무게 미입력 제품이 있어 아는 무게만 더한 합계 (설정(제품명)에서 입력)"{% endif %}>
|
||||||
|
{%- if box_weight_total_kg is not none -%}
|
||||||
|
{{ box_weight_total_kg }}<span class="cpg-weight-unit">kg</span>{% if box_weight_partial %}<span class="cpg-boxno-wmiss">일부 미입력</span>{% endif %}
|
||||||
|
{%- else -%}<span class="erp-muted">—</span>{%- endif -%}
|
||||||
|
</td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
{% endif %}
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# [배송] 말레이시아 배송 모듈 — `app/modules/dispatch/`, `dispatch_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/DISPATCH_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/dispatch/`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
|
|
||||||
|
- TikTok·Shopee 출고관리. 권한키 `dispatch`.
|
||||||
|
- 플랫폼별 데이터 엑셀 업로드(TikTok = `03_TikTok_Order_Export.xlsx`, Shopee = `Packing List.Doorstep Delivery.xlsx`)
|
||||||
|
→ 1상자 = 1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성.
|
||||||
|
- 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산.
|
||||||
|
- 작업 상태 토글(`dispatch_logs` 기록).
|
||||||
|
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
|
||||||
|
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
|
||||||
|
- 엑셀은 openpyxl 파싱/생성.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# [경비] 개인경비 모듈 — `app/modules/expense/`, `expense_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드(`router.py`·`store.py`·`categories.py`)가 기준.
|
||||||
|
> 템플릿: `templates/`. DB 구성은 필요할 때만 `docs/DATABASES.md` 의 expense_db 절.
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
# [입출고] 입출고 관리 모듈 — `app/modules/inout/`, `inout_db`(2026-10-16)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/INOUT_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/inout.css`, `inout.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db.single_items` 읽기 전용(`itemcode.py`). `APP_ENCRYPTION_KEY` 는 실적 모듈과 공유.
|
||||||
|
> 참고 모델: 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결.
|
||||||
|
|
||||||
|
## 발주 / 입고
|
||||||
|
|
||||||
|
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
|
||||||
|
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||||
|
- 미입고 현황(제품별 합계·발주별·지연).
|
||||||
|
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
|
||||||
|
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||||
|
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||||
|
- 잔량 종결·취소(취소는 입고 없을 때만).
|
||||||
|
- 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`).
|
||||||
|
- 모든 품목 입고완료·초과입고 = "✓ 전체 입고 완료"(초과면 "초과 포함", `order_badge`).
|
||||||
|
- 발주 삭제는 **수퍼관리자만**(발주 목록 🗑, `perms.super`, 입고·사진·메일 기록까지 CASCADE).
|
||||||
|
|
||||||
|
## 권한 / 옵션
|
||||||
|
|
||||||
|
- 권한키 `inout`(조회).
|
||||||
|
- **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션** — 상단 톱니 → 팝업(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`). 관리자는 둘 다.
|
||||||
|
- 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음.
|
||||||
|
- **입고 담당(발주 담당 아님)은 품목을 이름·발주 수량만**(`items_limited`), 옵션은 관리자만.
|
||||||
|
|
||||||
|
## 발주 메일 (003)
|
||||||
|
|
||||||
|
- 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 보냄.
|
||||||
|
- **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`).
|
||||||
|
- 보낸 기록·재발송 확인.
|
||||||
|
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
|
||||||
|
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
|
||||||
|
|
||||||
|
## 입고 요청 메일 (005, 2026-10-19)
|
||||||
|
|
||||||
|
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||||
|
- 받는 사람 = 옵션 → **물류센터** 탭 담당자 이메일(`inout_settings` `logistics_emails`), 참조 기본 = `receipt_mail_cc`(005 가 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 넣음). 창에서 고칠 수 있음.
|
||||||
|
- 제목 `[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.`(입고일) · 본문 "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + 표(상품 이름·상품 코드·입고 수량·비고 = 발주 품목 줄 메모, 합계) + 메모 + **맨 아래 입고증 사진 = 본문 안 이미지**(CID `multipart/related`, 첨부 아님 — `gmail.build_message(inline_images=)`), 서버가 가로 600px 이하·비율 유지 JPEG 로 줄임(`store.mail_images`, EXIF 회전 반영, HEIC 는 빼고 안내). 미리보기는 cid → data: 로 바꿔 보여 줌.
|
||||||
|
- 보낸 기록 `inout_receipt_mails`(입고 지우면 CASCADE), 이미 보낸 입고는 `resend` 확인.
|
||||||
|
|
||||||
|
## 사방넷 입고 파일 (2026-10-19, 마이그레이션 없음)
|
||||||
|
|
||||||
|
- 입고 기록 줄 [사방넷 입고 파일](엑셀 초록 `#217346`) → `GET /inout/orders/{id}/receipts/{rid}/sabangnet.xlsx`(발주·입고 담당). 1행 제목 **A 상품코드 · B 가용수량 · C 불용수량**,
|
||||||
|
A = 코드표 `single_items.sabangnet_code`(`itemcode.sabangnet_codes`), B = 입고 수량, **C = 수량이 아니라 상품 이름**(사용자 지정). A·C 는 글자 칸(앞자리 0 보존).
|
||||||
|
- 사방넷 코드가 빈 품목이 있거나 코드표를 못 읽으면 파일을 만들지 않고 발주서로 돌아가 품목을 알려 준다(빈 칸 업로드 방지). 파일 이름 `사방넷_입고_{입고일}_{발주번호}.xlsx`.
|
||||||
|
|
||||||
|
## 입고증 사진 (003)
|
||||||
|
|
||||||
|
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||||
|
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||||
|
|
||||||
|
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||||
|
|
||||||
|
- 테이블 `inout_products`·`inout_products_excluded`.
|
||||||
|
- [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기).
|
||||||
|
- 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동).
|
||||||
|
- 한 번 불러오면 발주서 제품은 이 목록에서. 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`).
|
||||||
|
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
|
||||||
|
- **발주 메일 표**(2026-10-19, `store.order_mail`): 전체 무게(kg) = 개당 g × 수량 · **PP 사용량(kg)** = 전체 무게 − 은 무게(은 함유량 왼쪽 열) · 은(Ag) 함유량 = `30% (76.5kg)`(괄호 = 전체 무게 × %, kg 소수 넷째). 합계 줄·요약(전체 무게·PP 사용량·은 총량)도 kg. 첫 요약 표는 항목·값 두 쌍씩 4열(4×4), 요청 사항은 맨 아래 한 줄 전체. 발주서 화면 표는 예전 그대로(PP g/개).
|
||||||
|
|
||||||
|
## 시각 / 날짜
|
||||||
|
|
||||||
|
- 시각은 DB 시간대와 무관하게 KST 로 읽음(`db._KstTimestamptzLoader`).
|
||||||
|
- 날짜 서식은 모두 `yyyy.mm.dd(요일)`(`ymd`·`ymdhm` 매크로, `store.fmt_date`).
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""입출고 관리(inout) 모듈 — 본사 → 공장 제품 제작 발주, 물류 입고(분할), 발주 대비 미입고·초과 관리.
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/inout)
|
||||||
|
- 저장소: `db.py` (inout_db / PostgreSQL) + `store.py` (상태·검사, 순수 함수)
|
||||||
|
- 제품: `itemcode.py` — itemcode_db.single_items(단품) 읽기 전용(ITEMCODE_DB_URL 재사용)
|
||||||
|
- 템플릿: `templates/inout/`, 화면 스크립트·스타일 `static/inout.{js,css}`
|
||||||
|
|
||||||
|
INOUT_DB_URL 미설정이면 build_inout_store 가 None → 라우터가 "설정 필요" 안내(앱은 죽지 않음).
|
||||||
|
권한: 모듈 권한키 `inout`(조회), 발주 담당·입고 담당은 모듈 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션.
|
||||||
|
상세 docs/INOUT_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_inout_store", "build_inout_items"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_inout_store(*, dsn: str | None) -> Any:
|
||||||
|
if not dsn:
|
||||||
|
return None
|
||||||
|
from .db import InoutDBStore # 지연 import
|
||||||
|
|
||||||
|
return InoutDBStore(dsn)
|
||||||
|
|
||||||
|
|
||||||
|
def build_inout_items() -> Any:
|
||||||
|
"""코드표 단품 리더(ITEMCODE_DB_URL). 미설정이면 enabled=False."""
|
||||||
|
from .itemcode import SingleItemReader # 지연 import
|
||||||
|
|
||||||
|
return SingleItemReader()
|
||||||
@@ -0,0 +1,669 @@
|
|||||||
|
"""inout_db PostgreSQL 저장소 — 공장·담당자·발주서·입고.
|
||||||
|
|
||||||
|
- 드라이버: psycopg 3 + pool(다른 모듈과 같은 패턴), 연결 `INOUT_DB_URL`. 스키마는 scripts/sql/inout_db_init.sql(앱이 만들지 않음).
|
||||||
|
- 상태(발주·부분입고·입고완료·초과·종결·취소)는 저장하지 않고 품목별 누적 입고로 계산한다(store.order_status) — 어긋날 일이 없다.
|
||||||
|
- 쓰기는 한 트랜잭션. 입고 저장은 발주서 행을 잠그고(FOR UPDATE) 그 안에서 누적 입고를 다시 읽어 초과를 판단한다
|
||||||
|
(두 사람이 동시에 입고해도 초과 확인을 건너뛰지 않게).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg.errors import UndefinedColumn, UndefinedTable
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg.types.datetime import TimestamptzLoader
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
|
||||||
|
|
||||||
|
|
||||||
|
class OverReceipt(Exception):
|
||||||
|
"""확인 없이 발주보다 많이 입고하려 함 — over = [{item_code, item_name, ordered, after, over}]."""
|
||||||
|
|
||||||
|
def __init__(self, over: list[dict[str, Any]]) -> None:
|
||||||
|
super().__init__("초과 입고")
|
||||||
|
self.over = over
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_email(e: str) -> str:
|
||||||
|
return (e or "").strip().lower()
|
||||||
|
|
||||||
|
|
||||||
|
class _KstTimestamptzLoader(TimestamptzLoader):
|
||||||
|
"""TIMESTAMPTZ → 한국 시각(KST) datetime. 화면·메일에 찍는 시각(입력·보낸 시각 등)이 DB 서버 시간대(보통 UTC)와 무관하게."""
|
||||||
|
|
||||||
|
def load(self, data: Any) -> datetime:
|
||||||
|
return super().load(data).astimezone(KST)
|
||||||
|
|
||||||
|
|
||||||
|
def _kst_session(conn: Any) -> None:
|
||||||
|
# 세션 시간대(SET TIME ZONE)는 쓰지 않는다 — 'Asia/Seoul' 은 시간대 자료가 없는 서버에서 접속이 실패하고,
|
||||||
|
# 고정 오프셋은 psycopg 가 못 읽어 UTC 로 돌아간다. 읽을 때 파이썬에서 바꾼다.
|
||||||
|
conn.adapters.register_loader("timestamptz", _KstTimestamptzLoader)
|
||||||
|
|
||||||
|
|
||||||
|
class InoutDBStore:
|
||||||
|
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 5):
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, configure=_kst_session, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._pool.close()
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 공장
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def list_factories(self, *, include_inactive: bool = False) -> list[dict[str, Any]]:
|
||||||
|
where = "" if include_inactive else "WHERE f.is_active"
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT f.*, (SELECT count(*) FROM inout_orders o WHERE o.factory_id = f.id) AS order_count "
|
||||||
|
f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name"
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", email: str = "",
|
||||||
|
memo: str = "", is_active: bool = True, sort_order: int = 0) -> int:
|
||||||
|
"""공장 추가·수정. 담당자(manager, 002)·연락처(contact)·이메일(email, 003 — 여러 개는 쉼표)."""
|
||||||
|
name = (name or "").strip()
|
||||||
|
if not name or len(name) > 100:
|
||||||
|
raise ValueError("공장 이름을 1~100자로 입력하세요.")
|
||||||
|
emails = ", ".join(store.parse_emails(email, label="공장 이메일"))
|
||||||
|
vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], emails, (memo or "").strip()[:store.MEMO_MAX],
|
||||||
|
bool(is_active), int(sort_order))
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
dup = conn.execute("SELECT id FROM inout_factories WHERE lower(name) = lower(%s) AND id <> %s",
|
||||||
|
(name, factory_id or 0)).fetchone()
|
||||||
|
if dup:
|
||||||
|
raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}")
|
||||||
|
if factory_id:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE inout_factories SET name=%s, manager=%s, contact=%s, email=%s, memo=%s, is_active=%s, sort_order=%s "
|
||||||
|
"WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("공장을 찾을 수 없습니다.")
|
||||||
|
return int(row["id"])
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO inout_factories (name, manager, contact, email, memo, is_active, sort_order) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"])
|
||||||
|
except UndefinedColumn:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 002·003(공장 담당자·이메일 칸)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_factory(self, factory_id: int) -> None:
|
||||||
|
"""발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
used = conn.execute("SELECT 1 FROM inout_orders WHERE factory_id=%s LIMIT 1", (factory_id,)).fetchone()
|
||||||
|
if used:
|
||||||
|
raise ValueError("발주 기록이 있는 공장은 지울 수 없습니다 — '사용 안 함'으로 바꾸세요.")
|
||||||
|
conn.execute("DELETE FROM inout_factories WHERE id=%s", (factory_id,))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 담당자(발주 담당·입고 담당)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def list_roles(self) -> dict[str, list[str]]:
|
||||||
|
out: dict[str, list[str]] = {r: [] for r in store.ROLES}
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
for r in conn.execute("SELECT email, role FROM inout_roles ORDER BY email").fetchall():
|
||||||
|
out.setdefault(r["role"], []).append(r["email"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def roles_of(self, email: str) -> set[str]:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT role FROM inout_roles WHERE email=%s", (_norm_email(email),)).fetchall()
|
||||||
|
return {r["role"] for r in rows}
|
||||||
|
|
||||||
|
def set_role_members(self, role: str, emails: list[str], *, by: str) -> None:
|
||||||
|
"""그 역할 담당자를 통째로 바꾼다(한 트랜잭션)."""
|
||||||
|
if role not in store.ROLES:
|
||||||
|
raise ValueError("알 수 없는 담당 종류입니다.")
|
||||||
|
clean = sorted({_norm_email(e) for e in emails if _norm_email(e)})
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
conn.execute("DELETE FROM inout_roles WHERE role=%s AND NOT (email = ANY(%s))", (role, clean))
|
||||||
|
for e in clean:
|
||||||
|
conn.execute("INSERT INTO inout_roles (email, role, created_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
|
||||||
|
(e, role, _norm_email(by)))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주서
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _insert_line(self, conn: Any, order_id: int, line_no: int, ln: dict[str, Any], names: dict[str, str],
|
||||||
|
specs: dict[str, dict[str, Any]]) -> None:
|
||||||
|
"""발주 품목 한 줄 — 004 가 적용됐으면 상품 정보의 단가·무게·은 함유량을 그때 값으로 함께 남긴다."""
|
||||||
|
if self.products_ready():
|
||||||
|
sp = specs.get(ln["item_code"]) or {}
|
||||||
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo, unit_price, weight_g, silver_pct) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"],
|
||||||
|
sp.get("unit_price"), sp.get("weight_g"), sp.get("silver_pct")))
|
||||||
|
else:
|
||||||
|
conn.execute("INSERT INTO inout_order_lines (order_id, line_no, item_code, item_name, qty, memo) VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, line_no, ln["item_code"], names.get(ln["item_code"], ""), ln["qty"], ln["memo"]))
|
||||||
|
|
||||||
|
def create_order(self, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||||
|
specs: dict[str, dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
"""data = store.validate_order 결과, names = {코드: 단품 이름}, specs = {코드: 상품 정보 행}(004). 반환 {id, order_no}."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._require_factory(conn, data["factory_id"])
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(hashtext('inout_order_no'))")
|
||||||
|
prefix = store.order_no(data["order_date"], 0)[:-2]
|
||||||
|
# 순번은 숫자로 비교 — 글자 max 면 "-99" 가 "-100" 보다 커서 100번째부터 같은 번호가 나온다
|
||||||
|
row = conn.execute("SELECT max(substr(order_no, %s)::int) AS m FROM inout_orders "
|
||||||
|
"WHERE order_no LIKE %s AND substr(order_no, %s) ~ '^[0-9]{1,9}$'",
|
||||||
|
(len(prefix) + 1, prefix + "%", len(prefix) + 1)).fetchone()
|
||||||
|
seq = (row["m"] or 0) + 1 if row else 1
|
||||||
|
no = store.order_no(data["order_date"], seq)
|
||||||
|
oid = conn.execute(
|
||||||
|
"INSERT INTO inout_orders (order_no, factory_id, order_date, due_date, memo, created_by, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(no, data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), _norm_email(by)),
|
||||||
|
).fetchone()["id"]
|
||||||
|
for i, ln in enumerate(data["lines"], start=1):
|
||||||
|
self._insert_line(conn, oid, i, ln, names, specs or {})
|
||||||
|
return {"id": int(oid), "order_no": no}
|
||||||
|
|
||||||
|
def update_order(self, order_id: int, data: dict[str, Any], names: dict[str, str], *, by: str,
|
||||||
|
specs: dict[str, dict[str, Any]] | None = None) -> None:
|
||||||
|
"""머리글·품목 고치기. 입고된 품목은 뺄 수 없다(입고 기록이 사라지므로) — 수량은 바꿀 수 있다.
|
||||||
|
이미 있던 품목의 단가 등 사본은 그대로(발주 당시 값), 새로 넣은 품목만 지금 상품 정보 값으로(004)."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서는 고칠 수 없습니다.")
|
||||||
|
self._require_factory(conn, data["factory_id"], allow_inactive_id=head["factory_id"])
|
||||||
|
existing = {r["item_code"]: r for r in conn.execute(
|
||||||
|
"SELECT l.id, l.item_code, COALESCE(sum(rl.qty), 0) AS received FROM inout_order_lines l "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s GROUP BY l.id",
|
||||||
|
(order_id,)).fetchall()}
|
||||||
|
wanted = {ln["item_code"] for ln in data["lines"]}
|
||||||
|
blocked = [c for c, r in existing.items() if c not in wanted and int(r["received"]) > 0]
|
||||||
|
if blocked:
|
||||||
|
raise ValueError("입고 기록이 있는 품목은 뺄 수 없습니다: " + ", ".join(sorted(blocked)))
|
||||||
|
for code, r in existing.items():
|
||||||
|
if code not in wanted:
|
||||||
|
conn.execute("DELETE FROM inout_order_lines WHERE id=%s", (r["id"],))
|
||||||
|
for i, ln in enumerate(data["lines"], start=1):
|
||||||
|
if ln["item_code"] in existing:
|
||||||
|
conn.execute("UPDATE inout_order_lines SET line_no=%s, qty=%s, memo=%s WHERE id=%s",
|
||||||
|
(i, ln["qty"], ln["memo"], existing[ln["item_code"]]["id"]))
|
||||||
|
else:
|
||||||
|
self._insert_line(conn, order_id, i, ln, names, specs or {})
|
||||||
|
conn.execute("UPDATE inout_orders SET factory_id=%s, order_date=%s, due_date=%s, memo=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(data["factory_id"], data["order_date"], data["due_date"], data["memo"], _norm_email(by), order_id))
|
||||||
|
|
||||||
|
def set_closed(self, order_id: int, *, closed: bool, reason: str = "", by: str) -> None:
|
||||||
|
"""종결(남은 미입고를 더 기다리지 않음) / 종결 풀기."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
if closed:
|
||||||
|
conn.execute("UPDATE inout_orders SET closed_at=now(), closed_by=%s, close_reason=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), (reason or "").strip()[:store.MEMO_MAX], _norm_email(by), order_id))
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE inout_orders SET closed_at=NULL, closed_by='', close_reason='', updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), order_id))
|
||||||
|
|
||||||
|
def cancel_order(self, order_id: int, *, by: str) -> None:
|
||||||
|
"""잘못 넣은 발주 — 입고 기록이 없을 때만 취소(기록은 남김)."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
if conn.execute("SELECT 1 FROM inout_receipts WHERE order_id=%s LIMIT 1", (order_id,)).fetchone():
|
||||||
|
raise ValueError("입고 기록이 있는 발주서는 취소할 수 없습니다 — 남은 수량은 '종결'하세요.")
|
||||||
|
conn.execute("UPDATE inout_orders SET cancelled_at=now(), cancelled_by=%s, updated_by=%s WHERE id=%s",
|
||||||
|
(_norm_email(by), _norm_email(by), order_id))
|
||||||
|
|
||||||
|
def delete_order(self, order_id: int) -> dict[str, Any]:
|
||||||
|
"""발주서 완전 삭제(수퍼관리자) — 품목·입고 기록·입고증 사진·메일 기록까지 함께(CASCADE). 되돌릴 수 없다.
|
||||||
|
반환 {order_no, receipts} — 화면 안내·로그용."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
n = conn.execute("SELECT count(*) AS n FROM inout_receipts WHERE order_id=%s", (order_id,)).fetchone()["n"]
|
||||||
|
row = conn.execute("DELETE FROM inout_orders WHERE id=%s RETURNING order_no", (order_id,)).fetchone()
|
||||||
|
return {"order_no": row["order_no"], "receipts": int(n)}
|
||||||
|
|
||||||
|
def get_order(self, order_id: int) -> dict[str, Any] | None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
head = conn.execute(
|
||||||
|
# 담당자(manager)는 002 열 — 미적용 DB 에서도 깨지지 않게 to_jsonb 로 읽는다
|
||||||
|
"SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact, "
|
||||||
|
"COALESCE(to_jsonb(f) ->> 'email', '') AS factory_email "
|
||||||
|
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s",
|
||||||
|
(order_id,)).fetchone()
|
||||||
|
if not head:
|
||||||
|
return None
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.*, COALESCE(sum(rl.qty), 0)::int AS received FROM inout_order_lines l "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id WHERE l.order_id=%s "
|
||||||
|
"GROUP BY l.id ORDER BY l.line_no", (order_id,)).fetchall()
|
||||||
|
receipts = conn.execute("SELECT * FROM inout_receipts WHERE order_id=%s ORDER BY receipt_date, id",
|
||||||
|
(order_id,)).fetchall()
|
||||||
|
rlines = conn.execute(
|
||||||
|
"SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl "
|
||||||
|
"JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id "
|
||||||
|
"WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall()
|
||||||
|
# 입고증 사진(목록만 — 내용은 /inout/photos/{id})·발주 메일 기록 — 003 미적용이면 빈 목록
|
||||||
|
try:
|
||||||
|
photos = conn.execute(
|
||||||
|
"SELECT p.id, p.receipt_id, p.filename, p.content_type, p.size_bytes FROM inout_receipt_photos p "
|
||||||
|
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE r.order_id=%s ORDER BY p.id", (order_id,)).fetchall()
|
||||||
|
mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
photos, mails = [], []
|
||||||
|
# 입고 요청 메일 기록(005) — 미적용이면 빈 목록
|
||||||
|
try:
|
||||||
|
rmails = conn.execute(
|
||||||
|
"SELECT m.* FROM inout_receipt_mails m JOIN inout_receipts r ON r.id = m.receipt_id "
|
||||||
|
"WHERE r.order_id=%s ORDER BY m.sent_at, m.id", (order_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
rmails = []
|
||||||
|
by_rmail: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for m in rmails:
|
||||||
|
by_rmail.setdefault(int(m["receipt_id"]), []).append(m)
|
||||||
|
by_photo: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for ph in photos:
|
||||||
|
by_photo.setdefault(int(ph["receipt_id"]), []).append(ph)
|
||||||
|
by_receipt: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for r in rlines:
|
||||||
|
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
|
||||||
|
lines = store.decorate_lines(lines)
|
||||||
|
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
|
||||||
|
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
|
||||||
|
"status_label": store.ORDER_LABELS[status],
|
||||||
|
"receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []),
|
||||||
|
"mails": by_rmail.get(int(r["id"]), []),
|
||||||
|
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts],
|
||||||
|
"mails": mails}
|
||||||
|
|
||||||
|
def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "",
|
||||||
|
date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
||||||
|
"""목록 — 상태는 품목 합계로 계산한 뒤 거른다. q = 발주번호·제품 코드·제품 이름."""
|
||||||
|
where, params = ["TRUE"], []
|
||||||
|
if factory_id:
|
||||||
|
where.append("o.factory_id = %s")
|
||||||
|
params.append(factory_id)
|
||||||
|
if date_from:
|
||||||
|
where.append("o.order_date >= %s")
|
||||||
|
params.append(date_from)
|
||||||
|
if date_to:
|
||||||
|
where.append("o.order_date <= %s")
|
||||||
|
params.append(date_to)
|
||||||
|
if q.strip():
|
||||||
|
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
where.append("(o.order_no ILIKE %s OR EXISTS (SELECT 1 FROM inout_order_lines x WHERE x.order_id = o.id "
|
||||||
|
"AND (x.item_code ILIKE %s OR x.item_name ILIKE %s)))")
|
||||||
|
params += [like, like, like]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
heads = conn.execute(
|
||||||
|
"SELECT o.*, f.name AS factory_name FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
# 상태는 품목 합계로 계산해 아래에서 거르므로 넉넉히 읽는다(발주서는 많아야 연 수천 건)
|
||||||
|
f"WHERE {' AND '.join(where)} ORDER BY o.order_date DESC, o.id DESC LIMIT {_SCAN_LIMIT}", params
|
||||||
|
).fetchall()
|
||||||
|
ids = [h["id"] for h in heads]
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.order_id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
"WHERE l.order_id = ANY(%s) GROUP BY l.id ORDER BY l.line_no", (ids,)).fetchall() if ids else []
|
||||||
|
by_order: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for ln in lines:
|
||||||
|
by_order.setdefault(int(ln["order_id"]), []).append(ln)
|
||||||
|
allowed = store.STATUS_FILTERS.get(status, store.STATUS_FILTERS["active"])[1]
|
||||||
|
out = []
|
||||||
|
for h in heads:
|
||||||
|
ls = by_order.get(int(h["id"]), [])
|
||||||
|
st = store.order_status(ls, closed=bool(h["closed_at"]), cancelled=bool(h["cancelled_at"]))
|
||||||
|
if st not in allowed:
|
||||||
|
continue
|
||||||
|
names = [x["item_name"] or x["item_code"] for x in ls]
|
||||||
|
out.append({**h, "status": st, "status_label": store.ORDER_LABELS[st], "summary": store.summarize(ls),
|
||||||
|
"line_count": len(ls), "items_label": (names[0] + (f" 외 {len(names) - 1}종" if len(names) > 1 else "")) if names else ""})
|
||||||
|
if len(out) >= limit:
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
|
||||||
|
confirm_over: bool, by: str, photos: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
"""입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함).
|
||||||
|
photos = store.validate_photos 결과(입고증) — 입고와 한 트랜잭션(사진 저장이 실패하면 입고도 저장 안 함)."""
|
||||||
|
try:
|
||||||
|
return self._add_receipt(order_id, quantities, receipt_date=receipt_date, memo=memo,
|
||||||
|
confirm_over=confirm_over, by=by, photos=photos or [])
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않아 사진을 저장할 수 없습니다 — "
|
||||||
|
"사진 없이 저장하거나 관리자에게 알려 주세요.") from None
|
||||||
|
|
||||||
|
def _add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
|
||||||
|
confirm_over: bool, by: str, photos: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서에는 입고할 수 없습니다.")
|
||||||
|
if head["closed_at"]:
|
||||||
|
raise ValueError("종결된 발주서입니다 — 입고하려면 발주 담당이 종결을 풀어야 합니다.")
|
||||||
|
lines = conn.execute(
|
||||||
|
"SELECT l.id, l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
"WHERE l.order_id=%s GROUP BY l.id", (order_id,)).fetchall()
|
||||||
|
# 전체 입고 완료(모든 품목 입고 ≥ 발주)면 더 받지 않는다(2026-10-19) — 화면은 버튼을 막고, 서버도 거절(잠근 뒤 판단)
|
||||||
|
if lines and all(int(x["received"]) >= int(x["qty"]) for x in lines):
|
||||||
|
raise ValueError("전체 입고가 완료된 발주서입니다 — 더 입고할 수 없습니다(잘못 넣은 입고는 입고 기록에서 지운 뒤 다시 넣으세요).")
|
||||||
|
data = store.validate_receipt(lines, quantities, receipt_date=receipt_date, memo=memo)
|
||||||
|
if data["over"] and not confirm_over:
|
||||||
|
raise OverReceipt(data["over"])
|
||||||
|
rid = conn.execute("INSERT INTO inout_receipts (order_id, receipt_date, memo, created_by) VALUES (%s,%s,%s,%s) RETURNING id",
|
||||||
|
(order_id, data["receipt_date"], data["memo"], _norm_email(by))).fetchone()["id"]
|
||||||
|
for it in data["items"]:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)",
|
||||||
|
(rid, it["order_line_id"], it["qty"]))
|
||||||
|
self._insert_photos(conn, int(rid), photos, by)
|
||||||
|
return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"]), "photos": len(photos)}
|
||||||
|
|
||||||
|
# ── 입고증 사진(003) ──
|
||||||
|
@staticmethod
|
||||||
|
def _insert_photos(conn: Any, receipt_id: int, photos: list[dict[str, Any]], by: str) -> None:
|
||||||
|
for ph in photos:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_photos (receipt_id, filename, content_type, size_bytes, data, created_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(receipt_id, ph["filename"], ph["content_type"], len(ph["data"]), ph["data"], _norm_email(by)))
|
||||||
|
|
||||||
|
def add_receipt_photos(self, order_id: int, receipt_id: int, files: list[tuple[str, bytes]], *, by: str) -> int:
|
||||||
|
"""이미 있는 입고에 사진 더하기(빠뜨렸을 때). 장수 한도는 잠근 뒤 다시 센다. 반환 = 더한 장수."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
if not conn.execute("SELECT 1 FROM inout_receipts WHERE id=%s AND order_id=%s", (receipt_id, order_id)).fetchone():
|
||||||
|
raise ValueError("입고 기록을 찾을 수 없습니다.")
|
||||||
|
have = int(conn.execute("SELECT count(*) AS n FROM inout_receipt_photos WHERE receipt_id=%s",
|
||||||
|
(receipt_id,)).fetchone()["n"])
|
||||||
|
photos = store.validate_photos(files, existing=have)
|
||||||
|
if not photos:
|
||||||
|
raise ValueError("올릴 사진을 고르세요.")
|
||||||
|
self._insert_photos(conn, receipt_id, photos, by)
|
||||||
|
return len(photos)
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_receipt_photo(self, order_id: int, photo_id: int) -> None:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
self._lock_order(conn, order_id)
|
||||||
|
row = conn.execute("DELETE FROM inout_receipt_photos p USING inout_receipts r "
|
||||||
|
"WHERE p.id=%s AND p.receipt_id = r.id AND r.order_id=%s RETURNING p.id",
|
||||||
|
(photo_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("사진을 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
||||||
|
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT p.id, p.filename, p.content_type, p.data, r.order_id FROM inout_receipt_photos p "
|
||||||
|
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE p.id=%s", (photo_id,)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# Gmail 연결(사람별, 갱신 토큰 암호문만) · 발주 메일 기록 — 003
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def gmail_token(self, email: str) -> dict[str, Any] | None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)).fetchone()
|
||||||
|
except UndefinedTable:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def save_gmail_token(self, email: str, *, refresh_token_enc: str, scopes: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_gmail_tokens (email, refresh_token_enc, scopes, connected_at, last_error) "
|
||||||
|
"VALUES (%s,%s,%s,now(),'') ON CONFLICT (email) DO UPDATE SET refresh_token_enc=EXCLUDED.refresh_token_enc, "
|
||||||
|
"scopes=EXCLUDED.scopes, connected_at=now(), last_error=''",
|
||||||
|
(_norm_email(email), refresh_token_enc, scopes[:500]))
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 003(발주 메일)이 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def delete_gmail_token(self, email: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("DELETE FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),))
|
||||||
|
except UndefinedTable:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def mark_gmail(self, email: str, *, error: str = "") -> None:
|
||||||
|
"""보낸 뒤 — 성공이면 마지막 사용 시각, 실패면 오류 문구(비밀값 없음)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("UPDATE inout_gmail_tokens SET last_used_at = CASE WHEN %s = '' THEN now() ELSE last_used_at END, "
|
||||||
|
"last_error=%s WHERE email=%s", (error[:300], error[:300], _norm_email(email)))
|
||||||
|
|
||||||
|
def add_order_mail(self, order_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_order_mails (order_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 — 005
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def settings_ready(self) -> bool:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return bool(conn.execute("SELECT to_regclass('public.inout_settings') IS NOT NULL AND "
|
||||||
|
"to_regclass('public.inout_receipt_mails') IS NOT NULL AS ok").fetchone()["ok"])
|
||||||
|
|
||||||
|
def get_settings(self) -> dict[str, str]:
|
||||||
|
"""설정 값 — 없는 키는 store.SETTING_DEFAULTS. 005 미적용이어도 기본값으로."""
|
||||||
|
out = dict(store.SETTING_DEFAULTS)
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
for r in conn.execute("SELECT key, value FROM inout_settings").fetchall():
|
||||||
|
if r["key"] in out:
|
||||||
|
out[r["key"]] = r["value"]
|
||||||
|
except UndefinedTable:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
|
||||||
|
def save_settings(self, values: dict[str, str], *, by: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
for k, v in values.items():
|
||||||
|
conn.execute("INSERT INTO inout_settings (key, value, updated_by, updated_at) VALUES (%s,%s,%s,now()) "
|
||||||
|
"ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_by=EXCLUDED.updated_by, updated_at=now()",
|
||||||
|
(k, v, _norm_email(by)))
|
||||||
|
except UndefinedTable:
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
|
||||||
|
|
||||||
|
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
|
||||||
|
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT id, filename, content_type, data FROM inout_receipt_photos WHERE receipt_id=%s ORDER BY id",
|
||||||
|
(receipt_id,)).fetchall()
|
||||||
|
except UndefinedTable:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def add_receipt_mail(self, receipt_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("INSERT INTO inout_receipt_mails (receipt_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s)",
|
||||||
|
(receipt_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
|
||||||
|
except UndefinedTable:
|
||||||
|
pass # 메일은 이미 나갔다 — 기록만 못 남김(005 미적용)
|
||||||
|
|
||||||
|
def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None:
|
||||||
|
"""잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고)."""
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
head = self._lock_order(conn, order_id)
|
||||||
|
if head["cancelled_at"]:
|
||||||
|
raise ValueError("취소된 발주서입니다.")
|
||||||
|
row = conn.execute("DELETE FROM inout_receipts WHERE id=%s AND order_id=%s RETURNING id",
|
||||||
|
(receipt_id, order_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("입고 기록을 찾을 수 없습니다.")
|
||||||
|
conn.execute("UPDATE inout_orders SET updated_by=%s WHERE id=%s", (_norm_email(by), order_id))
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 정보(004) — 코드표 단품 + 단가·무게(개당 g)·은 함유량(%) 수기 입력, 지운 단품은 제외 목록
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def products_ready(self) -> bool:
|
||||||
|
"""004 가 적용됐나(상품 표·발주 품목 값 칸). 한 번 확인되면 기억."""
|
||||||
|
if getattr(self, "_products_ok", False):
|
||||||
|
return True
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
ok = bool(conn.execute(
|
||||||
|
"SELECT to_regclass('public.inout_products') IS NOT NULL AND EXISTS (SELECT 1 FROM information_schema.columns "
|
||||||
|
"WHERE table_name = 'inout_order_lines' AND column_name = 'unit_price') AS ok").fetchone()["ok"])
|
||||||
|
self._products_ok = ok
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def _need_products(self) -> None:
|
||||||
|
if not self.products_ready():
|
||||||
|
raise ValueError("DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다.")
|
||||||
|
|
||||||
|
def list_products(self) -> list[dict[str, Any]]:
|
||||||
|
if not self.products_ready():
|
||||||
|
return []
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM inout_products ORDER BY item_code").fetchall()
|
||||||
|
|
||||||
|
def list_excluded(self) -> list[dict[str, Any]]:
|
||||||
|
if not self.products_ready():
|
||||||
|
return []
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute("SELECT * FROM inout_products_excluded ORDER BY item_code").fetchall()
|
||||||
|
|
||||||
|
def import_products(self, items: list[dict[str, str]], *, by: str) -> dict[str, int]:
|
||||||
|
"""코드표 단품 → 상품 정보. 새 단품은 추가, 값(단가·무게·은 함유량)을 넣은 상품은 그대로(이름도),
|
||||||
|
값이 없는 상품은 이름만 최신으로, 제외 목록의 단품은 건너뛴다."""
|
||||||
|
self._need_products()
|
||||||
|
out = {"added": 0, "renamed": 0, "kept": 0, "excluded": 0, "same": 0}
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
have = {r["item_code"]: r for r in conn.execute("SELECT * FROM inout_products FOR UPDATE").fetchall()}
|
||||||
|
skip = {r["item_code"] for r in conn.execute("SELECT item_code FROM inout_products_excluded").fetchall()}
|
||||||
|
for it in items:
|
||||||
|
code, name = it["code"].strip().upper(), (it.get("name") or "").strip()[:300]
|
||||||
|
if not code:
|
||||||
|
continue
|
||||||
|
if code in skip:
|
||||||
|
out["excluded"] += 1
|
||||||
|
elif code not in have:
|
||||||
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) "
|
||||||
|
"ON CONFLICT (item_code) DO NOTHING", (code, name, _norm_email(by)))
|
||||||
|
have[code] = {"item_code": code}
|
||||||
|
out["added"] += 1
|
||||||
|
elif store.has_values(have[code]):
|
||||||
|
out["kept"] += 1
|
||||||
|
elif have[code].get("item_name") != name:
|
||||||
|
conn.execute("UPDATE inout_products SET item_name=%s, updated_at=now() WHERE item_code=%s", (name, code))
|
||||||
|
out["renamed"] += 1
|
||||||
|
else:
|
||||||
|
out["same"] += 1
|
||||||
|
return out
|
||||||
|
|
||||||
|
def save_products(self, rows: list[dict[str, Any]], *, by: str) -> int:
|
||||||
|
"""값 저장 — rows = [{code, unit_price, weight_g, silver_pct}](store.validate_product_values 를 거친 값). 한 트랜잭션."""
|
||||||
|
self._need_products()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
for r in rows:
|
||||||
|
hit = conn.execute("UPDATE inout_products SET unit_price=%s, weight_g=%s, silver_pct=%s, updated_by=%s, updated_at=now() "
|
||||||
|
"WHERE item_code=%s RETURNING item_code",
|
||||||
|
(r["unit_price"], r["weight_g"], r["silver_pct"], _norm_email(by), r["code"])).fetchone()
|
||||||
|
if not hit:
|
||||||
|
raise ValueError(f"상품 정보에 없는 단품입니다: {r['code']}")
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
def exclude_product(self, code: str, *, by: str) -> None:
|
||||||
|
"""상품 정보에서 지우고 제외 목록에 — 다음 불러오기에서 빠진다(지난 발주서는 그대로)."""
|
||||||
|
self._need_products()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("DELETE FROM inout_products WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("상품을 찾을 수 없습니다.")
|
||||||
|
conn.execute("INSERT INTO inout_products_excluded (item_code, item_name, excluded_by) VALUES (%s,%s,%s) "
|
||||||
|
"ON CONFLICT (item_code) DO UPDATE SET excluded_at=now(), excluded_by=EXCLUDED.excluded_by",
|
||||||
|
(code, row["item_name"], _norm_email(by)))
|
||||||
|
|
||||||
|
def restore_product(self, code: str, *, by: str) -> None:
|
||||||
|
"""제외 목록에서 되살리기 — 바로 상품 정보로(값은 빈칸)."""
|
||||||
|
self._need_products()
|
||||||
|
with self._pool.connection() as conn, conn.transaction():
|
||||||
|
row = conn.execute("DELETE FROM inout_products_excluded WHERE item_code=%s RETURNING item_name", (code,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("제외 목록에 없는 단품입니다.")
|
||||||
|
conn.execute("INSERT INTO inout_products (item_code, item_name, updated_by) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING",
|
||||||
|
(code, row["item_name"], _norm_email(by)))
|
||||||
|
|
||||||
|
def catalog_count(self) -> int:
|
||||||
|
if not self.products_ready():
|
||||||
|
return 0
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return int(conn.execute("SELECT count(*) AS n FROM inout_products").fetchone()["n"])
|
||||||
|
|
||||||
|
def catalog_search(self, q: str, *, limit: int = 30) -> list[dict[str, Any]]:
|
||||||
|
"""발주서 제품 고르기 — 상품 정보에서(지운 단품 제외). 코드 앞부분 일치 먼저."""
|
||||||
|
esc = (q or "").strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
if not esc:
|
||||||
|
return []
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
|
||||||
|
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
|
||||||
|
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s",
|
||||||
|
{"q": f"%{esc}%", "p": f"{esc}%", "n": int(limit)}).fetchall()
|
||||||
|
|
||||||
|
def catalog_lookup(self, codes: list[str]) -> dict[str, dict[str, Any]]:
|
||||||
|
if not codes or not self.products_ready():
|
||||||
|
return {}
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM inout_products WHERE item_code = ANY(%s)", ([c.upper() for c in codes],)).fetchall()
|
||||||
|
return {r["item_code"]: r for r in rows}
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 미입고 현황 — 진행 중(종결·취소 아님) 발주의 남은 수량, 그리고 초과 입고
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def outstanding(self, *, factory_id: int | None = None, q: str = "") -> dict[str, list[dict[str, Any]]]:
|
||||||
|
where, params = ["o.closed_at IS NULL", "o.cancelled_at IS NULL"], []
|
||||||
|
if factory_id:
|
||||||
|
where.append("o.factory_id = %s")
|
||||||
|
params.append(factory_id)
|
||||||
|
if q.strip():
|
||||||
|
like = "%" + q.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||||
|
where.append("(l.item_code ILIKE %s OR l.item_name ILIKE %s OR o.order_no ILIKE %s)")
|
||||||
|
params += [like, like, like]
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT o.id AS order_id, o.order_no, o.order_date, o.due_date, f.name AS factory_name, "
|
||||||
|
"l.item_code, l.item_name, l.qty, COALESCE(sum(rl.qty), 0)::int AS received "
|
||||||
|
"FROM inout_order_lines l JOIN inout_orders o ON o.id = l.order_id "
|
||||||
|
"JOIN inout_factories f ON f.id = o.factory_id "
|
||||||
|
"LEFT JOIN inout_receipt_lines rl ON rl.order_line_id = l.id "
|
||||||
|
f"WHERE {' AND '.join(where)} GROUP BY l.id, o.id, f.name "
|
||||||
|
"ORDER BY o.due_date NULLS LAST, o.order_date, o.id, l.line_no", params).fetchall()
|
||||||
|
rows = store.decorate_lines(rows)
|
||||||
|
return {"pending": [r for r in rows if r["remaining"] > 0], "over": [r for r in rows if r["over"] > 0]}
|
||||||
|
|
||||||
|
# ── 내부 ──
|
||||||
|
@staticmethod
|
||||||
|
def _lock_order(conn: Any, order_id: int) -> dict[str, Any]:
|
||||||
|
head = conn.execute("SELECT * FROM inout_orders WHERE id=%s FOR UPDATE", (order_id,)).fetchone()
|
||||||
|
if not head:
|
||||||
|
raise LookupError("발주서를 찾을 수 없습니다.")
|
||||||
|
return head
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _require_factory(conn: Any, factory_id: int, *, allow_inactive_id: int | None = None) -> None:
|
||||||
|
row = conn.execute("SELECT is_active FROM inout_factories WHERE id=%s", (factory_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("공장을 찾을 수 없습니다.")
|
||||||
|
if not row["is_active"] and factory_id != allow_inactive_id:
|
||||||
|
raise ValueError("사용하지 않는 공장입니다(옵션에서 '사용'으로 바꾸세요).")
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
"""발주 메일 — 발주 담당자 본인 Gmail 로 보내기(2026-10-16 사용자 요청, Gmail API).
|
||||||
|
|
||||||
|
연결(사람마다 한 번): [Gmail 연결] → 구글 동의 화면(로그인과 같은 OAuth 클라이언트 GOOGLE_CLIENT_ID, 범위 = gmail.send 만)
|
||||||
|
→ /inout/gmail/callback 에서 ① 고른 구글 계정이 ERP 로그인 계정과 같은지(다르면 거절 — 남의 메일함으로 보내지 않게)
|
||||||
|
② gmail.send 를 허락했는지 ③ 갱신 토큰이 왔는지 확인 → 갱신 토큰을 APP_ENCRYPTION_KEY(실적 모듈과 같은 마스터 키,
|
||||||
|
AES-256-GCM, AAD = inout:gmail:{email})로 암호화해 inout_gmail_tokens 에. 원문·접근 토큰은 저장·출력하지 않는다.
|
||||||
|
보내기: 갱신 토큰 → 접근 토큰(oauth2.googleapis.com/token) → gmail.users.messages.send(raw = RFC 822, 글 + HTML).
|
||||||
|
사람이 [메일 발송]을 눌렀을 때만 보낸다(자동 발송 없음). 연결이 끊겼으면(invalid_grant·권한 없음) 다시 연결 안내.
|
||||||
|
구글 클라우드 준비(관리자 1회): Gmail API 사용 설정 · OAuth 동의 화면에 …/auth/gmail.send 범위 추가 ·
|
||||||
|
OAuth 클라이언트의 승인된 리디렉션 URI 에 {PUBLIC_BASE_URL}/inout/gmail/callback 추가. 상세 docs/INOUT_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.utils import formataddr
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
|
||||||
|
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||||
|
SEND_URI = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
|
||||||
|
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
|
||||||
|
CLIENT_NAME = "inout_gmail"
|
||||||
|
|
||||||
|
|
||||||
|
class GmailNotConnected(Exception):
|
||||||
|
"""Gmail 연결이 없거나 끊김 — 다시 [Gmail 연결]."""
|
||||||
|
|
||||||
|
|
||||||
|
class GmailError(Exception):
|
||||||
|
"""보내기 실패(구글 오류 등) — 문구는 화면에 그대로(비밀값 없음)."""
|
||||||
|
|
||||||
|
|
||||||
|
def _http() -> httpx.Client:
|
||||||
|
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||||
|
return httpx.Client(timeout=20.0)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 토큰 암호화(실적 모듈과 같은 마스터 키) ─────────────────
|
||||||
|
def _ring() -> Any:
|
||||||
|
from app.modules.performance.security.crypto import CryptoConfigError, KeyRing # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
return KeyRing.from_env()
|
||||||
|
except CryptoConfigError as exc:
|
||||||
|
raise GmailError(f"암호화 키가 없어 Gmail 연결을 저장할 수 없습니다 — {exc}") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _aad(email: str) -> str:
|
||||||
|
return f"inout:gmail:{(email or '').strip().lower()}"
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_token(email: str, refresh_token: str) -> str:
|
||||||
|
from app.modules.performance.security.crypto import encrypt # noqa: WPS433
|
||||||
|
|
||||||
|
return encrypt(refresh_token, aad=_aad(email), ring=_ring())
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_token(email: str, enc: str) -> str:
|
||||||
|
from app.modules.performance.security.crypto import DecryptError, decrypt # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
return decrypt(enc, aad=_aad(email), ring=_ring())
|
||||||
|
except DecryptError:
|
||||||
|
raise GmailNotConnected("저장된 Gmail 연결을 읽을 수 없습니다(암호화 키가 바뀌었을 수 있음) — 다시 연결하세요.") from None
|
||||||
|
|
||||||
|
|
||||||
|
# ── OAuth 클라이언트(로그인과 같은 GOOGLE_CLIENT_ID, 범위만 다름) ──
|
||||||
|
def oauth_client() -> Any:
|
||||||
|
from app.main import env, oauth # noqa: WPS433
|
||||||
|
|
||||||
|
if not env("GOOGLE_CLIENT_ID") or not env("GOOGLE_CLIENT_SECRET"):
|
||||||
|
raise GmailError("GOOGLE_CLIENT_ID/SECRET 이 없어 Gmail 을 연결할 수 없습니다.")
|
||||||
|
client = oauth.create_client(CLIENT_NAME)
|
||||||
|
if client is None:
|
||||||
|
oauth.register(
|
||||||
|
name=CLIENT_NAME,
|
||||||
|
client_id=env("GOOGLE_CLIENT_ID"),
|
||||||
|
client_secret=env("GOOGLE_CLIENT_SECRET"),
|
||||||
|
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
|
||||||
|
client_kwargs={"scope": f"openid email {GMAIL_SCOPE}"},
|
||||||
|
)
|
||||||
|
client = oauth.create_client(CLIENT_NAME)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def check_grant(token: dict[str, Any], *, expected_email: str) -> tuple[str, str]:
|
||||||
|
"""콜백 토큰 확인 → (갱신 토큰, 허락된 범위). 계정이 다르거나 발송 권한·갱신 토큰이 없으면 GmailError."""
|
||||||
|
info = token.get("userinfo") or {}
|
||||||
|
got = str(info.get("email") or "").strip().lower()
|
||||||
|
want = (expected_email or "").strip().lower()
|
||||||
|
if not got or got != want:
|
||||||
|
raise GmailError(f"ERP 로그인 계정({want})과 다른 구글 계정({got or '알 수 없음'})을 골랐습니다 — 같은 계정으로 다시 연결하세요.")
|
||||||
|
scopes = str(token.get("scope") or "")
|
||||||
|
if GMAIL_SCOPE not in scopes.split():
|
||||||
|
raise GmailError("메일 보내기 권한(gmail.send)을 허락하지 않았습니다 — 동의 화면에서 체크한 뒤 다시 연결하세요.")
|
||||||
|
refresh = str(token.get("refresh_token") or "")
|
||||||
|
if not refresh:
|
||||||
|
raise GmailError("구글이 갱신 토큰을 주지 않았습니다 — 구글 계정 → 보안 → 타사 앱 접근에서 이 앱을 지우고 다시 연결하세요.")
|
||||||
|
return refresh, scopes
|
||||||
|
|
||||||
|
|
||||||
|
# ── 보내기 ──────────────────────────────────────────────
|
||||||
|
def _google_message(resp: httpx.Response) -> str:
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
return f"HTTP {resp.status_code}"
|
||||||
|
err = body.get("error")
|
||||||
|
if isinstance(err, dict):
|
||||||
|
return str(err.get("message") or err.get("status") or resp.status_code)[:200]
|
||||||
|
return str(body.get("error_description") or err or resp.status_code)[:200]
|
||||||
|
|
||||||
|
|
||||||
|
def access_token(refresh_token: str) -> str:
|
||||||
|
from app.main import env # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
resp = client.post(TOKEN_URI, data={"client_id": env("GOOGLE_CLIENT_ID"), "client_secret": env("GOOGLE_CLIENT_SECRET"),
|
||||||
|
"refresh_token": refresh_token, "grant_type": "refresh_token"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise GmailError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code != 200:
|
||||||
|
try:
|
||||||
|
code = str(resp.json().get("error") or "")
|
||||||
|
except ValueError:
|
||||||
|
code = ""
|
||||||
|
if code in ("invalid_grant", "unauthorized_client", "invalid_client"):
|
||||||
|
raise GmailNotConnected("Gmail 연결이 끊겼습니다(권한 취소·비밀번호 변경 등) — 다시 연결하세요.")
|
||||||
|
raise GmailError(f"구글 인증 실패: {_google_message(resp)}")
|
||||||
|
token = str(resp.json().get("access_token") or "")
|
||||||
|
if not token:
|
||||||
|
raise GmailError("구글 인증 서버가 접근 토큰을 주지 않았습니다.")
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
|
||||||
|
text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes:
|
||||||
|
"""글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어
|
||||||
|
<img src="cid:…"> 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19)."""
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = formataddr((sender_name or sender_email, sender_email))
|
||||||
|
msg["To"] = ", ".join(to)
|
||||||
|
if cc:
|
||||||
|
msg["Cc"] = ", ".join(cc)
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg.set_content(text)
|
||||||
|
msg.add_alternative(html, subtype="html")
|
||||||
|
if inline_images:
|
||||||
|
html_part = msg.get_payload()[1]
|
||||||
|
for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게
|
||||||
|
html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline")
|
||||||
|
return msg.as_bytes()
|
||||||
|
|
||||||
|
|
||||||
|
def send(refresh_token: str, raw: bytes) -> str:
|
||||||
|
"""보내고 Gmail 메시지 id 를 돌려준다."""
|
||||||
|
token = access_token(refresh_token)
|
||||||
|
body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
resp = client.post(SEND_URI, json=body, headers={"Authorization": f"Bearer {token}"})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise GmailError(f"Gmail 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code in (401, 403):
|
||||||
|
msg = _google_message(resp)
|
||||||
|
if "has not been used" in msg or "disabled" in msg.lower():
|
||||||
|
raise GmailError(f"Gmail API 가 꺼져 있습니다 — 관리자가 구글 클라우드에서 Gmail API 를 사용 설정해야 합니다. ({msg})")
|
||||||
|
raise GmailNotConnected(f"Gmail 보내기 권한이 없습니다 — 다시 연결하세요. ({msg})")
|
||||||
|
if resp.status_code != 200:
|
||||||
|
raise GmailError(f"메일을 보내지 못했습니다: {_google_message(resp)}")
|
||||||
|
return str(resp.json().get("id") or "")
|
||||||
|
|
||||||
|
|
||||||
|
def revoke(refresh_token: str) -> None:
|
||||||
|
"""연결 끊기 — 구글 쪽 권한도 취소(실패해도 무시, 우리 쪽 토큰은 지운다)."""
|
||||||
|
try:
|
||||||
|
with _http() as client:
|
||||||
|
client.post(REVOKE_URI, data={"token": refresh_token})
|
||||||
|
except httpx.HTTPError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def configured() -> bool:
|
||||||
|
"""APP_ENCRYPTION_KEY·GOOGLE_CLIENT_ID/SECRET 이 있는지(화면 안내용)."""
|
||||||
|
return bool(os.getenv("APP_ENCRYPTION_KEY", "").strip() and os.getenv("GOOGLE_CLIENT_ID", "").strip()
|
||||||
|
and os.getenv("GOOGLE_CLIENT_SECRET", "").strip())
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""itemcode_db 읽기 전용 — 단품(single_items)만 검색·확인.
|
||||||
|
|
||||||
|
입출고 발주서의 제품은 코드표 DB 의 단품 아이템에서만 고른다(2026-10-16 사용자 요청 — 세트는 공장 발주 대상이 아님).
|
||||||
|
itemcode_db 실제 스키마(운영 확인됨, malaysia/itemcode.py 와 같음): single_items(item_code, sabangnet_code, name).
|
||||||
|
환경변수 `ITEMCODE_DB_URL`(읽기 전용 역할 itemcode_ro) — cupang·malaysia 모듈과 공유.
|
||||||
|
미설정/실패 시 enabled=False, 빈 결과(앱/모듈을 죽이지 않음) — 그때 발주서 저장은 "코드표 연결 필요"로 막는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger("inout.itemcode")
|
||||||
|
|
||||||
|
_SEARCH_SQL = (
|
||||||
|
"SELECT item_code, name FROM single_items "
|
||||||
|
"WHERE item_code ILIKE %(q)s OR name ILIKE %(q)s "
|
||||||
|
"ORDER BY (item_code ILIKE %(prefix)s) DESC, item_code ASC LIMIT %(limit)s"
|
||||||
|
)
|
||||||
|
_LOOKUP_SQL = "SELECT item_code, name FROM single_items WHERE upper(item_code) = ANY(%(codes)s)"
|
||||||
|
|
||||||
|
|
||||||
|
class SingleItemReader:
|
||||||
|
def __init__(self, dsn: str | None = None) -> None:
|
||||||
|
self._pool: Any = None
|
||||||
|
self.enabled = False
|
||||||
|
self.reason = ""
|
||||||
|
self.last_error = ""
|
||||||
|
self._configure(dsn if dsn is not None else os.getenv("ITEMCODE_DB_URL", "").strip())
|
||||||
|
|
||||||
|
def _configure(self, dsn: str) -> None:
|
||||||
|
if not dsn:
|
||||||
|
self.reason = "ITEMCODE_DB_URL 미설정 — 코드표(단품) 조회 비활성."
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
self._pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=3,
|
||||||
|
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||||
|
self._pool.open(wait=False)
|
||||||
|
self.enabled = True
|
||||||
|
except Exception as exc: # noqa: BLE001 — 설정/드라이버 문제로 모듈을 죽이지 않음
|
||||||
|
self.reason = f"itemcode_db 연결 풀 생성 실패: {type(exc).__name__}"
|
||||||
|
|
||||||
|
def search(self, query: str, *, limit: int = 30) -> list[dict[str, str]]:
|
||||||
|
"""코드·이름 부분 일치(코드 앞부분 일치 먼저). 반환 [{"code","name"}]. 실패는 빈 목록."""
|
||||||
|
q = (query or "").strip()
|
||||||
|
if not q or not self.enabled or not self._pool:
|
||||||
|
return []
|
||||||
|
esc = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
rows = self._run(_SEARCH_SQL, {"q": f"%{esc}%", "prefix": f"{esc}%", "limit": int(limit)})
|
||||||
|
return [{"code": str(r["item_code"]).strip(), "name": str(r.get("name") or "").strip()} for r in rows or []]
|
||||||
|
|
||||||
|
def list_all(self, *, limit: int = 20000) -> list[dict[str, str]] | None:
|
||||||
|
"""단품 전체(옵션 → 상품 정보 → 단품 불러오기). 조회 불가면 None(빈 목록과 구분)."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
rows = self._run("SELECT item_code, name FROM single_items ORDER BY item_code LIMIT %(limit)s", {"limit": int(limit)})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return [{"code": str(r["item_code"]).strip().upper(), "name": str(r.get("name") or "").strip()} for r in rows if r.get("item_code")]
|
||||||
|
|
||||||
|
def lookup(self, codes: list[str]) -> dict[str, str] | None:
|
||||||
|
"""코드들 → {코드(대문자): 이름}. 단품 표에 없는 코드는 빠진다. 조회 불가면 None."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
|
||||||
|
if not wanted:
|
||||||
|
return {}
|
||||||
|
rows = self._run(_LOOKUP_SQL, {"codes": wanted})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(r["item_code"]).strip().upper(): str(r.get("name") or "").strip() for r in rows}
|
||||||
|
|
||||||
|
def sabangnet_codes(self, codes: list[str]) -> dict[str, str] | None:
|
||||||
|
"""코드들 → {코드(대문자): 사방넷 코드}(사방넷 입고 파일, 2026-10-19). 사방넷 코드가 빈 단품은 ''. 조회 불가면 None."""
|
||||||
|
if not self.enabled or not self._pool:
|
||||||
|
return None
|
||||||
|
wanted = sorted({c.strip().upper() for c in codes if c and c.strip()})
|
||||||
|
if not wanted:
|
||||||
|
return {}
|
||||||
|
rows = self._run("SELECT item_code, sabangnet_code FROM single_items WHERE upper(item_code) = ANY(%(codes)s)", {"codes": wanted})
|
||||||
|
if rows is None:
|
||||||
|
return None
|
||||||
|
return {str(r["item_code"]).strip().upper(): str(r.get("sabangnet_code") or "").strip() for r in rows}
|
||||||
|
|
||||||
|
def _run(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]] | None:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(sql, params).fetchall()
|
||||||
|
self.last_error = ""
|
||||||
|
return rows
|
||||||
|
except Exception as exc: # noqa: BLE001 — 모듈을 죽이지 않음
|
||||||
|
self.last_error = f"{type(exc).__name__}"
|
||||||
|
logger.exception("itemcode(single_items) 조회 실패")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._pool is not None:
|
||||||
|
self._pool.close()
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,683 @@
|
|||||||
|
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, DB 없음).
|
||||||
|
|
||||||
|
흐름(2026-10-16 사용자 요청, 상용 ERP 참고 — 이카운트 "발주 대비 미입고 현황"·Odoo 분할 입고/잔량 종결):
|
||||||
|
발주 담당이 공장에 발주서(단품 코드·수량)를 넣고 → 물류에 들어올 때마다 입고 담당이 그날 들어온 수량을 입력(여러 번 나눠도 됨)
|
||||||
|
→ 품목마다 발주 − 누적 입고 = 미입고. 다 들어오면 입고완료, 더 들어오면 초과입고(확인 후 허용, 빨강 표시).
|
||||||
|
더 안 들어올 잔량은 발주 담당이 "종결"(이카운트 발주 종결 · Odoo No backorder) — 미입고 현황에서 빠지고 종결로 남는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html as _html
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
ROLE_ORDER = "order" # 발주 담당
|
||||||
|
ROLE_RECEIVE = "receive" # 입고 담당
|
||||||
|
ROLES = (ROLE_ORDER, ROLE_RECEIVE)
|
||||||
|
ROLE_LABELS = {ROLE_ORDER: "발주 담당", ROLE_RECEIVE: "입고 담당"}
|
||||||
|
|
||||||
|
MAX_QTY = 10_000_000
|
||||||
|
MAX_LINES = 200
|
||||||
|
MEMO_MAX = 500
|
||||||
|
|
||||||
|
# 품목 상태
|
||||||
|
LINE_NONE, LINE_PARTIAL, LINE_DONE, LINE_OVER = "none", "partial", "done", "over"
|
||||||
|
LINE_LABELS = {LINE_NONE: "미입고", LINE_PARTIAL: "부분입고", LINE_DONE: "입고완료", LINE_OVER: "초과입고"}
|
||||||
|
|
||||||
|
# 발주서 상태 — 진행(open·partial)은 미입고 현황에 나온다
|
||||||
|
ST_OPEN, ST_PARTIAL, ST_DONE, ST_OVER, ST_CLOSED, ST_CANCELLED = "open", "partial", "done", "over", "closed", "cancelled"
|
||||||
|
# 모든 품목이 입고완료·초과입고 = "전체 입고 완료"(2026-10-17 요청 — 초과가 있으면 화면에 "초과 포함"만 덧붙인다)
|
||||||
|
ORDER_LABELS = {ST_OPEN: "발주", ST_PARTIAL: "부분입고", ST_DONE: "전체 입고 완료", ST_OVER: "전체 입고 완료",
|
||||||
|
ST_CLOSED: "종결", ST_CANCELLED: "취소"}
|
||||||
|
ACTIVE_STATUSES = (ST_OPEN, ST_PARTIAL) # 아직 더 들어올 것이 있는 발주
|
||||||
|
STATUS_FILTERS = { # 목록 거르기
|
||||||
|
"active": ("진행 중", ACTIVE_STATUSES),
|
||||||
|
"done": ("완료", (ST_DONE, ST_OVER)),
|
||||||
|
"closed": ("종결·취소", (ST_CLOSED, ST_CANCELLED)),
|
||||||
|
"all": ("전체", tuple(ORDER_LABELS)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
WEEKDAYS_KO = "월화수목금토일"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_date(d: date | None) -> str:
|
||||||
|
"""날짜 서식 — 2026.10.17(토). 입출고 화면·메일 모두 이 모양(2026-10-17 요청). 화면 쪽은 _macros.html ymd 와 같다."""
|
||||||
|
if not d:
|
||||||
|
return ""
|
||||||
|
return f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_datetime(dt: datetime | None) -> str:
|
||||||
|
"""2026.10.17(토) 15:14 — 시각은 DB 에서 KST 로 읽는다(db._KstTimestamptzLoader)."""
|
||||||
|
return f"{fmt_date(dt)} {dt:%H:%M}" if dt else ""
|
||||||
|
|
||||||
|
|
||||||
|
def line_status(qty: int, received: int) -> str:
|
||||||
|
if received <= 0:
|
||||||
|
return LINE_NONE
|
||||||
|
if received < qty:
|
||||||
|
return LINE_PARTIAL
|
||||||
|
return LINE_DONE if received == qty else LINE_OVER
|
||||||
|
|
||||||
|
|
||||||
|
def order_status(lines: Iterable[dict[str, Any]], *, closed: bool = False, cancelled: bool = False) -> str:
|
||||||
|
"""lines: [{qty, received}]. 취소·종결이 먼저, 그다음 입고 합계로."""
|
||||||
|
if cancelled:
|
||||||
|
return ST_CANCELLED
|
||||||
|
if closed:
|
||||||
|
return ST_CLOSED
|
||||||
|
sts = [line_status(int(x["qty"]), int(x.get("received") or 0)) for x in lines]
|
||||||
|
if not sts or all(s == LINE_NONE for s in sts):
|
||||||
|
return ST_OPEN
|
||||||
|
if any(s in (LINE_NONE, LINE_PARTIAL) for s in sts):
|
||||||
|
return ST_PARTIAL
|
||||||
|
return ST_OVER if any(s == LINE_OVER for s in sts) else ST_DONE
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(lines: list[dict[str, Any]]) -> dict[str, int]:
|
||||||
|
"""발주·입고·미입고(0 아래로 안 내려감)·초과 합계."""
|
||||||
|
ordered = sum(int(x["qty"]) for x in lines)
|
||||||
|
received = sum(int(x.get("received") or 0) for x in lines)
|
||||||
|
remaining = sum(max(int(x["qty"]) - int(x.get("received") or 0), 0) for x in lines)
|
||||||
|
over = sum(max(int(x.get("received") or 0) - int(x["qty"]), 0) for x in lines)
|
||||||
|
pct = min(100, round(received * 100 / ordered)) if ordered else 0
|
||||||
|
return {"ordered": ordered, "received": received, "remaining": remaining, "over": over, "pct": pct}
|
||||||
|
|
||||||
|
|
||||||
|
def decorate_lines(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""화면용 — 품목마다 미입고·초과·상태 이름."""
|
||||||
|
out = []
|
||||||
|
for x in lines:
|
||||||
|
qty, rec = int(x["qty"]), int(x.get("received") or 0)
|
||||||
|
st = line_status(qty, rec)
|
||||||
|
out.append({**x, "received": rec, "remaining": max(qty - rec, 0), "over": max(rec - qty, 0),
|
||||||
|
"status": st, "status_label": LINE_LABELS[st]})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ── 입력 검사 ────────────────────────────────────────────────
|
||||||
|
def parse_qty(raw: Any, *, label: str = "수량", allow_zero: bool = False) -> int:
|
||||||
|
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||||
|
if not s:
|
||||||
|
if allow_zero:
|
||||||
|
return 0
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
try:
|
||||||
|
n = int(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"{label}은(는) 정수로 입력하세요.") from None
|
||||||
|
if n < 0 or (n == 0 and not allow_zero):
|
||||||
|
raise ValueError(f"{label}은(는) {0 if allow_zero else 1} 이상이어야 합니다.")
|
||||||
|
if n > MAX_QTY:
|
||||||
|
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(raw: Any, *, label: str, required: bool = True) -> date | None:
|
||||||
|
s = str(raw or "").strip()
|
||||||
|
if not s:
|
||||||
|
if required:
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(s)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"{label} 형식이 올바르지 않습니다(YYYY-MM-DD).") from None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_order(*, factory_id: Any, order_date: Any, due_date: Any, memo: Any,
|
||||||
|
codes: list[str], quantities: list[str], line_memos: list[str] | None = None) -> dict[str, Any]:
|
||||||
|
"""발주서 폼 → 정리된 값. 빈 줄(코드·수량 둘 다 없음)은 건너뛴다. 같은 제품 두 줄은 오류."""
|
||||||
|
errors: list[str] = []
|
||||||
|
try:
|
||||||
|
fid = int(str(factory_id or "").strip())
|
||||||
|
except ValueError:
|
||||||
|
fid = 0
|
||||||
|
if fid <= 0:
|
||||||
|
errors.append("공장을 고르세요.")
|
||||||
|
od = dd = None
|
||||||
|
try:
|
||||||
|
od = parse_date(order_date, label="발주일")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
try:
|
||||||
|
dd = parse_date(due_date, label="입고 예정일", required=False)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
if od and dd and dd < od:
|
||||||
|
errors.append("입고 예정일이 발주일보다 빠릅니다.")
|
||||||
|
line_memos = line_memos or []
|
||||||
|
lines: list[dict[str, Any]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
for i, code in enumerate(codes):
|
||||||
|
code = (code or "").strip().upper()
|
||||||
|
raw_qty = quantities[i] if i < len(quantities) else ""
|
||||||
|
if not code and not str(raw_qty or "").strip():
|
||||||
|
continue
|
||||||
|
if not code:
|
||||||
|
errors.append(f"{i + 1}번째 줄: 제품을 고르세요.")
|
||||||
|
continue
|
||||||
|
if code in seen:
|
||||||
|
errors.append(f"{code}: 같은 제품이 두 줄에 있습니다 — 한 줄로 합쳐 주세요.")
|
||||||
|
continue
|
||||||
|
seen.add(code)
|
||||||
|
try:
|
||||||
|
qty = parse_qty(raw_qty, label=f"{code} 발주 수량")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
continue
|
||||||
|
lines.append({"item_code": code, "qty": qty,
|
||||||
|
"memo": str(line_memos[i] if i < len(line_memos) else "").strip()[:MEMO_MAX]})
|
||||||
|
if not lines and not any("줄" in e or "수량" in e for e in errors):
|
||||||
|
errors.append("발주할 제품을 한 줄 이상 넣으세요.")
|
||||||
|
if len(lines) > MAX_LINES:
|
||||||
|
errors.append(f"한 발주서에 {MAX_LINES}개 제품까지 넣을 수 있습니다.")
|
||||||
|
if errors:
|
||||||
|
raise ValueError("\n".join(errors))
|
||||||
|
return {"factory_id": fid, "order_date": od, "due_date": dd, "memo": str(memo or "").strip()[:MEMO_MAX], "lines": lines}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_receipt(order_lines: list[dict[str, Any]], quantities: dict[int, Any], *,
|
||||||
|
receipt_date: Any, memo: Any) -> dict[str, Any]:
|
||||||
|
"""입고 입력 — quantities: {발주 줄 id: 입력값}. 빈칸·0 은 이번에 안 들어온 것.
|
||||||
|
over = 이번 입고로 발주를 넘는 품목(확인 받은 뒤 저장). order_lines 는 지금까지 누적 입고(received)를 포함."""
|
||||||
|
errors: list[str] = []
|
||||||
|
try:
|
||||||
|
rd = parse_date(receipt_date, label="입고일")
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
rd = None
|
||||||
|
by_id = {int(x["id"]): x for x in order_lines}
|
||||||
|
items: list[dict[str, Any]] = []
|
||||||
|
over: list[dict[str, Any]] = []
|
||||||
|
for lid, raw in quantities.items():
|
||||||
|
line = by_id.get(int(lid))
|
||||||
|
if line is None:
|
||||||
|
errors.append("이 발주서에 없는 품목이 들어 있습니다.")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
qty = parse_qty(raw, label=f"{line['item_code']} 입고 수량", allow_zero=True)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
continue
|
||||||
|
if qty == 0:
|
||||||
|
continue
|
||||||
|
items.append({"order_line_id": int(lid), "qty": qty})
|
||||||
|
after = int(line.get("received") or 0) + qty
|
||||||
|
if after > int(line["qty"]):
|
||||||
|
over.append({"item_code": line["item_code"], "item_name": line.get("item_name", ""),
|
||||||
|
"ordered": int(line["qty"]), "after": after, "over": after - int(line["qty"])})
|
||||||
|
if not items and not errors:
|
||||||
|
errors.append("입고 수량을 한 품목 이상 넣으세요.")
|
||||||
|
if errors:
|
||||||
|
raise ValueError("\n".join(errors))
|
||||||
|
return {"receipt_date": rd, "memo": str(memo or "").strip()[:MEMO_MAX], "items": items, "over": over}
|
||||||
|
|
||||||
|
|
||||||
|
def order_no(order_date: date, seq: int) -> str:
|
||||||
|
"""PO-YYMMDD-NN — 발주일 기준 그날 순번(01부터)."""
|
||||||
|
return f"PO-{order_date:%y%m%d}-{seq:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주 메일(2026-10-16, 마이그레이션 003) — 받는 주소 검사, 본문(요약) 만들기. 보내기는 gmail.py
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
MAX_RECIPIENTS = 10
|
||||||
|
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) -> list[str]:
|
||||||
|
"""'a@x.com, b@y.co.kr; c@z.com' → 주소 목록(순서 유지·중복 제거). 형식이 틀리면 ValueError."""
|
||||||
|
out: list[str] = []
|
||||||
|
for part in re.split(r"[\s,;]+", str(raw or "")):
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
if not _EMAIL_RE.match(part) or len(part) > 254:
|
||||||
|
raise ValueError(f"{label} 형식이 올바르지 않습니다: {part[:60]}")
|
||||||
|
if part.lower() not in [x.lower() for x in out]:
|
||||||
|
out.append(part)
|
||||||
|
if required and not out:
|
||||||
|
raise ValueError(f"{label}을(를) 입력하세요.")
|
||||||
|
if len(out) > MAX_RECIPIENTS:
|
||||||
|
raise ValueError(f"{label}은(는) {MAX_RECIPIENTS}개까지 넣을 수 있습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||||
|
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||||||
|
— 발주 품목에 남긴 그때 값(004). 없으면 '-'. (2026-10-19 — 예전엔 PP(g/개)·개당 은 g)"""
|
||||||
|
lines = order["lines"]
|
||||||
|
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
|
||||||
|
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
|
||||||
|
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
|
||||||
|
total = sum(int(x["qty"]) for x in lines)
|
||||||
|
money = order_totals(lines)
|
||||||
|
due = fmt_date(order["due_date"]) if order.get("due_date") else "협의"
|
||||||
|
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
|
||||||
|
who = sender_name or sender_email
|
||||||
|
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||||||
|
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||||
|
if money["amount"] is not None:
|
||||||
|
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||||
|
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||||
|
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||||||
|
if money["pp_kg"] is not None:
|
||||||
|
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||||||
|
if money["pp_use_kg"] is not None:
|
||||||
|
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||||||
|
if ag_kg is not None:
|
||||||
|
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||||||
|
if order.get("memo"):
|
||||||
|
facts.append(("요청 사항", order["memo"]))
|
||||||
|
|
||||||
|
def cells(x: dict[str, Any]) -> dict[str, str]:
|
||||||
|
price, w, pct = to_dec(x.get("unit_price")), to_dec(x.get("weight_g")), to_dec(x.get("silver_pct"))
|
||||||
|
q = int(x["qty"])
|
||||||
|
amt = line_amount(q, price)
|
||||||
|
total_kg = w * q / Decimal(1000) if w is not None else None # 전체 무게 = 개당 g × 수량
|
||||||
|
ag_kg = total_kg * pct / Decimal(100) if total_kg is not None and pct is not None else None
|
||||||
|
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
|
||||||
|
"weight": fmt_num(total_kg, 3) if total_kg is not None else "-",
|
||||||
|
"pp_use": fmt_num(total_kg - ag_kg, 3) if ag_kg is not None else "-",
|
||||||
|
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag_kg, 4)}kg)" if ag_kg is not None else "")) if pct is not None else "-"}
|
||||||
|
|
||||||
|
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||||
|
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||||
|
text += [f"- {k}: {v}" for k, v in facts]
|
||||||
|
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||||
|
for i, x in enumerate(lines, start=1):
|
||||||
|
c = cells(x)
|
||||||
|
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
|
||||||
|
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||||||
|
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}"
|
||||||
|
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
||||||
|
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||||
|
# HTML 본문 — 값은 모두 escape
|
||||||
|
e = _html.escape
|
||||||
|
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||||||
|
r = "text-align:right;white-space:nowrap;"
|
||||||
|
# 요약 표 = 항목·값 두 쌍씩 한 줄(4열, 2026-10-19 — 예전 2열 × 8행). 요청 사항(길 수 있음)은 맨 아래 한 줄 전체.
|
||||||
|
# 칸 높이는 글자 한 줄에 맞게 — 받은 메일(메일 프로그램)에서 칸이 크게 늘어나 보여 줄 높이·글자 크기·위아래 여백을 칸마다 못 박는다.
|
||||||
|
ftd = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;height:20px;vertical-align:middle;white-space:nowrap;"
|
||||||
|
fth = f"{ftd}background:#f6f7f9;text-align:left;font-weight:700;"
|
||||||
|
pairs = [(k, v) for k, v in facts if k != "요청 사항"]
|
||||||
|
fact_rows = ""
|
||||||
|
for i in range(0, len(pairs), 2):
|
||||||
|
cols = "".join(f'<th style="{fth}">{e(k)}</th><td style="{ftd}">{e(str(v))}</td>' for k, v in pairs[i:i + 2])
|
||||||
|
if len(pairs[i:i + 2]) == 1:
|
||||||
|
cols += f'<th style="{fth}"></th><td style="{ftd}"></td>'
|
||||||
|
fact_rows += f"<tr>{cols}</tr>"
|
||||||
|
if order.get("memo"): # 요청 사항은 길면 줄을 바꿔야 하므로 높이를 고정하지 않는다
|
||||||
|
memo_td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;vertical-align:middle;"
|
||||||
|
fact_rows += (f'<tr><th style="{fth}">요청 사항</th>'
|
||||||
|
f'<td colspan="3" style="{memo_td}">{e(str(order["memo"]))}</td></tr>')
|
||||||
|
rows = []
|
||||||
|
for i, x in enumerate(lines, start=1):
|
||||||
|
c = cells(x)
|
||||||
|
rows.append(
|
||||||
|
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||||
|
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}{r}">{int(x["qty"]):,}</td>'
|
||||||
|
f'<td style="{td}{r}">{e(c["price"])}</td><td style="{td}{r}">{e(c["amount"])}</td>'
|
||||||
|
f'<td style="{td}{r}">{e(c["weight"])}</td><td style="{td}{r}">{e(c["pp_use"])}</td><td style="{td}{r}">{e(c["ag"])}</td>'
|
||||||
|
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>')
|
||||||
|
foot_amount = fmt_num(money["amount"]) if money["amount"] is not None else ""
|
||||||
|
foot_pp = fmt_num(money["pp_kg"], 3) if money["pp_kg"] is not None else ""
|
||||||
|
foot_use = fmt_num(money["pp_use_kg"], 3) if money["pp_use_kg"] is not None else ""
|
||||||
|
foot_ag = f'{fmt_num(ag_kg, 4)} kg' if ag_kg is not None else ""
|
||||||
|
bg = "background:#f6f7f9;"
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||||||
|
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{fact_rows}</table>'
|
||||||
|
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||||||
|
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||||
|
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
||||||
|
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||||
|
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||||
|
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>'
|
||||||
|
f'<th style="{td}">비고</th></tr></thead>'
|
||||||
|
f'<tbody>{"".join(rows)}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||||||
|
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||||
|
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>'
|
||||||
|
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||||
|
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||||
|
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
||||||
|
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
PRODUCT_LIMITS = {"unit_price": ("단가", Decimal("1000000000"), 2), "weight_g": ("무게", Decimal("1000000"), 2),
|
||||||
|
"silver_pct": ("은 함유량", Decimal("100"), 4)}
|
||||||
|
|
||||||
|
|
||||||
|
def to_dec(v: Any) -> Decimal | None:
|
||||||
|
if v is None or v == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return Decimal(str(v))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_num(v: Any, places: int = 2) -> str:
|
||||||
|
"""1234.50 → '1,234.5', 1234 → '1,234' (소수 끝 0 은 뺀다)."""
|
||||||
|
d = to_dec(v)
|
||||||
|
if d is None:
|
||||||
|
return ""
|
||||||
|
q = d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||||
|
s = f"{q:,.{places}f}"
|
||||||
|
return s.rstrip("0").rstrip(".") if "." in s else s
|
||||||
|
|
||||||
|
|
||||||
|
def silver_g(weight_g: Any, silver_pct: Any) -> Decimal | None:
|
||||||
|
w, p = to_dec(weight_g), to_dec(silver_pct)
|
||||||
|
if w is None or p is None:
|
||||||
|
return None
|
||||||
|
return (w * p / Decimal(100)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def line_amount(qty: int, unit_price: Any) -> Decimal | None:
|
||||||
|
p = to_dec(unit_price)
|
||||||
|
return None if p is None else (p * int(qty)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
"""발주 금액 합(단가 있는 줄만, 없으면 None)·단가 없는 줄 수·PP 총량(= 전체 무게, kg)·은 총량(g)·
|
||||||
|
PP 사용량(kg, 무게·은 함유량이 다 있는 줄의 전체 무게 − 은 무게 — 메일 표, 2026-10-19)."""
|
||||||
|
amount = pp = ag = use = None
|
||||||
|
missing = 0
|
||||||
|
for x in lines:
|
||||||
|
q = int(x["qty"])
|
||||||
|
a = line_amount(q, x.get("unit_price"))
|
||||||
|
if a is None:
|
||||||
|
missing += 1
|
||||||
|
else:
|
||||||
|
amount = (amount or Decimal(0)) + a
|
||||||
|
w = to_dec(x.get("weight_g"))
|
||||||
|
if w is not None:
|
||||||
|
pp = (pp or Decimal(0)) + w * q / Decimal(1000)
|
||||||
|
p = to_dec(x.get("silver_pct"))
|
||||||
|
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||||
|
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||||
|
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
||||||
|
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag,
|
||||||
|
"pp_use_kg": use}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_decimal(raw: Any, *, key: str) -> Decimal | None:
|
||||||
|
"""상품 정보 칸 하나 — 빈칸은 None(미입력), 숫자·쉼표·0 이상·한도 안·소수 자리."""
|
||||||
|
label, limit, places = PRODUCT_LIMITS[key]
|
||||||
|
s = str(raw if raw is not None else "").replace(",", "").replace("%", "").strip()
|
||||||
|
if not s:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
d = Decimal(s)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise ValueError(f"{label}은(는) 숫자로 입력하세요.") from None
|
||||||
|
if not d.is_finite() or d < 0:
|
||||||
|
raise ValueError(f"{label}은(는) 0 이상이어야 합니다.")
|
||||||
|
if d > limit:
|
||||||
|
raise ValueError(f"{label}이(가) 너무 큽니다(최대 {fmt_num(limit, 0)}).")
|
||||||
|
return d.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]:
|
||||||
|
"""{"unit_price","weight_g","silver_pct"} → 정리된 값. 틀리면 ValueError(칸 이름 포함)."""
|
||||||
|
return {k: parse_decimal(values.get(k), key=k) for k in PRODUCT_LIMITS}
|
||||||
|
|
||||||
|
|
||||||
|
def has_values(p: dict[str, Any]) -> bool:
|
||||||
|
"""단가·무게·은 함유량 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||||
|
return any(p.get(k) is not None for k in PRODUCT_LIMITS)
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고증 사진(2026-10-16, 마이그레이션 003)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
MAX_PHOTOS = 10 # 입고 한 건에
|
||||||
|
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 한 장(브라우저가 줄여서 보내므로 보통 0.3~1MB)
|
||||||
|
|
||||||
|
|
||||||
|
def sniff_image(data: bytes) -> str | None:
|
||||||
|
"""파일 머리로 이미지 종류 판단(브라우저가 보낸 종류는 믿지 않는다). 모르면 None."""
|
||||||
|
if data[:3] == b"\xff\xd8\xff":
|
||||||
|
return "image/jpeg"
|
||||||
|
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
||||||
|
return "image/png"
|
||||||
|
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||||
|
return "image/webp"
|
||||||
|
if data[:6] in (b"GIF87a", b"GIF89a"):
|
||||||
|
return "image/gif"
|
||||||
|
if data[4:12] in (b"ftypheic", b"ftypheix", b"ftypmif1", b"ftyphevc", b"ftypheif"):
|
||||||
|
return "image/heic" # 아이폰 원본 — 사파리 외 브라우저는 미리보기 못 함(내려받기)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> list[dict[str, Any]]:
|
||||||
|
"""[(파일 이름, 내용)] → [{filename, content_type, data}]. 빈 파일은 건너뛴다. 하나라도 틀리면 ValueError."""
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for name, data in files:
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
name = (name or "photo").replace("\\", "/").rsplit("/", 1)[-1][:120]
|
||||||
|
if len(data) > MAX_PHOTO_BYTES:
|
||||||
|
raise ValueError(f"사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지): {name}")
|
||||||
|
ctype = sniff_image(data)
|
||||||
|
if ctype is None:
|
||||||
|
raise ValueError(f"사진 파일(JPG·PNG·WEBP·GIF·HEIC)만 올릴 수 있습니다: {name}")
|
||||||
|
out.append({"filename": name, "content_type": ctype, "data": data})
|
||||||
|
if existing + len(out) > MAX_PHOTOS:
|
||||||
|
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||||||
|
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||||||
|
# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
SETTING_LOGISTICS_EMAILS = "logistics_emails"
|
||||||
|
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
|
||||||
|
SETTING_ORDER_MAIL_CC = "order_mail_cc" # 발주 메일 참조 기본값(2026-10-19 — king@, 옵션 → 공장에서 고침)
|
||||||
|
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr",
|
||||||
|
SETTING_ORDER_MAIL_CC: "king@dbxcorp.co.kr"}
|
||||||
|
MAIL_IMAGE_MAX_W = 600
|
||||||
|
|
||||||
|
|
||||||
|
def clean_emails(raw: Any, *, label: str) -> str:
|
||||||
|
"""옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '')."""
|
||||||
|
return ", ".join(parse_emails(raw, label=label))
|
||||||
|
|
||||||
|
|
||||||
|
def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
|
||||||
|
"""입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영).
|
||||||
|
반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps # noqa: WPS433
|
||||||
|
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
skipped = 0
|
||||||
|
for ph in photos:
|
||||||
|
try:
|
||||||
|
im = Image.open(BytesIO(bytes(ph["data"])))
|
||||||
|
if im.format == "JPEG":
|
||||||
|
im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름)
|
||||||
|
im = ImageOps.exif_transpose(im)
|
||||||
|
if im.mode not in ("RGB", "L"):
|
||||||
|
rgba = im.convert("RGBA")
|
||||||
|
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||||
|
bg.paste(rgba, mask=rgba.split()[-1])
|
||||||
|
im = bg
|
||||||
|
if im.width > MAIL_IMAGE_MAX_W:
|
||||||
|
im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS)
|
||||||
|
buf = BytesIO()
|
||||||
|
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
|
||||||
|
except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로)
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height})
|
||||||
|
return out, skipped
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_mail_subject(receipt_date: date) -> str:
|
||||||
|
d = receipt_date
|
||||||
|
return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다."
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0,
|
||||||
|
sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
"""입고 1건 → 제목·글 본문·HTML 본문. 이미지는 <img src="cid:…"> (보낼 때 gmail.build_message 가 본문에 붙임).
|
||||||
|
비고 = 그 발주 품목의 줄 메모. 값은 모두 escape."""
|
||||||
|
memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]}
|
||||||
|
rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")}
|
||||||
|
for x in receipt["lines"]]
|
||||||
|
total = sum(r["qty"] for r in rows)
|
||||||
|
who = sender_name or sender_email
|
||||||
|
when = fmt_date(receipt["receipt_date"])
|
||||||
|
info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}"
|
||||||
|
lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다."
|
||||||
|
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||||
|
text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"]
|
||||||
|
text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows]
|
||||||
|
text.append(f"합계 {total:,}개")
|
||||||
|
if receipt.get("memo"):
|
||||||
|
text += ["", f"메모: {receipt['memo']}"]
|
||||||
|
if images or skipped:
|
||||||
|
text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")]
|
||||||
|
text += ["", f"입고 담당: {who} ({sender_email})"]
|
||||||
|
# HTML 본문
|
||||||
|
e = _html.escape
|
||||||
|
td = "padding:6px 10px;border:1px solid #d9dce1;"
|
||||||
|
r_ = "text-align:right;white-space:nowrap;"
|
||||||
|
bg = "background:#f6f7f9;"
|
||||||
|
body_rows = "".join(
|
||||||
|
f'<tr><td style="{td}">{e(r["name"])}</td><td style="{td}font-family:Consolas,monospace">{e(r["code"])}</td>'
|
||||||
|
f'<td style="{td}{r_}">{r["qty"]:,}</td><td style="{td}">{e(r["note"])}</td></tr>' for r in rows)
|
||||||
|
imgs = "".join(
|
||||||
|
f'<p style="margin:8px 0"><img src="cid:{e(im["cid"])}" width="{im["width"]}" height="{im["height"]}" alt="입고 인증 사진 {i}" '
|
||||||
|
f'style="display:block;width:{im["width"]}px;max-width:100%;height:auto;border:1px solid #d9dce1"></p>'
|
||||||
|
for i, im in enumerate(images, start=1))
|
||||||
|
photo_block = ""
|
||||||
|
if images or skipped:
|
||||||
|
photo_block = (f'<p style="margin:18px 0 4px"><b>입고 인증 사진</b> <span style="color:#777">{len(images)}장</span></p>{imgs}'
|
||||||
|
+ (f'<p style="color:#777">본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.</p>' if skipped else ""))
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
f"<p>안녕하세요.<br>{e(lead)}</p>"
|
||||||
|
f'<p style="color:#555;margin:0 0 8px">{e(info)}</p>'
|
||||||
|
'<table style="border-collapse:collapse;min-width:480px">'
|
||||||
|
f'<thead><tr style="{bg}"><th style="{td}">상품 이름</th><th style="{td}">상품 코드</th><th style="{td}">입고 수량</th>'
|
||||||
|
f'<th style="{td}">비고</th></tr></thead><tbody>{body_rows}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="2" style="{td}{bg}text-align:right">합계</th><th style="{td}{bg}{r_}">{total:,}</th>'
|
||||||
|
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||||
|
+ (f'<p style="margin:10px 0 0">메모: {e(str(receipt["memo"]))}</p>' if receipt.get("memo") else "")
|
||||||
|
+ photo_block
|
||||||
|
+ f'<p style="color:#555;margin-top:18px">입고 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html}
|
||||||
|
|
||||||
|
|
||||||
|
def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str:
|
||||||
|
"""미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로)."""
|
||||||
|
import base64 # noqa: WPS433
|
||||||
|
|
||||||
|
for im in images:
|
||||||
|
html = html.replace(f'src="cid:{_html.escape(im["cid"])}"',
|
||||||
|
f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"')
|
||||||
|
return html
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 사방넷 입고 파일(2026-10-19) — 입고 1건 → 엑셀. 1행 제목 A 상품코드 · B 가용수량 · C 불용수량,
|
||||||
|
# A = 코드표(itemcode_db single_items)의 사방넷 코드, B = 입고 수량, C = 수량이 아니라 상품 이름(사용자 지정).
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
SABANGNET_HEADER = ("상품코드", "가용수량", "불용수량")
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_rows(receipt: dict[str, Any], codes: dict[str, str]) -> tuple[list[list[Any]], list[str]]:
|
||||||
|
"""입고 품목 → (엑셀 줄 [사방넷 코드, 입고 수량, 상품 이름], 사방넷 코드가 없는 품목 "코드 이름" 목록)."""
|
||||||
|
rows: list[list[Any]] = []
|
||||||
|
missing: list[str] = []
|
||||||
|
for x in receipt["lines"]:
|
||||||
|
code = (codes.get(str(x["item_code"]).strip().upper()) or "").strip()
|
||||||
|
if not code:
|
||||||
|
missing.append(f"{x['item_code']} {x['item_name']}".strip())
|
||||||
|
rows.append([code, int(x["qty"]), str(x["item_name"] or "")])
|
||||||
|
return rows, missing
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_xlsx(rows: list[list[Any]]) -> bytes:
|
||||||
|
"""제목 행(굵게·회색 바탕) + 줄. 상품코드·불용수량(상품 이름)은 글자 칸(앞자리 0 보존)."""
|
||||||
|
from io import BytesIO # noqa: WPS433
|
||||||
|
|
||||||
|
from openpyxl import Workbook # noqa: WPS433
|
||||||
|
from openpyxl.styles import Font, PatternFill # noqa: WPS433
|
||||||
|
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "입고"
|
||||||
|
ws.append(list(SABANGNET_HEADER))
|
||||||
|
for c in ws[1]:
|
||||||
|
c.font = Font(bold=True)
|
||||||
|
c.fill = PatternFill(start_color="FFE7E9ED", end_color="FFE7E9ED", fill_type="solid")
|
||||||
|
for code, qty, name in rows:
|
||||||
|
ws.append([code, qty, name])
|
||||||
|
r = ws.max_row
|
||||||
|
ws.cell(row=r, column=1).number_format = "@"
|
||||||
|
ws.cell(row=r, column=3).number_format = "@"
|
||||||
|
for letter, col in (("A", 0), ("B", 1), ("C", 2)):
|
||||||
|
longest = max(sum(2 if ord(ch) > 0x1100 else 1 for ch in str(v)) for v in [SABANGNET_HEADER[col]] + [r[col] for r in rows])
|
||||||
|
ws.column_dimensions[letter].width = max(10, min(60, longest + 2))
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def sabangnet_filename(order: dict[str, Any], receipt: dict[str, Any]) -> str:
|
||||||
|
return f"사방넷_입고_{receipt['receipt_date']:%Y%m%d}_{order['order_no']}.xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 발주 알림 메일(2026-10-19) — 발주 담당이 발주 메일을 보낼 때 입고 담당(옵션 → 담당자)에게 같은 Gmail 로 따로 자동 발송.
|
||||||
|
# 내용 = 발주번호·발주일·제품 코드·제품명·수량만(단가·무게 등은 넣지 않음), 제목 = 발주 메일과 같음.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def order_notice_mail(order: dict[str, Any], *, subject: str, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||||
|
e = _html.escape
|
||||||
|
lines = order["lines"]
|
||||||
|
total = sum(int(x["qty"]) for x in lines)
|
||||||
|
who = sender_name or sender_email
|
||||||
|
when = fmt_date(order["order_date"])
|
||||||
|
text = ["입고 담당자님, 안녕하세요.", "", "아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.", "",
|
||||||
|
f"- 발주번호: {order['order_no']}", f"- 발주일: {when}", "", "[발주 품목] 제품 코드 · 제품명 · 수량"]
|
||||||
|
text += [f"- {x['item_code']} · {x['item_name']} · {int(x['qty']):,}개" for x in lines]
|
||||||
|
text += [f"합계 {total:,}개", "", f"발주 담당: {who} ({sender_email})"]
|
||||||
|
td = "padding:4px 10px;border:1px solid #d9dce1;font-size:14px;line-height:20px;"
|
||||||
|
th = f"{td}background:#f6f7f9;font-weight:700;white-space:nowrap;"
|
||||||
|
r = "text-align:right;white-space:nowrap;"
|
||||||
|
facts = (f'<tr><th style="{th}text-align:left">발주번호</th><td style="{td}">{e(order["order_no"])}</td>'
|
||||||
|
f'<th style="{th}text-align:left">발주일</th><td style="{td}">{e(when)}</td></tr>')
|
||||||
|
rows = "".join(f'<tr><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td><td style="{td}">{e(x["item_name"])}</td>'
|
||||||
|
f'<td style="{td}{r}">{int(x["qty"]):,}</td></tr>' for x in lines)
|
||||||
|
html = (
|
||||||
|
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||||
|
"<p>입고 담당자님, 안녕하세요.<br>아래와 같이 공장에 발주했습니다. 입고 준비에 참고해 주세요.</p>"
|
||||||
|
f'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;margin:8px 0 0">{facts}</table>'
|
||||||
|
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||||
|
'<table cellpadding="0" cellspacing="0" style="border-collapse:collapse;min-width:420px">'
|
||||||
|
f'<thead><tr><th style="{th}">제품 코드</th><th style="{th}">제품명</th><th style="{th}">수량</th></tr></thead>'
|
||||||
|
f'<tbody>{rows}</tbody>'
|
||||||
|
f'<tfoot><tr><th colspan="2" style="{th}text-align:right">합계</th><th style="{th}{r}">{total:,}</th></tr></tfoot></table>'
|
||||||
|
f'<p style="color:#555;margin-top:18px">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||||
|
)
|
||||||
|
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
{# 상태 배지 — 발주서(open·partial·done·over·closed·cancelled) / 품목(none·partial·done·over) #}
|
||||||
|
{% macro status_badge(status, label) -%}
|
||||||
|
<span class="io-badge io-st-{{ status }}">{{ label }}</span>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 진행률 막대 — 입고 ÷ 발주 #}
|
||||||
|
{% macro progress(summary) -%}
|
||||||
|
<span class="io-progress" title="입고 {{ '{:,}'.format(summary.received) }} / 발주 {{ '{:,}'.format(summary.ordered) }}">
|
||||||
|
<span class="io-progress-bar{% if summary.over %} is-over{% endif %}" style="width:{{ summary.pct }}%"></span>
|
||||||
|
</span><span class="io-progress-pct">{{ summary.pct }}%</span>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 날짜 서식 — 2026.10.17(토) / 2026.10.17(토) 15:14 (2026-10-17 요청, 메일·JSON 은 store.fmt_date·fmt_datetime) #}
|
||||||
|
{% macro ymd(d) -%}{% if d %}{{ d.strftime('%Y.%m.%d') }}({{ '월화수목금토일'[d.weekday()] }}){% endif %}{%- endmacro %}
|
||||||
|
{% macro ymdhm(d) -%}{% if d %}{{ ymd(d) }} {{ d.strftime('%H:%M') }}{% endif %}{%- endmacro %}
|
||||||
|
|
||||||
|
{# 발주서 상태 — 모든 품목이 입고완료·초과입고면 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함"), 나머지는 상태 배지 #}
|
||||||
|
{% macro order_badge(status, label) -%}
|
||||||
|
{% if status in ('done', 'over') %}<span class="io-badge io-st-done io-st-all">✓ {{ label }}</span>{% if status == 'over' %}<span class="io-badge-note">초과 포함</span>{% endif %}
|
||||||
|
{%- else %}{{ status_badge(status, label) }}{% endif %}
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{# 입고 예정일 — 지났는데 남은 게 있으면 빨강 "지연 N일" #}
|
||||||
|
{% macro due(due_date, today, active) -%}
|
||||||
|
{% if due_date %}{{ ymd(due_date) }}{% if active and due_date < today %} <span class="io-late">지연 {{ (today - due_date).days }}일</span>{% elif active %} <span class="erp-muted">D-{{ (due_date - today).days }}</span>{% endif %}{% else %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{% macro n(v) -%}{{ '{:,}'.format(v or 0) }}{%- endmacro %}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
{# 입출고 관리 공용 상단: 탭(발주 목록·미입고 현황) + 담당 표시 + 새 발주서 + 옵션 톱니(관리자, 팝업) + 알림 문구(?msg=) #}
|
||||||
|
<div class="io-nav">
|
||||||
|
<a class="erp-btn {% if tab == 'orders' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/">발주 목록</a>
|
||||||
|
<a class="erp-btn {% if tab == 'pending' %}erp-btn-primary{% else %}erp-btn-outline{% endif %}" href="/inout/pending">미입고 현황</a>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<span class="io-roles erp-muted">
|
||||||
|
{% if perms.can_order %}<span class="erp-badge erp-badge-neutral">발주 담당</span>{% endif %}
|
||||||
|
{% if perms.can_receive %}<span class="erp-badge erp-badge-neutral">입고 담당</span>{% endif %}
|
||||||
|
{% if not perms.can_order and not perms.can_receive %}조회만 가능 — 담당 지정은 옵션(관리자){% endif %}
|
||||||
|
</span>
|
||||||
|
{% if perms.can_order %}<a class="erp-btn erp-btn-primary" href="/inout/orders/new">+ 새 발주서</a>{% endif %}
|
||||||
|
{% if perms.admin %}
|
||||||
|
<button type="button" class="io-gear" id="io-options-btn" title="입출고 관리 옵션" aria-label="입출고 관리 옵션"
|
||||||
|
aria-haspopup="dialog" {% if open_options %}data-open="1"{% endif %}>
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||||
|
<circle cx="12" cy="12" r="3"/>
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if msg %}<p class="io-flash" role="status">{{ msg }}</p>{% endif %}
|
||||||
|
|
||||||
|
{% if perms.admin %}
|
||||||
|
{# 옵션 팝업 — 내용은 열 때 GET /inout/settings?panel=1 로 받아 넣고, 저장은 제자리에서(inout.js) #}
|
||||||
|
<dialog class="io-dlg" id="io-options" aria-labelledby="io-options-title" tabindex="-1">
|
||||||
|
<header class="io-dlg-head">
|
||||||
|
<h2 id="io-options-title">입출고 관리 옵션</h2>
|
||||||
|
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p class="io-dlg-msg" role="status" hidden></p>
|
||||||
|
<div class="io-dlg-body" id="io-options-body"><p class="erp-muted">불러오는 중…</p></div>
|
||||||
|
</dialog>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
{% from "inout/_macros.html" import ymd %}
|
||||||
|
{# 옵션 팝업 내용(GET /inout/settings?panel=1) — 탭: 담당자 · 공장 · 상품 정보(004). 폼 저장은 inout.js 가 제자리에서(X-Inout-Options: 1 → JSON).
|
||||||
|
공장 줄은 표(<table>) 안에 폼을 둘 수 없어 입력칸에 form="…" 속성으로 표 밖 폼에 묶는다 — 열이 머리 줄과 맞는다. #}
|
||||||
|
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
|
||||||
|
<button type="button" role="tab" class="is-active" aria-selected="true" data-pane="roles">담당자</button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="factories" tabindex="-1">공장 <span class="io-dlg-count">{{ factories|length }}</span></button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="products" tabindex="-1">상품 정보 <span class="io-dlg-count">{{ products|length }}</span></button>
|
||||||
|
<button type="button" role="tab" aria-selected="false" data-pane="logistics" tabindex="-1">물류센터</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="roles" role="tabpanel">
|
||||||
|
<p class="io-help">
|
||||||
|
<b>발주 담당</b> — 발주서 작성·고치기·잔량 종결·취소. <b>입고 담당</b> — 물류에 들어온 입고 수량 입력·지우기.
|
||||||
|
그 밖의 사람은 조회만 합니다. ERP 관리자는 지정 없이도 둘 다 할 수 있습니다.
|
||||||
|
후보 = ERP 관리자 화면에서 <b>입출고 관리</b> 권한을 받은 사용자.
|
||||||
|
</p>
|
||||||
|
<form method="post" action="/inout/settings/roles" class="io-dlg-form">
|
||||||
|
<table class="io-dlg-table">
|
||||||
|
<thead><tr><th>사용자</th>{% for role, label in role_labels.items() %}<th class="io-c">{{ label }}</th>{% endfor %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for c in candidates %}
|
||||||
|
<tr>
|
||||||
|
<td><b class="io-user">{{ c.name or c.email }}</b><span class="io-sub">{{ c.email }}</span></td>
|
||||||
|
{% for role in role_labels %}
|
||||||
|
<td class="io-c"><input type="checkbox" name="{{ role }}_email" value="{{ c.email }}" {% if c.email in roles[role] %}checked{% endif %}
|
||||||
|
aria-label="{{ c.email }} {{ role_labels[role] }}" /></td>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="3" class="io-empty">입출고 관리 권한을 받은 사용자가 없습니다 — ERP 관리자 화면에서 먼저 권한을 주세요.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary">담당자 저장</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="factories" role="tabpanel" hidden>
|
||||||
|
<p class="io-help">발주서에서 고르는 공장(발주처)입니다. <b>이메일</b>은 발주 메일을 받을 주소(여러 개는 쉼표). 발주 기록이 있는 공장은 지우지 말고 <b>사용</b>을 끄면 목록에서 숨겨집니다.</p>
|
||||||
|
<form method="post" action="/inout/settings/order-mail" class="io-dlg-form io-ordercc-form">
|
||||||
|
<label class="io-logi-field"><span>발주 메일 참조 <small>(모든 발주 메일의 참조 칸에 미리 들어감 — 보낼 때 고칠 수 있음, 여러 개는 쉼표)</small></span>
|
||||||
|
<span class="io-ordercc-row"><input class="io-in" type="text" inputmode="email" name="order_mail_cc" value="{{ settings.order_mail_cc }}" maxlength="1000"
|
||||||
|
aria-label="발주 메일 참조" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm"{% if not settings_ready %} disabled title="DB 마이그레이션 inout_db 005 필요"{% endif %}>저장</button></span></label>
|
||||||
|
</form>
|
||||||
|
{% for f in factories %}<form method="post" action="/inout/settings/factories" id="io-f{{ f.id }}" class="io-dlg-form"><input type="hidden" name="id" value="{{ f.id }}" /></form>{% endfor %}
|
||||||
|
<form method="post" action="/inout/settings/factories" id="io-fnew" class="io-dlg-form"><input type="hidden" name="is_active" value="1" /></form>
|
||||||
|
<table class="io-dlg-table io-factory-table">
|
||||||
|
<colgroup><col class="w-name" /><col class="w-man" /><col class="w-tel" /><col class="w-mail" /><col class="w-memo" /><col class="w-sort" /><col class="w-use" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
|
||||||
|
<thead><tr><th>공장 이름</th><th>담당자</th><th>연락처</th><th title="발주 메일을 받을 주소 — 여러 개는 쉼표로">이메일</th><th>메모</th><th class="io-c">순서</th><th class="io-c">사용</th><th class="io-c">발주</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for f in factories %}
|
||||||
|
{% set fid = 'io-f' ~ f.id %}
|
||||||
|
<tr class="{% if not f.is_active %}is-inactive{% endif %}">
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="name" value="{{ f.name }}" maxlength="100" required aria-label="공장 이름" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="manager" value="{{ f.manager }}" maxlength="100" aria-label="담당자" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="tel" name="contact" value="{{ f.contact }}" maxlength="200" aria-label="연락처" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" inputmode="email" name="email" value="{{ f.email }}" maxlength="600" aria-label="이메일" placeholder="발주 메일 받는 주소" /></td>
|
||||||
|
<td><input class="io-in" form="{{ fid }}" type="text" name="memo" value="{{ f.memo }}" maxlength="500" aria-label="메모" /></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="{{ fid }}" type="number" name="sort_order" value="{{ f.sort_order }}" aria-label="순서" /></td>
|
||||||
|
<td class="io-c"><input form="{{ fid }}" type="checkbox" name="is_active" value="1" {% if f.is_active %}checked{% endif %} aria-label="사용" /></td>
|
||||||
|
<td class="io-c io-sub">{{ f.order_count }}건</td>
|
||||||
|
<td class="io-btns">
|
||||||
|
<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm">저장</button>
|
||||||
|
{% if not f.order_count %}<button form="{{ fid }}" type="submit" class="erp-btn erp-btn-outline erp-btn-sm" formaction="/inout/settings/factories/{{ f.id }}/delete"
|
||||||
|
formnovalidate data-confirm="공장 '{{ f.name }}' 을(를) 지울까요?">지우기</button>{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
<tr class="io-new-row">
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="name" maxlength="100" required placeholder="새 공장 이름" aria-label="새 공장 이름" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="manager" maxlength="100" placeholder="담당자" aria-label="담당자" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="tel" name="contact" maxlength="200" placeholder="010-0000-0000" aria-label="연락처" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" inputmode="email" name="email" maxlength="600" placeholder="factory@example.com" aria-label="이메일" /></td>
|
||||||
|
<td><input class="io-in" form="io-fnew" type="text" name="memo" maxlength="500" placeholder="메모" aria-label="메모" /></td>
|
||||||
|
<td class="io-c"><input class="io-in io-in-num" form="io-fnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
|
||||||
|
<td></td><td></td>
|
||||||
|
<td class="io-btns"><button form="io-fnew" type="submit" class="erp-btn erp-btn-primary erp-btn-sm">+ 추가</button></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
|
||||||
|
{% if not products_ready %}
|
||||||
|
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="io-help">
|
||||||
|
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
|
||||||
|
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||||
|
</p>
|
||||||
|
<div class="io-prod-bar">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||||
|
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
|
||||||
|
<span class="io-sub" id="io-prod-count">{{ products|length }}개{% if excluded %} · 제외 {{ excluded|length }}개{% endif %}</span>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" id="io-prod-save" disabled>변경 저장 <span id="io-prod-dirty"></span></button>
|
||||||
|
</div>
|
||||||
|
{% if products %}
|
||||||
|
<div class="io-prod-scroll">
|
||||||
|
<table class="io-dlg-table io-prod-table">
|
||||||
|
<colgroup><col class="w-code" /><col /><col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" /><col class="w-del" /></colgroup>
|
||||||
|
<thead><tr><th>코드</th><th>제품명</th><th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th><th></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for p in products %}
|
||||||
|
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name)|lower }}">
|
||||||
|
<td class="io-code">{{ p.item_code }}</td>
|
||||||
|
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||||
|
<td><input class="io-in io-in-num" data-key="silver_pct" value="{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" /></td>
|
||||||
|
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||||
|
<td class="io-r"><button type="button" class="io-icon-btn" data-exclude="{{ p.item_code }}" title="지우기 — 다음 불러오기에서도 뺌" aria-label="{{ p.item_code }} 지우기">✕</button></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||||
|
{% endif %}
|
||||||
|
{% if excluded %}
|
||||||
|
<details class="io-excluded">
|
||||||
|
<summary>제외 목록 {{ excluded|length }}개 — 불러오기에서 빠지는 단품</summary>
|
||||||
|
<ul>
|
||||||
|
{% for x in excluded %}
|
||||||
|
<li><span class="io-code">{{ x.item_code }}</span> {{ x.item_name }} <span class="io-sub">· {{ ymd(x.excluded_at) }}</span>
|
||||||
|
<button type="button" class="io-link-btn" data-restore="{{ x.item_code }}">되살리기</button></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="io-dlg-pane" data-pane="logistics" role="tabpanel" hidden>
|
||||||
|
{% if not settings_ready %}
|
||||||
|
<p class="io-error">DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
|
||||||
|
{% endif %}
|
||||||
|
<p class="io-help">
|
||||||
|
입고 담당이 <b>입고 저장</b>을 누르면 물류센터 입고 담당자에게 보낼 <b>입고 요청 메일</b>(전산 등록 부탁 · 입고 상품 표 · 입고증 사진)을
|
||||||
|
미리 보여 주고, [메일 발송]을 눌러 입고 담당 본인 Gmail 로 보냅니다. 아래 주소가 받는 사람·참조 칸에 미리 들어갑니다(보낼 때 고칠 수 있음).
|
||||||
|
</p>
|
||||||
|
<form method="post" action="/inout/settings/logistics" class="io-dlg-form io-logi-form">
|
||||||
|
<label class="io-logi-field"><span>물류센터 담당자 이메일 <small>(받는 사람 — 여러 개는 쉼표)</small></span>
|
||||||
|
<input class="io-in" type="text" inputmode="email" name="logistics_emails" value="{{ settings.logistics_emails }}" maxlength="1000"
|
||||||
|
placeholder="logistics@example.com" aria-label="물류센터 담당자 이메일" /></label>
|
||||||
|
<label class="io-logi-field"><span>입고 요청 메일 참조 <small>(여러 개는 쉼표)</small></span>
|
||||||
|
<input class="io-in" type="text" inputmode="email" name="receipt_mail_cc" value="{{ settings.receipt_mail_cc }}" maxlength="1000"
|
||||||
|
aria-label="입고 요청 메일 참조" /></label>
|
||||||
|
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary"{% if not settings_ready %} disabled{% endif %}>물류센터 저장</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<p class="io-dlg-foot">코드표(단품) 연결: {{ items_status }}</p>
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="io-filter" method="get" action="/inout/">
|
||||||
|
{# 상태 = 링크(다른 거르기 값 유지). 검색 칸 Enter 는 아래 [찾기] — 상태는 숨은 칸 값 그대로 #}
|
||||||
|
{% set keep = {'factory': filters.factory or '', 'q': filters.q, 'from': filters['from'], 'to': filters['to']} %}
|
||||||
|
<div class="io-seg" role="group" aria-label="상태">
|
||||||
|
{% for key, f in status_filters.items() %}
|
||||||
|
<a href="/inout/?{{ dict(keep, status=key) | urlencode }}" class="io-seg-btn{% if filters.status == key %} is-active{% endif %}"
|
||||||
|
{% if filters.status == key %}aria-current="true"{% endif %}>{{ f[0] }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<input type="hidden" name="status" value="{{ filters.status }}" />
|
||||||
|
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
|
||||||
|
<option value="">전체 공장</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
<label class="io-date">발주일 <input class="erp-input" type="date" name="from" value="{{ filters['from'] }}" /></label>
|
||||||
|
<span class="erp-muted">~</span>
|
||||||
|
<input class="erp-input" type="date" name="to" value="{{ filters['to'] }}" aria-label="발주일 끝" />
|
||||||
|
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="발주번호·제품 코드·제품 이름" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="erp-card-block">
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr>
|
||||||
|
<th>발주번호</th><th>공장</th><th>제품</th><th>발주일</th><th>입고 예정일</th>
|
||||||
|
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th><th>진행</th><th>상태</th>
|
||||||
|
{% if perms.super %}<th class="io-col-trash"><span class="sr-only">삭제</span></th>{% endif %}
|
||||||
|
</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for o in orders %}
|
||||||
|
{% set active = o.status in ('open', 'partial') %}
|
||||||
|
<tr class="io-row-link" data-href="/inout/orders/{{ o.id }}">
|
||||||
|
<td><a href="/inout/orders/{{ o.id }}" class="io-order-no">{{ o.order_no }}</a></td>
|
||||||
|
<td>{{ o.factory_name }}</td>
|
||||||
|
<td class="io-items">{{ o.items_label }}<div class="erp-row-sub">{{ o.line_count }}종</div></td>
|
||||||
|
<td>{{ ymd(o.order_date) }}</td>
|
||||||
|
<td>{{ due(o.due_date, today, active) }}</td>
|
||||||
|
<td class="io-num">{{ n(o.summary.ordered) }}</td>
|
||||||
|
<td class="io-num">{{ n(o.summary.received) }}</td>
|
||||||
|
<td class="io-num{% if o.summary.remaining and active %} io-remaining{% endif %}">{{ n(o.summary.remaining) }}{% if o.summary.over %}<div class="io-over-sub">초과 +{{ n(o.summary.over) }}</div>{% endif %}</td>
|
||||||
|
<td class="io-progress-cell">{{ progress(o.summary) }}</td>
|
||||||
|
<td class="io-status-cell">{{ order_badge(o.status, o.status_label) }}</td>
|
||||||
|
{% if perms.super %}
|
||||||
|
{# 수퍼관리자만 — 완전 삭제(품목·입고 기록·사진·메일 기록까지) #}
|
||||||
|
<td class="io-col-trash"><form method="post" action="/inout/orders/{{ o.id }}/delete"
|
||||||
|
data-erp-confirm="{{ o.order_no }} 발주서를 완전히 삭제할까요?{% if o.summary.received %} 입고 {{ n(o.summary.received) }}개 기록과 입고증 사진{% else %} 품목{% endif %}·발주 메일 기록까지 모두 지워지고 되돌릴 수 없습니다.">
|
||||||
|
<input type="hidden" name="back" value="{{ request.url.path }}{% if request.url.query %}?{{ request.url.query }}{% endif %}" />
|
||||||
|
<button type="submit" class="io-icon-btn io-del-btn" title="발주 삭제(수퍼관리자)" aria-label="{{ o.order_no }} 발주 삭제">
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg>
|
||||||
|
</button></form></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="{{ 11 if perms.super else 10 }}" class="erp-empty">{% if filters.status == 'active' %}진행 중인 발주가 없습니다.{% else %}조건에 맞는 발주가 없습니다.{% endif %}</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %}
|
||||||
|
{#- 메일 창(발주 메일 · 입고 요청 메일 같은 모양) — 열면 미리보기 GET, [메일 발송]을 눌러야 보낸다(inout.js initMail) -#}
|
||||||
|
{%- macro mail_dialog(id, title, open_url='', open_title='') -%}
|
||||||
|
<dialog class="io-dlg io-mail-dlg" id="{{ id }}" aria-labelledby="{{ id }}-title" tabindex="-1"
|
||||||
|
{%- if open_url %} data-open-url="{{ open_url }}" data-open-title="{{ open_title }}"{% endif %}>
|
||||||
|
<header class="io-dlg-head">
|
||||||
|
<h2 id="{{ id }}-title" data-mail-title>{{ title }}</h2>
|
||||||
|
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<p class="io-dlg-msg" role="status" hidden></p>
|
||||||
|
<div class="io-dlg-body" data-mail-body><p class="erp-muted">불러오는 중…</p></div>
|
||||||
|
<footer class="io-dlg-footbar" data-mail-foot hidden>
|
||||||
|
<button type="button" class="io-link-btn" data-gmail-disconnect>Gmail 연결 끊기</button>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary" data-mail-send>메일 발송</button>
|
||||||
|
</footer>
|
||||||
|
</dialog>
|
||||||
|
{%- endmacro -%}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% set active = order.status in ('open', 'partial') %}
|
||||||
|
{% set receiving = perms.can_receive and can_receive_now %}
|
||||||
|
{# 전체 입고 완료(모든 품목 입고완료·초과) — 입고 칸·[입고 저장]을 흐리게 막는다(서버도 거절, 2026-10-19). 입고 기록을 지우면 다시 열림 #}
|
||||||
|
{% set recv_done = order.status in ('done', 'over') %}
|
||||||
|
{% set dis = ' disabled' if recv_done else '' %}
|
||||||
|
{% set photo_admin = perms.can_receive and not order.cancelled_at %}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<div class="erp-card-block io-head">
|
||||||
|
<div class="io-head-main">
|
||||||
|
<div class="io-head-title">
|
||||||
|
<h2>{{ order.order_no }}</h2>{{ order_badge(order.status, order.status_label) }}
|
||||||
|
</div>
|
||||||
|
<dl class="io-head-meta">
|
||||||
|
<div><dt>공장</dt><dd>{{ order.factory_name }}{% if order.factory_manager or order.factory_contact %}<span class="io-factory-who">{{ order.factory_manager }}{% if order.factory_manager and order.factory_contact %} · {% endif %}{{ order.factory_contact }}</span>{% endif %}</dd></div>
|
||||||
|
<div><dt>발주일</dt><dd>{{ ymd(order.order_date) }}</dd></div>
|
||||||
|
<div><dt>입고 예정일</dt><dd>{{ due(order.due_date, today, active) }}</dd></div>
|
||||||
|
<div><dt>진행</dt><dd>{{ progress(order.summary) }}</dd></div>
|
||||||
|
<div><dt>발주 메일</dt><dd>{% if order.mails %}{% set last = order.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(last.sent_at) }}</span><span class="io-factory-who">{{ last.sent_by }} → {{ last.to_addrs }}{% if order.mails|length > 1 %} · 모두 {{ order.mails|length }}번{% endif %}</span>{% else %}<span class="erp-muted">아직 안 보냄</span>{% endif %}</dd></div>
|
||||||
|
{% if order.memo %}<div class="io-wide"><dt>메모</dt><dd>{{ order.memo }}</dd></div>{% endif %}
|
||||||
|
{% if order.closed_at %}<div class="io-wide"><dt>종결</dt><dd>{{ ymd(order.closed_at) }} · {{ order.closed_by }}{% if order.close_reason %} — {{ order.close_reason }}{% endif %}</dd></div>{% endif %}
|
||||||
|
{% if order.cancelled_at %}<div class="io-wide"><dt>취소</dt><dd>{{ ymd(order.cancelled_at) }} · {{ order.cancelled_by }}</dd></div>{% endif %}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="io-kpis io-kpis-head">
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">발주</div><div class="erp-summary-value">{{ n(order.summary.ordered) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">입고</div><div class="erp-summary-value">{{ n(order.summary.received) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini{% if order.summary.remaining and active %} io-kpi-remaining{% endif %}"><div class="erp-summary-label">미입고</div><div class="erp-summary-value">{{ n(order.summary.remaining) }}</div></div>
|
||||||
|
{% if order.summary.over %}<div class="erp-summary-card erp-summary-card--mini io-kpi-over"><div class="erp-summary-label">초과</div><div class="erp-summary-value">+{{ n(order.summary.over) }}</div></div>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if perms.can_order and not order.cancelled_at %}
|
||||||
|
<div class="io-head-actions">
|
||||||
|
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm io-mail-btn" id="io-mail-btn" data-order="{{ order.id }}"
|
||||||
|
{% if open_mail %}data-open="1"{% endif %} aria-haspopup="dialog">
|
||||||
|
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
|
||||||
|
{% if order.mails %}발주 메일 다시 보내기{% else %}발주 메일 보내기{% endif %}</button>
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/inout/orders/{{ order.id }}/edit">발주서 고치기</a>
|
||||||
|
{% if order.closed_at %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/reopen"><button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">종결 풀기</button></form>
|
||||||
|
{% elif order.summary.remaining %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/close" class="io-close-form" data-erp-confirm="남은 미입고 {{ n(order.summary.remaining) }}개를 더 기다리지 않고 종결할까요? 미입고 현황에서 빠집니다.">
|
||||||
|
<input class="erp-input io-close-reason" type="text" name="reason" maxlength="500" placeholder="종결 사유(선택)" />
|
||||||
|
<button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">잔량 종결</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% if not order.receipts %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/cancel" data-erp-confirm="이 발주서를 취소할까요? (입고 기록이 없을 때만)">
|
||||||
|
<button class="erp-btn erp-btn-danger erp-btn-sm" type="submit">발주 취소</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
|
||||||
|
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/receipts" class="erp-card-block io-block" id="io-receipt-form" enctype="multipart/form-data">
|
||||||
|
{# Enter 키 = 이 버튼(일반 저장). 없으면 폼의 첫 제출 버튼인 [초과 입고로 저장]이 눌려 확인 없이 초과가 저장된다 #}
|
||||||
|
{% if receiving %}<button type="submit" class="io-default-submit" tabindex="-1" aria-hidden="true"{{ dis }}>입고 저장</button>{% endif %}
|
||||||
|
<input type="hidden" name="confirm_over" value="" id="io-confirm-over" />
|
||||||
|
<div class="erp-card-block-head">
|
||||||
|
<h2>품목</h2>
|
||||||
|
{% if receiving and recv_done %}<span class="erp-muted io-recv-done-note">✓ 전체 입고 완료 — 더 입고할 수 없습니다(잘못 넣은 입고는 아래 입고 기록에서 지운 뒤 다시 넣으세요)</span>
|
||||||
|
{% elif receiving %}<span class="erp-muted">물류에 들어온 수량을 [이번 입고]에 넣고 저장 — 여러 번 나눠 넣어도 됩니다</span>
|
||||||
|
{% elif perms.can_receive and order.closed_at %}<span class="erp-muted">종결된 발주서 — 입고하려면 발주 담당이 종결을 풀어야 합니다</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if over %}
|
||||||
|
<div class="io-over-box" role="alert">
|
||||||
|
<b>발주보다 많이 입고하려고 합니다.</b> 맞으면 [초과 입고로 저장]을 누르세요.
|
||||||
|
<ul>{% for o in over %}<li>{% if not items_limited %}<span class="io-code">{{ o.item_code }}</span> {% endif %}{{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
|
||||||
|
{% if photos_lost %}<p class="io-photo-lost">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>{% endif %}
|
||||||
|
<button type="submit" class="io-btn-over" name="confirm_over" value="1">초과 입고로 저장</button>
|
||||||
|
<span class="erp-muted">숫자를 고치려면 아래 칸을 고친 뒤 [입고 저장]</span>
|
||||||
|
</div>
|
||||||
|
{% elif photos_lost %}
|
||||||
|
<p class="io-error">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
{# 입고 담당(발주 담당 아님) = 제품 이름·발주 수량(+ 이번 입고)만, 발주 담당 = 단가·금액·PP·은 함께 #}
|
||||||
|
<thead><tr><th class="io-col-no">#</th>{% if not items_limited %}<th>제품 코드</th>{% endif %}<th>제품</th><th class="io-num">발주</th>
|
||||||
|
{% if show_prices %}<th class="io-num io-col-money">단가(원)</th><th class="io-num io-col-money">금액(원)</th><th class="io-num io-col-spec">PP(g/개)</th><th class="io-num io-col-spec">은(Ag)</th>{% endif %}
|
||||||
|
{% if not items_limited %}<th class="io-num">입고</th><th class="io-num">미입고</th><th>상태</th>{% endif %}
|
||||||
|
{% if receiving %}<th class="io-col-recv">이번 입고</th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for ln in order.lines %}
|
||||||
|
<tr>
|
||||||
|
<td class="io-col-no">{{ loop.index }}</td>
|
||||||
|
{% if not items_limited %}<td class="io-code">{{ ln.item_code }}</td>{% endif %}
|
||||||
|
<td>{{ ln.item_name }}{% if ln.memo %}<div class="erp-row-sub">{{ ln.memo }}</div>{% endif %}</td>
|
||||||
|
<td class="io-num">{{ n(ln.qty) }}</td>
|
||||||
|
{% if show_prices %}
|
||||||
|
{% set amt = line_amount(ln.qty, ln.unit_price) %}{% set ag = silver_g(ln.weight_g, ln.silver_pct) %}
|
||||||
|
<td class="io-num io-col-money">{{ fmt_num(ln.unit_price) if ln.unit_price is not none else '-' }}</td>
|
||||||
|
<td class="io-num io-col-money">{{ fmt_num(amt) if amt is not none else '-' }}</td>
|
||||||
|
<td class="io-num io-col-spec">{{ fmt_num(ln.weight_g) if ln.weight_g is not none else '-' }}</td>
|
||||||
|
<td class="io-num io-col-spec">{% if ln.silver_pct is not none %}{{ fmt_num(ln.silver_pct, 4) }}%{% if ag is not none %}<div class="erp-row-sub">{{ fmt_num(ag, 4) }}g/개</div>{% endif %}{% else %}-{% endif %}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if not items_limited %}
|
||||||
|
<td class="io-num">{{ n(ln.received) }}</td>
|
||||||
|
<td class="io-num{% if ln.remaining and active %} io-remaining{% endif %}">{{ n(ln.remaining) }}{% if ln.over %}<div class="io-over-sub">초과 +{{ n(ln.over) }}</div>{% endif %}</td>
|
||||||
|
<td>{{ status_badge(ln.status, ln.status_label) }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% if receiving %}<td class="io-col-recv"><input class="erp-input io-qty io-recv" type="text" inputmode="numeric" name="qty_{{ ln.id }}"
|
||||||
|
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" data-ordered="{{ ln.qty }}" data-received="{{ ln.received }}"
|
||||||
|
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining and not items_limited else '' }}"
|
||||||
|
aria-label="{{ ln.item_name }} 이번 입고 수량"{{ dis }} /></td>{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
{% if show_prices and order.lines %}
|
||||||
|
<tfoot><tr class="io-total-row">
|
||||||
|
<td colspan="3">합계</td>
|
||||||
|
<td class="io-num">{{ n(order.summary.ordered) }}</td>
|
||||||
|
<td class="io-num io-col-money"></td>
|
||||||
|
<td class="io-num io-col-money"><b>{{ fmt_num(totals.amount) if totals.amount is not none else '-' }}</b>{% if totals.missing_price %}<div class="erp-row-sub">단가 미입력 {{ totals.missing_price }}종 제외</div>{% endif %}</td>
|
||||||
|
<td class="io-num io-col-spec">{% if totals.pp_kg is not none %}{{ fmt_num(totals.pp_kg, 3) }}kg{% else %}-{% endif %}</td>
|
||||||
|
<td class="io-num io-col-spec">{% if totals.silver_g is not none %}{{ fmt_num(totals.silver_g, 2) }}g{% else %}-{% endif %}</td>
|
||||||
|
{% if not items_limited %}<td colspan="3"></td>{% endif %}
|
||||||
|
{% if receiving %}<td></td>{% endif %}
|
||||||
|
</tr></tfoot>
|
||||||
|
{% endif %}
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if receiving %}
|
||||||
|
<div class="io-receipt-bar{% if recv_done %} is-locked{% endif %}"{% if recv_done %} aria-disabled="true" title="전체 입고 완료 — 더 입고할 수 없습니다"{% endif %}>
|
||||||
|
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required{{ dis }} /></label>
|
||||||
|
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등"{{ dis }} /></label>
|
||||||
|
<div class="erp-field io-photo-field">
|
||||||
|
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
|
||||||
|
<label class="io-photo-pick">
|
||||||
|
<input type="file" name="photos" accept="image/*" multiple id="io-photo-input" class="io-photo-input" data-max="{{ max_photos }}"{{ dis }} />
|
||||||
|
<svg class="io-photo-pick-icon" viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
|
||||||
|
입고증 업로드
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline" id="io-fill-remaining"{{ dis }}>남은 수량 모두 채우기</button>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary io-recv-save"{{ dis }}>입고 저장 <span id="io-recv-total"></span></button>
|
||||||
|
<div class="io-photo-previews" id="io-photo-previews" aria-live="polite"></div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>입고 기록</h2><span class="erp-muted">{{ order.receipts|length }}회</span></div>
|
||||||
|
{% if order.receipts %}
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th><th>입고 요청 메일 · 사방넷</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in order.receipts %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ ymd(r.receipt_date) }}{% if r.memo %}<div class="erp-row-sub">{{ r.memo }}</div>{% endif %}</td>
|
||||||
|
<td>{% for x in r.lines %}<span class="io-chip">{% if items_limited %}{{ x.item_name }}{% else %}<span class="io-code">{{ x.item_code }}</span>{% endif %} {{ n(x.qty) }}</span>{% endfor %}</td>
|
||||||
|
<td class="io-num">{{ n(r.total) }}</td>
|
||||||
|
<td class="io-photos-cell">
|
||||||
|
{% for ph in r.photos %}
|
||||||
|
<button type="button" class="io-thumb" data-photo="{{ ph.id }}" data-receipt="{{ r.id }}" data-type="{{ ph.content_type }}"
|
||||||
|
data-name="{{ ph.filename }}" title="{{ ph.filename }} — 크게 보기" aria-label="입고증 사진 크게 보기 {{ loop.index }}">
|
||||||
|
{% if ph.content_type == 'image/heic' %}<span class="io-thumb-heic">HEIC</span>{% else %}<img src="/inout/photos/{{ ph.id }}" alt="" loading="lazy" />{% endif %}
|
||||||
|
</button>
|
||||||
|
{% endfor %}
|
||||||
|
{% if photo_admin and r.photos|length < max_photos %}
|
||||||
|
<form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/photos" enctype="multipart/form-data" class="io-add-photo-form">
|
||||||
|
<label class="io-thumb io-thumb-add" title="입고증 사진 더하기">
|
||||||
|
<input type="file" name="photos" accept="image/*" multiple class="io-photo-input io-photo-auto" data-max="{{ max_photos - r.photos|length }}" aria-label="입고증 사진 더하기" />
|
||||||
|
<span aria-hidden="true">+</span>
|
||||||
|
</label>
|
||||||
|
</form>
|
||||||
|
{% elif not r.photos %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="erp-muted">{{ r.created_by }}<div class="erp-row-sub">{{ ymdhm(r.created_at) }}</div></td>
|
||||||
|
<td class="io-rmail-cell">
|
||||||
|
{% if r.mails %}{% set lm = r.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(lm.sent_at) }}</span>
|
||||||
|
<div class="erp-row-sub">{{ lm.sent_by }}{% if r.mails|length > 1 %} · 모두 {{ r.mails|length }}번{% endif %}</div>{% endif %}
|
||||||
|
{% if perms.can_receive %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-rmail-btn" aria-haspopup="dialog"
|
||||||
|
data-url="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/mail" data-title="입고 요청 메일 · {{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개">
|
||||||
|
{% if r.mails %}다시 보내기{% else %}보내기{% endif %}</button>
|
||||||
|
{% elif not r.mails %}<span class="erp-muted">-</span>{% endif %}
|
||||||
|
{% if perms.can_order or perms.can_receive %}
|
||||||
|
<a class="erp-btn erp-btn-outline erp-btn-sm io-sabang-btn" href="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/sabangnet.xlsx"
|
||||||
|
title="사방넷 입고 엑셀 — 상품코드(사방넷 코드)·가용수량(입고 수량)·불용수량(상품 이름)" download>사방넷 입고 파일</a>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
{% if photo_admin %}
|
||||||
|
<td><form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/delete"
|
||||||
|
data-erp-confirm="{{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 되고 입고증 사진도 지워집니다.">
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">지우기</button></form></td>
|
||||||
|
{% endif %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<p class="erp-empty">아직 입고된 것이 없습니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{# 입고증 사진 크게 보기 — 앞뒤 넘기기(←/→), 원본 열기, 지우기(입고 담당) #}
|
||||||
|
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
||||||
|
<div class="io-viewer-bar">
|
||||||
|
<span class="io-viewer-title" id="io-viewer-title"></span>
|
||||||
|
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
||||||
|
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
||||||
|
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="io-viewer-nav is-prev" data-step="-1" aria-label="이전 사진">‹</button>
|
||||||
|
<img class="io-viewer-img" id="io-viewer-img" alt="입고증 사진" />
|
||||||
|
<p class="io-viewer-heic" id="io-viewer-heic" hidden>HEIC 사진은 이 브라우저에서 미리 볼 수 없습니다 — [원본]으로 내려받으세요.</p>
|
||||||
|
<button type="button" class="io-viewer-nav is-next" data-step="1" aria-label="다음 사진">›</button>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
{% if perms.can_order and not order.cancelled_at %}
|
||||||
|
{# 발주 메일 — 열면 GET /inout/orders/{id}/mail 로 미리보기, [메일 발송]을 눌러야 보낸다(발주 담당 본인 Gmail) #}
|
||||||
|
{{ mail_dialog('io-mail', '발주 메일 보내기 · ' ~ order.order_no) }}
|
||||||
|
{% endif %}
|
||||||
|
{% if perms.can_receive and order.receipts %}
|
||||||
|
{# 입고 요청 메일(005) — 물류센터 입고 담당자에게 전산 등록 부탁(입고 담당 본인 Gmail). 입고 저장 뒤 ?rmail={입고 id} 면 바로 연다 #}
|
||||||
|
{% set open_r = order.receipts | selectattr('id', 'equalto', open_rmail) | list if open_rmail else [] %}
|
||||||
|
{% if open_r %}
|
||||||
|
{{ mail_dialog('io-rmail', '입고 요청 메일', '/inout/orders/' ~ order.id ~ '/receipts/' ~ open_r[0].id ~ '/mail',
|
||||||
|
'입고 요청 메일 · ' ~ ymd(open_r[0].receipt_date) ~ ' 입고 ' ~ n(open_r[0].total) ~ '개') }}
|
||||||
|
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="erp-card-block io-order-form" method="post" id="io-order-form"
|
||||||
|
action="{% if order %}/inout/orders/{{ order.id }}/edit{% else %}/inout/orders/new{% endif %}">
|
||||||
|
<div class="erp-card-block-head">
|
||||||
|
<h2>{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}</h2>
|
||||||
|
<span class="erp-muted">{% if from_catalog %}제품은 옵션 → 상품 정보의 단품에서 고릅니다(단가 함께){% else %}제품은 코드표의 단품에서 고릅니다{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
|
||||||
|
{% if not items_enabled %}<div class="io-error" role="alert">제품을 고를 목록이 없습니다 — 관리자가 옵션 → 상품 정보에서 단품을 불러오거나 코드표 DB(ITEMCODE_DB_URL)를 연결해야 합니다.</div>{% endif %}
|
||||||
|
|
||||||
|
<div class="erp-form-grid">
|
||||||
|
<label class="erp-field"><span>공장 *</span>
|
||||||
|
<select name="factory_id" required>
|
||||||
|
<option value="">공장 고르기</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if vals.factory_id|string == f.id|string %}selected{% endif %}>{{ f.name }}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
{% if not factories %}<span class="io-hint">공장이 없습니다 — 관리자가 옵션에서 먼저 공장을 추가해야 합니다.</span>{% endif %}
|
||||||
|
</label>
|
||||||
|
<label class="erp-field"><span>발주일 *</span><input type="date" name="order_date" value="{{ vals.order_date }}" required /></label>
|
||||||
|
<label class="erp-field"><span>입고 예정일</span><input type="date" name="due_date" value="{{ vals.due_date }}" /></label>
|
||||||
|
<label class="erp-field"><span>메모</span><input type="text" name="memo" value="{{ vals.memo }}" maxlength="500" placeholder="공장 전달 사항 등" /></label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table io-lines" id="io-lines">
|
||||||
|
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th><th>줄 메모</th><th class="io-col-del"></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for ln in lines %}
|
||||||
|
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
||||||
|
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}">
|
||||||
|
<td class="io-col-no"></td>
|
||||||
|
<td class="io-item-cell">
|
||||||
|
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||||
|
<input type="hidden" name="item_name" value="{{ ln.name }}" />
|
||||||
|
<input class="erp-input io-item-search" type="text" value="{{ ln.code }}{% if ln.name %} · {{ ln.name }}{% endif %}" autocomplete="off"
|
||||||
|
placeholder="코드 또는 이름" {% if received %}readonly title="입고된 제품은 바꿀 수 없습니다(수량은 바꿀 수 있음)"{% endif %} />
|
||||||
|
{% if received %}<div class="erp-row-sub">입고 {{ '{:,}'.format(received) }}개 — 제품은 그대로, 수량만 바꿀 수 있습니다</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" /></td>
|
||||||
|
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
|
||||||
|
<td class="io-col-money io-amount">-</td>
|
||||||
|
<td><input class="erp-input" type="text" name="line_memo" value="{{ ln.memo }}" maxlength="500" /></td>
|
||||||
|
<td class="io-col-del">{% if not received %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot><tr><td colspan="7">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-add-line">+ 제품 줄 추가</button>
|
||||||
|
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종 · 금액 <b id="io-total-amount">0</b>원<span id="io-total-noprice"></span></span>
|
||||||
|
</td></tr></tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template id="io-line-tpl">
|
||||||
|
<tr class="io-line">
|
||||||
|
<td class="io-col-no"></td>
|
||||||
|
<td class="io-item-cell">
|
||||||
|
<input type="hidden" name="item_code" value="" />
|
||||||
|
<input type="hidden" name="item_name" value="" />
|
||||||
|
<input class="erp-input io-item-search" type="text" value="" autocomplete="off" placeholder="코드 또는 이름" />
|
||||||
|
</td>
|
||||||
|
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" /></td>
|
||||||
|
<td class="io-col-money io-price">-</td>
|
||||||
|
<td class="io-col-money io-amount">-</td>
|
||||||
|
<td><input class="erp-input" type="text" name="line_memo" value="" maxlength="500" /></td>
|
||||||
|
<td class="io-col-del"><button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button></td>
|
||||||
|
</tr>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div class="io-form-actions">
|
||||||
|
<a class="erp-btn erp-btn-outline" href="{% if order %}/inout/orders/{{ order.id }}{% else %}/inout/{% endif %}">취소</a>
|
||||||
|
<button type="submit" class="erp-btn erp-btn-primary">{% if order %}고친 내용 저장{% else %}발주서 저장{% endif %}</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
{% from "inout/_macros.html" import due, n, ymd %}
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019g" />{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<section class="io">
|
||||||
|
{% include "inout/_nav.html" %}
|
||||||
|
|
||||||
|
<form class="io-filter" method="get" action="/inout/pending">
|
||||||
|
<select class="erp-select" name="factory" aria-label="공장" onchange="this.form.submit()">
|
||||||
|
<option value="">전체 공장</option>
|
||||||
|
{% for f in factories %}<option value="{{ f.id }}" {% if filters.factory == f.id %}selected{% endif %}>{{ f.name }}{% if not f.is_active %} (사용 안 함){% endif %}</option>{% endfor %}
|
||||||
|
</select>
|
||||||
|
<input class="erp-input io-search" type="search" name="q" value="{{ filters.q }}" placeholder="제품 코드·제품 이름·발주번호" />
|
||||||
|
<button type="submit" class="erp-btn erp-btn-outline">찾기</button>
|
||||||
|
<span class="io-nav-gap"></span>
|
||||||
|
<span class="erp-muted">진행 중인 발주(종결·취소 제외)의 남은 수량</span>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="io-kpis">
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 수량</div><div class="erp-summary-value">{{ n(total_remaining) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 제품</div><div class="erp-summary-value">{{ n(items|length) }}종</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini"><div class="erp-summary-label">미입고 발주 줄</div><div class="erp-summary-value">{{ n(rows|length) }}</div></div>
|
||||||
|
<div class="erp-summary-card erp-summary-card--mini{% if over %} io-kpi-over{% endif %}"><div class="erp-summary-label">초과 입고</div><div class="erp-summary-value">{{ n(over|length) }}건</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>제품별 미입고 합계</h2><span class="erp-muted">여러 발주에 걸친 남은 수량을 제품마다 더한 값</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>제품 코드</th><th>제품</th><th class="io-num">미입고</th><th class="io-num">발주 건수</th><th>가장 이른 입고 예정일</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for it in items %}
|
||||||
|
<tr>
|
||||||
|
<td class="io-code">{{ it.item_code }}</td><td>{{ it.item_name }}</td>
|
||||||
|
<td class="io-num io-remaining">{{ n(it.remaining) }}</td><td class="io-num">{{ it.orders }}</td>
|
||||||
|
<td>{{ due(it.earliest_due, today, True) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr><td colspan="5" class="erp-empty">미입고된 제품이 없습니다. 모두 들어왔습니다.</td></tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if rows %}
|
||||||
|
<div class="erp-card-block io-block">
|
||||||
|
<div class="erp-card-block-head"><h2>발주별 미입고</h2><span class="erp-muted">입고 예정일이 이른 순 — 지난 것은 빨강</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>입고 예정일</th><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th>
|
||||||
|
<th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">미입고</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in rows %}
|
||||||
|
<tr class="io-row-link{% if r.due_date and r.due_date < today %} is-late{% endif %}" data-href="/inout/orders/{{ r.order_id }}">
|
||||||
|
<td>{{ due(r.due_date, today, True) }}</td>
|
||||||
|
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a><div class="erp-row-sub">발주 {{ ymd(r.order_date) }}</div></td>
|
||||||
|
<td>{{ r.factory_name }}</td><td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
|
||||||
|
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td>
|
||||||
|
<td class="io-num io-remaining">{{ n(r.remaining) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if over %}
|
||||||
|
<div class="erp-card-block io-block io-block-over">
|
||||||
|
<div class="erp-card-block-head"><h2>초과 입고</h2><span class="erp-muted">발주보다 많이 들어온 제품 — 공장과 확인이 필요합니다</span></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="erp-table io-table">
|
||||||
|
<thead><tr><th>발주번호</th><th>공장</th><th>제품 코드</th><th>제품</th><th class="io-num">발주</th><th class="io-num">입고</th><th class="io-num">초과</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in over %}
|
||||||
|
<tr class="io-row-link" data-href="/inout/orders/{{ r.order_id }}">
|
||||||
|
<td><a href="/inout/orders/{{ r.order_id }}" class="io-order-no">{{ r.order_no }}</a></td><td>{{ r.factory_name }}</td>
|
||||||
|
<td class="io-code">{{ r.item_code }}</td><td>{{ r.item_name }}</td>
|
||||||
|
<td class="io-num">{{ n(r.qty) }}</td><td class="io-num">{{ n(r.received) }}</td><td class="io-num io-over">+{{ n(r.over) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
|
{% block scripts %}<script src="/static/inout.js?v=20261019c" defer></script>{% endblock %}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# [말레이시아재고] 말레이시아 창고 재고관리 — `app/modules/malaysia/`, `malaysia_stock_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 같은 폴더 `README.md`.
|
||||||
|
> 정적 파일: `app/static/malaysia.js`, `malaysia_rack.js`, `malaysia_rack_view.js`. 템플릿: `templates/`.
|
||||||
|
> 상품은 `itemcode_db` 읽기 전용(`itemcode.py`). 세트 BOM 이 "누락"이면 `itemcode_ro` 의 `set_components` SELECT 권한부터 점검.
|
||||||
|
|
||||||
|
- 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트 → 낱개 자동 분해), 현재고 현황.
|
||||||
|
- 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`).
|
||||||
|
- 권한키 `malaysia`.
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# [공지] 긴급 공지 모듈 — `app/modules/notice/`, `project_db`(마이그레이션 024 `urgent_notice*`)
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/NOTICE_MODULE.md`.
|
||||||
|
> 정적 파일: `app/static/erp-notice.js`, `erp-notice.css`, `erp-notice-admin.js`.
|
||||||
|
|
||||||
|
- 수퍼관리자만 작성(`/notice/`, 진입 = ERP 왼쪽 아래 · Project ⚙ 옵션).
|
||||||
|
- 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람.
|
||||||
|
- ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에
|
||||||
|
[확인] 누를 때까지 표시(Esc·바깥 클릭 무시), 확인 기록.
|
||||||
|
- 연결 풀은 `ProjectStore.pool` 공유(→ Project 모듈 DB 변경 시 영향 확인), 새 환경변수 없음.
|
||||||
|
- PC 알림 프로그램은 아직 미지원.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""긴급 공지 — ERP 전체 화면 가운데에 띄우는 공지(2026-10-12).
|
||||||
|
|
||||||
|
- 라우터: `router.py` (prefix=/notice) — 만들기·고치기는 수퍼관리자만, 받기·[확인]은 로그인 사용자 누구나
|
||||||
|
- 저장소: `db.py` (project_db 마이그레이션 024 의 urgent_notice* 표 — 프로젝트 저장소의 연결 풀을 같이 쓴다)
|
||||||
|
- 검증: `store.py`
|
||||||
|
- 화면: 관리 `templates/notice/admin.html` + `static/erp-notice-admin.js`, 표시 `static/erp-notice.js`(erp_base.html 공용)
|
||||||
|
상세는 docs/NOTICE_MODULE.md.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .router import router
|
||||||
|
|
||||||
|
__all__ = ["router", "build_notice_store"]
|
||||||
|
|
||||||
|
|
||||||
|
def build_notice_store(project_store: Any) -> Any:
|
||||||
|
"""프로젝트 저장소(PROJECT_DB_URL)가 있으면 그 연결 풀로 NoticeStore, 없으면 None(공지 API 는 503)."""
|
||||||
|
if project_store is None:
|
||||||
|
return None
|
||||||
|
from .db import NoticeStore # noqa: WPS433
|
||||||
|
|
||||||
|
return NoticeStore(project_store.pool)
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
"""긴급 공지 저장소 — project_db(마이그레이션 024)의 urgent_notice* 표. 연결 풀은 프로젝트 저장소와 같이 쓴다."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from psycopg import errors as psycopg_errors
|
||||||
|
|
||||||
|
from app.modules.project import store as pj_store
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
|
||||||
|
def _iso(v: Any) -> str:
|
||||||
|
return v.astimezone(KST).isoformat(timespec="minutes") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _version(v: Any) -> str:
|
||||||
|
"""공지 내용 버전 = updated_at(마이크로초까지, UTC) — 고치기·취소 때마다 바뀐다. 받는 사람 화면이 바뀐 내용을 다시 그리고,
|
||||||
|
[확인]이 어느 내용을 읽고 누른 것인지 서버가 가린다(2026-10-15 검토 F07)."""
|
||||||
|
return v.astimezone(timezone.utc).strftime("%Y%m%d%H%M%S%f") if isinstance(v, datetime) else ""
|
||||||
|
|
||||||
|
|
||||||
|
class NoticeStore:
|
||||||
|
def __init__(self, pool: Any) -> None:
|
||||||
|
self._pool = pool
|
||||||
|
|
||||||
|
def _conn(self) -> Any:
|
||||||
|
return self._pool.connection()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _run(fn: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except psycopg_errors.UndefinedTable:
|
||||||
|
raise store.NoticeMigrationNeeded()
|
||||||
|
|
||||||
|
# ── 읽기 ────────────────────────────────────────────────
|
||||||
|
@staticmethod
|
||||||
|
def _row(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": int(r["id"]), "title": r["title"], "body_html": r["body_html"],
|
||||||
|
"show_at": _iso(r["show_at"]), "to_all": bool(r["to_all"]),
|
||||||
|
"created_by": r["created_by"], "created_at": _iso(r["created_at"]),
|
||||||
|
"updated_by": r.get("updated_by") or "", "updated_at": _iso(r.get("updated_at")),
|
||||||
|
"version": _version(r.get("updated_at")),
|
||||||
|
"cancelled_at": _iso(r.get("cancelled_at")), "cancelled_by": r.get("cancelled_by") or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_notices(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
|
"""관리 화면 — 최근 것부터. 받는 사람·확인한 사람 목록을 함께."""
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM urgent_notices ORDER BY show_at DESC, id DESC LIMIT %s",
|
||||||
|
(int(limit),)).fetchall()
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
targets: dict[int, list[str]] = {i: [] for i in ids}
|
||||||
|
acks: dict[int, dict[str, str]] = {i: {} for i in ids}
|
||||||
|
if ids:
|
||||||
|
for t in conn.execute("SELECT notice_id, user_email FROM urgent_notice_targets "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY user_email", (ids,)).fetchall():
|
||||||
|
targets[int(t["notice_id"])].append(t["user_email"])
|
||||||
|
for a in conn.execute("SELECT notice_id, user_email, acked_at FROM urgent_notice_acks "
|
||||||
|
"WHERE notice_id = ANY(%s) ORDER BY acked_at", (ids,)).fetchall():
|
||||||
|
acks[int(a["notice_id"])][a["user_email"]] = _iso(a["acked_at"])
|
||||||
|
return [{**self._row(r), "targets": targets[int(r["id"])], "acks": acks[int(r["id"])]} for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def pending_for(self, *, email: str, now: datetime | None = None) -> list[dict[str, Any]]:
|
||||||
|
"""이 사람이 지금 봐야 할 공지 — 취소 안 됨·띄울 시각이 지남·받는 사람(전체 또는 지정)·아직 [확인] 안 함. 오래된 것부터."""
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT n.* FROM urgent_notices n "
|
||||||
|
"WHERE n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||||
|
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||||
|
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||||
|
" AND NOT EXISTS (SELECT 1 FROM urgent_notice_acks a WHERE a.notice_id = n.id AND a.user_email = %s) "
|
||||||
|
"ORDER BY n.show_at ASC, n.id ASC LIMIT 20",
|
||||||
|
(now or datetime.now(KST), em, em),
|
||||||
|
).fetchall()
|
||||||
|
return [self._row(r) for r in rows]
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def get_notice(self, *, notice_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT * FROM urgent_notices WHERE id = %s", (notice_id,)).fetchone()
|
||||||
|
if r is None:
|
||||||
|
return None
|
||||||
|
t = [x["user_email"] for x in conn.execute(
|
||||||
|
"SELECT user_email FROM urgent_notice_targets WHERE notice_id = %s ORDER BY user_email",
|
||||||
|
(notice_id,)).fetchall()]
|
||||||
|
return {**self._row(r), "targets": t}
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def is_recipient(self, *, notice: dict[str, Any], email: str) -> bool:
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
return bool(notice["to_all"]) or em in notice.get("targets", [])
|
||||||
|
|
||||||
|
# ── 쓰기 ────────────────────────────────────────────────
|
||||||
|
def _link_images(self, conn: Any, notice_id: int, body: str, by: str) -> None:
|
||||||
|
"""본문에 든 이미지를 이 공지에 묶는다 — 내가 올린, 아직 어느 공지에도 안 묶인 이미지만(남의 공지 이미지 가로채기 방지)."""
|
||||||
|
ids = store.image_ids_in(body)
|
||||||
|
if ids:
|
||||||
|
conn.execute("UPDATE urgent_notice_images SET notice_id = %s "
|
||||||
|
"WHERE id = ANY(%s) AND notice_id IS NULL AND uploaded_by = %s", (notice_id, ids, by))
|
||||||
|
# 하루 넘게 어느 공지에도 안 묶인 이미지(올렸다가 저장 안 함)는 정리
|
||||||
|
conn.execute("DELETE FROM urgent_notice_images WHERE notice_id IS NULL AND created_at < now() - interval '1 day'")
|
||||||
|
|
||||||
|
def create_notice(self, *, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any, by: str) -> dict[str, Any]:
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
nid = int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notices (title, body_html, show_at, to_all, created_by, updated_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", (ttl, html, when, all_, who, who),
|
||||||
|
).fetchone()["id"])
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (nid, em))
|
||||||
|
self._link_images(conn, nid, html, who)
|
||||||
|
return nid
|
||||||
|
return self.get_notice(notice_id=self._run(run)) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def update_notice(self, *, notice_id: int, title: Any, body: Any, show_at: Any, to_all: Any, targets: Any,
|
||||||
|
by: str, reshow: bool = False) -> dict[str, Any]:
|
||||||
|
"""고치기 — 받는 사람·시각·내용 전부. reshow=True 면 이미 [확인]한 사람에게도 다시 띄운다(확인 기록 지움)."""
|
||||||
|
ttl = store.validate_title(title)
|
||||||
|
html = store.sanitize_body(body)
|
||||||
|
when = store.parse_show_at(show_at)
|
||||||
|
all_, emails = store.validate_targets(to_all, targets)
|
||||||
|
who = pj_store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute("UPDATE urgent_notices SET title=%s, body_html=%s, show_at=%s, to_all=%s, "
|
||||||
|
"updated_by=%s, updated_at=now() WHERE id=%s RETURNING id",
|
||||||
|
(ttl, html, when, all_, who, notice_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
conn.execute("DELETE FROM urgent_notice_targets WHERE notice_id = %s", (notice_id,))
|
||||||
|
for em in emails:
|
||||||
|
conn.execute("INSERT INTO urgent_notice_targets (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING", (notice_id, em))
|
||||||
|
if reshow:
|
||||||
|
conn.execute("DELETE FROM urgent_notice_acks WHERE notice_id = %s", (notice_id,))
|
||||||
|
self._link_images(conn, notice_id, html, who)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def cancel_notice(self, *, notice_id: int, by: str, cancel: bool = True) -> dict[str, Any]:
|
||||||
|
"""취소(더 띄우지 않음) · 취소 되돌리기. 기록은 남는다."""
|
||||||
|
def run() -> None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"UPDATE urgent_notices SET cancelled_at = CASE WHEN %s THEN now() ELSE NULL END, "
|
||||||
|
"cancelled_by = CASE WHEN %s THEN %s ELSE '' END, updated_at = now() WHERE id = %s RETURNING id",
|
||||||
|
(cancel, cancel, pj_store.norm_str(by, lower=True), notice_id),
|
||||||
|
).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(notice_id)
|
||||||
|
self._run(run)
|
||||||
|
return self.get_notice(notice_id=notice_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def ack(self, *, notice_id: int, email: str, version: str | None = None, now: datetime | None = None) -> str:
|
||||||
|
"""[확인] — 결과: "acked"(처음) · "already"(이미 확인 — 여러 번 눌러도 한 번) · "stale"(그 사이 내용이 바뀜 — 읽은
|
||||||
|
version 이 지금과 다름) · "denied"(받는 사람이 아님·띄울 시각 전·취소·없음).
|
||||||
|
|
||||||
|
받는 사람·표시 시각·취소 확인과 기록이 **한 트랜잭션**(2026-10-15 검토 F08): 공지 행을 FOR SHARE 로 잠그고 조건을 본 뒤
|
||||||
|
기록한다 — 동시에 취소·고치기가 들어오면 그 쪽이 먼저 끝나거나(그러면 바뀐 행으로 다시 판정) 이 기록 뒤로 기다린다.
|
||||||
|
version 이 없으면(예전 화면) 내용 확인은 건너뛴다."""
|
||||||
|
em = pj_store.norm_str(email, lower=True)
|
||||||
|
|
||||||
|
def run() -> str:
|
||||||
|
with self._conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
n = conn.execute(
|
||||||
|
"SELECT n.id, n.updated_at FROM urgent_notices n "
|
||||||
|
"WHERE n.id = %s AND n.cancelled_at IS NULL AND n.show_at <= %s "
|
||||||
|
" AND (n.to_all OR EXISTS (SELECT 1 FROM urgent_notice_targets t "
|
||||||
|
" WHERE t.notice_id = n.id AND t.user_email = %s)) "
|
||||||
|
"FOR SHARE OF n",
|
||||||
|
(notice_id, now or datetime.now(KST), em),
|
||||||
|
).fetchone()
|
||||||
|
if n is None:
|
||||||
|
return "denied"
|
||||||
|
done = conn.execute("SELECT 1 FROM urgent_notice_acks WHERE notice_id = %s AND user_email = %s",
|
||||||
|
(notice_id, em)).fetchone()
|
||||||
|
if done is not None:
|
||||||
|
return "already"
|
||||||
|
if version and version != _version(n["updated_at"]):
|
||||||
|
return "stale"
|
||||||
|
r = conn.execute("INSERT INTO urgent_notice_acks (notice_id, user_email) VALUES (%s,%s) "
|
||||||
|
"ON CONFLICT DO NOTHING RETURNING notice_id", (notice_id, em)).fetchone()
|
||||||
|
return "acked" if r is not None else "already"
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
# ── 이미지 ──────────────────────────────────────────────
|
||||||
|
def add_image(self, *, data: bytes, filename: str, by: str) -> dict[str, Any]:
|
||||||
|
ctype = store.sniff_image(data)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return int(conn.execute(
|
||||||
|
"INSERT INTO urgent_notice_images (filename, content_type, size_bytes, data, uploaded_by) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s) RETURNING id",
|
||||||
|
(pj_store.norm_str(filename)[:200], ctype, len(data), data, pj_store.norm_str(by, lower=True)),
|
||||||
|
).fetchone()["id"])
|
||||||
|
iid = self._run(run)
|
||||||
|
return {"id": iid, "url": f"/notice/images/{iid}", "content_type": ctype}
|
||||||
|
|
||||||
|
def get_image(self, *, image_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._conn() as conn:
|
||||||
|
r = conn.execute("SELECT id, notice_id, content_type, data, uploaded_by FROM urgent_notice_images "
|
||||||
|
"WHERE id = %s", (image_id,)).fetchone()
|
||||||
|
return dict(r) if r else None
|
||||||
|
return self._run(run)
|
||||||
|
|
||||||
|
def enabled(self) -> bool:
|
||||||
|
try:
|
||||||
|
with self._conn() as conn:
|
||||||
|
return bool(conn.execute("SELECT to_regclass('public.urgent_notices') AS r").fetchone()["r"])
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return False
|
||||||
|
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
"""긴급 공지 라우터(/notice) — ERP 전체 화면 가운데 공지.
|
||||||
|
|
||||||
|
- 만들기·고치기·취소·이미지 올리기·확인 현황: 수퍼관리자(app.store.SUPER_ADMIN_EMAIL)만.
|
||||||
|
- 받기(GET /notice/api/pending)·[확인]: 로그인한 등록 사용자 누구나 — 모듈 권한과 무관(ERP 전체 공지).
|
||||||
|
- 저장: project_db 024(urgent_notice*). PROJECT_DB_URL 이 없거나 024 미적용이면 503(화면 스크립트는 조용히 멈춘다).
|
||||||
|
- 핸들러는 동기 DB 라 def(프로젝트 라우터와 같은 이유).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, File, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||||
|
|
||||||
|
from . import store
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/notice", tags=["notice"])
|
||||||
|
|
||||||
|
_MIGRATION_MSG = "긴급 공지 기능이 아직 준비되지 않았습니다(project_db 마이그레이션 024 필요)."
|
||||||
|
|
||||||
|
|
||||||
|
def _user(request: Request) -> dict[str, Any]:
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
|
||||||
|
user = get_current_user_record(request)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _is_super(user: dict[str, Any]) -> bool:
|
||||||
|
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
|
||||||
|
|
||||||
|
return str(user.get("email") or "").strip().lower() == SUPER_ADMIN_EMAIL
|
||||||
|
|
||||||
|
|
||||||
|
def _super(request: Request) -> dict[str, Any]:
|
||||||
|
user = _user(request)
|
||||||
|
if not _is_super(user):
|
||||||
|
raise HTTPException(status_code=403, detail="긴급 공지는 수퍼관리자만 만들 수 있습니다.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _store(request: Request) -> Any:
|
||||||
|
st = getattr(request.app.state, "notice_store", None)
|
||||||
|
if st is None:
|
||||||
|
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||||
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _call(fn: Any, **kw: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn(**kw)
|
||||||
|
except store.NoticeMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=_MIGRATION_MSG)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
except KeyError:
|
||||||
|
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def _public(n: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""받는 사람 화면에 보내는 값 — 받는 사람 목록·확인 현황은 빼고."""
|
||||||
|
return {k: n.get(k, "") for k in ("id", "title", "body_html", "show_at", "created_by", "version")}
|
||||||
|
|
||||||
|
|
||||||
|
# ── 화면 ─────────────────────────────────────────────────────
|
||||||
|
@router.get("/", response_class=HTMLResponse)
|
||||||
|
def notice_admin_page(request: Request) -> HTMLResponse:
|
||||||
|
"""긴급 공지 관리 — 수퍼관리자만. 목록(예약·표시 중·취소)·확인 현황·새 공지."""
|
||||||
|
from app.main import build_erp_nav, render_template, user_store # noqa: WPS433
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
user = _super(request)
|
||||||
|
st = getattr(request.app.state, "notice_store", None)
|
||||||
|
enabled = bool(st) and st.enabled()
|
||||||
|
# 받는 사람 후보 = 등록 사용자 전원 — 프로젝트 멤버 고르기와 같은 모양(아이콘 + 이름)으로 그린다(project.js memberPickHtml)
|
||||||
|
people = sorted(
|
||||||
|
({"email": u["email"], "id": u["email"].split("@")[0], "name": u.get("name") or u["email"].split("@")[0],
|
||||||
|
"avatar": u.get("picture") or ""} for u in user_store.list_all()),
|
||||||
|
key=lambda p: p["id"],
|
||||||
|
)
|
||||||
|
return render_template(request, "notice/admin.html", {
|
||||||
|
"user": user, "is_admin": is_admin(user),
|
||||||
|
"nav_items": build_erp_nav(user, active=""),
|
||||||
|
"page_title": "긴급 공지", "page_subtitle": "정한 시각에 받는 사람 화면 가운데에 띄웁니다([확인] 전까지)",
|
||||||
|
"enabled": enabled, "people": people,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 받는 사람 ────────────────────────────────────────────────
|
||||||
|
@router.get("/api/pending")
|
||||||
|
def api_pending(request: Request) -> JSONResponse:
|
||||||
|
"""지금 내가 봐야 할 공지(띄울 시각이 지났고 아직 [확인] 안 한 것, 오래된 것부터)."""
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
rows = _call(st.pending_for, email=user["email"])
|
||||||
|
return JSONResponse({"notices": [_public(n) for n in rows]})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/{notice_id}/ack")
|
||||||
|
def api_ack(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""[확인] — 받는 사람이고 띄울 시각이 지난, 취소 안 된 공지만(검증과 기록을 저장소가 한 트랜잭션에서, 검토 F08).
|
||||||
|
여러 번 눌러도 한 번 기록. payload.version = 화면에 띄운 내용의 버전 — 그 사이 고쳐졌으면 409(바뀐 내용을 다시 읽게, F07)."""
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
version = str((payload or {}).get("version") or "").strip() or None
|
||||||
|
result = _call(st.ack, notice_id=notice_id, email=user["email"], version=version)
|
||||||
|
if result == "denied":
|
||||||
|
raise HTTPException(status_code=404, detail="공지를 찾을 수 없습니다.")
|
||||||
|
if result == "stale":
|
||||||
|
raise HTTPException(status_code=409, detail="공지 내용이 수정되었습니다. 바뀐 내용을 확인한 뒤 다시 [확인]을 눌러 주세요.")
|
||||||
|
return JSONResponse({"ok": True, "result": result})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/images/{image_id}")
|
||||||
|
def notice_image(request: Request, image_id: int) -> Response:
|
||||||
|
"""공지 본문 이미지 — 수퍼관리자, 또는 그 공지를 받는 사람(띄울 시각이 지난 공지)만."""
|
||||||
|
from datetime import datetime # noqa: WPS433
|
||||||
|
|
||||||
|
from app.timezone import KST # noqa: WPS433
|
||||||
|
|
||||||
|
user = _user(request)
|
||||||
|
st = _store(request)
|
||||||
|
img = _call(st.get_image, image_id=image_id)
|
||||||
|
if img is None:
|
||||||
|
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||||
|
if not _is_super(user):
|
||||||
|
n = _call(st.get_notice, notice_id=int(img["notice_id"])) if img["notice_id"] else None
|
||||||
|
if (n is None or n["cancelled_at"] or not st.is_recipient(notice=n, email=user["email"])
|
||||||
|
or datetime.fromisoformat(n["show_at"]) > datetime.now(KST)):
|
||||||
|
raise HTTPException(status_code=404, detail="이미지를 찾을 수 없습니다.")
|
||||||
|
return Response(content=bytes(img["data"]), media_type=img["content_type"], headers={
|
||||||
|
"X-Content-Type-Options": "nosniff", "Cache-Control": "private, max-age=3600",
|
||||||
|
"Content-Security-Policy": "default-src 'none'; img-src 'self'; sandbox",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 수퍼관리자 ───────────────────────────────────────────────
|
||||||
|
@router.get("/api/notices")
|
||||||
|
def api_list(request: Request) -> JSONResponse:
|
||||||
|
_super(request)
|
||||||
|
st = _store(request)
|
||||||
|
return JSONResponse({"notices": _call(st.list_notices)})
|
||||||
|
|
||||||
|
|
||||||
|
def _fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"title": payload.get("title"), "body": payload.get("body_html") or "",
|
||||||
|
"show_at": payload.get("show_at"), "to_all": payload.get("to_all", True),
|
||||||
|
"targets": payload.get("targets") or []}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/notices")
|
||||||
|
def api_create(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.create_notice, **_fields(payload), by=user["email"])
|
||||||
|
return JSONResponse({"notice": n}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/notices/{notice_id}")
|
||||||
|
def api_update(request: Request, notice_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""고치기 — reshow=true 면 이미 [확인]한 사람에게도 다시 띄운다."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.update_notice, notice_id=notice_id, **_fields(payload), by=user["email"],
|
||||||
|
reshow=payload.get("reshow") is True)
|
||||||
|
return JSONResponse({"notice": n})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/notices/{notice_id}/cancel")
|
||||||
|
def api_cancel(request: Request, notice_id: int, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""취소(더 띄우지 않음) {cancel: true} · 되돌리기 {cancel: false}."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
n = _call(st.cancel_notice, notice_id=notice_id, by=user["email"], cancel=payload.get("cancel", True) is not False)
|
||||||
|
return JSONResponse({"notice": n})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/images")
|
||||||
|
def api_upload_image(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""본문 이미지 올리기 — 저장(공지 만들기·고치기) 때 본문에 든 것만 그 공지에 묶인다."""
|
||||||
|
user = _super(request)
|
||||||
|
st = _store(request)
|
||||||
|
data = file.file.read(store.IMAGE_MAX_BYTES + 1)
|
||||||
|
img = _call(st.add_image, data=data, filename=file.filename or "image", by=user["email"])
|
||||||
|
return JSONResponse({"image": img}, status_code=201)
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""긴급 공지 — 순수 검증(DB 없음). 저장은 db.py, 화면·권한은 router.py."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.modules.project import store as pj_store
|
||||||
|
from app.timezone import KST
|
||||||
|
|
||||||
|
TITLE_MAX = 200
|
||||||
|
BODY_MAX = 100_000 # 정리한 HTML 기준(이미지는 주소만 들어간다)
|
||||||
|
IMAGE_MAX_BYTES = 10 * 1024 * 1024
|
||||||
|
TARGETS_MAX = 500
|
||||||
|
|
||||||
|
# 이미지 형식은 올린 쪽이 정한 Content-Type 이 아니라 파일 앞 바이트로 정한다(svg·html 은 받지 않는다).
|
||||||
|
_MAGIC: tuple[tuple[bytes, str], ...] = (
|
||||||
|
(b"\x89PNG\r\n\x1a\n", "image/png"),
|
||||||
|
(b"\xff\xd8\xff", "image/jpeg"),
|
||||||
|
(b"GIF87a", "image/gif"),
|
||||||
|
(b"GIF89a", "image/gif"),
|
||||||
|
)
|
||||||
|
_IMG_SRC_OK = re.compile(r"^/notice/images/(\d+)$")
|
||||||
|
_IMG_TAG = re.compile(r"<img\b[^>]*>", re.IGNORECASE)
|
||||||
|
_SRC_ATTR = re.compile(r"""\bsrc\s*=\s*"([^"]*)\"""", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
class NoticeMigrationNeeded(Exception):
|
||||||
|
"""project_db 024 미적용."""
|
||||||
|
|
||||||
|
|
||||||
|
def validate_title(v: Any) -> str:
|
||||||
|
t = pj_store.norm_str(v)
|
||||||
|
if not t:
|
||||||
|
raise ValueError("공지 제목을 입력하세요.")
|
||||||
|
if len(t) > TITLE_MAX:
|
||||||
|
raise ValueError(f"제목은 {TITLE_MAX}자 이하로 입력하세요.")
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_body(html: Any) -> str:
|
||||||
|
"""작업 설명란과 같은 허용 목록으로 정리한 뒤, 이미지는 공지 이미지 주소(/notice/images/{id})만 남긴다
|
||||||
|
(외부 주소·data: 이미지는 뺀다 — 받는 사람 화면에서 다른 곳으로 요청이 나가지 않게)."""
|
||||||
|
out = pj_store.sanitize_description_html(str(html or ""))
|
||||||
|
|
||||||
|
def keep(m: re.Match[str]) -> str:
|
||||||
|
src = _SRC_ATTR.search(m.group(0))
|
||||||
|
return m.group(0) if src and _IMG_SRC_OK.match(src.group(1)) else ""
|
||||||
|
out = _IMG_TAG.sub(keep, out)
|
||||||
|
if len(out) > BODY_MAX:
|
||||||
|
raise ValueError("내용이 너무 깁니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def image_ids_in(html: str) -> list[int]:
|
||||||
|
"""본문에 들어 있는 공지 이미지 id(순서대로, 중복 없이)."""
|
||||||
|
ids: list[int] = []
|
||||||
|
for tag in _IMG_TAG.findall(html or ""):
|
||||||
|
src = _SRC_ATTR.search(tag)
|
||||||
|
m = _IMG_SRC_OK.match(src.group(1)) if src else None
|
||||||
|
if m and int(m.group(1)) not in ids:
|
||||||
|
ids.append(int(m.group(1)))
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
def parse_show_at(v: Any, *, now: datetime | None = None) -> datetime:
|
||||||
|
"""띄울 시각 — 'YYYY-MM-DDTHH:MM'(화면 입력, 한국시간) 또는 시간대가 붙은 ISO. 비우면 지금."""
|
||||||
|
s = pj_store.norm_str(v)
|
||||||
|
if not s:
|
||||||
|
return now or datetime.now(KST)
|
||||||
|
try:
|
||||||
|
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||||
|
if d.tzinfo is None:
|
||||||
|
d = d.replace(tzinfo=KST)
|
||||||
|
if not 2000 <= d.year <= 2100:
|
||||||
|
raise ValueError("띄울 시각이 올바르지 않습니다.")
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def validate_targets(to_all: Any, targets: Any) -> tuple[bool, list[str]]:
|
||||||
|
"""(전체 여부, 받는 사람 이메일). 전체가 아니면 한 명 이상."""
|
||||||
|
if to_all is True or to_all in ("1", "true", "on"):
|
||||||
|
return True, []
|
||||||
|
emails = pj_store.normalize_emails(targets if isinstance(targets, (list, tuple)) else [])
|
||||||
|
if not emails:
|
||||||
|
raise ValueError("받는 사람을 한 명 이상 고르거나 '전체'를 고르세요.")
|
||||||
|
if len(emails) > TARGETS_MAX:
|
||||||
|
raise ValueError(f"받는 사람은 {TARGETS_MAX}명까지 고를 수 있습니다.")
|
||||||
|
return False, emails
|
||||||
|
|
||||||
|
|
||||||
|
def sniff_image(data: bytes) -> str:
|
||||||
|
"""파일 앞 바이트로 이미지 형식 — png·jpeg·gif·webp 만. 아니면 ValueError."""
|
||||||
|
if not data:
|
||||||
|
raise ValueError("빈 파일입니다.")
|
||||||
|
if len(data) > IMAGE_MAX_BYTES:
|
||||||
|
raise ValueError("이미지는 10MB 이하만 올릴 수 있습니다.")
|
||||||
|
for magic, ctype in _MAGIC:
|
||||||
|
if data.startswith(magic):
|
||||||
|
return ctype
|
||||||
|
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||||
|
return "image/webp"
|
||||||
|
raise ValueError("이미지(png·jpg·gif·webp)만 올릴 수 있습니다.")
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}
|
||||||
|
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||||
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
|
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{% if not enabled %}
|
||||||
|
<div class="ntc-card">
|
||||||
|
<h2>긴급 공지 준비 필요</h2>
|
||||||
|
<p>project_db 마이그레이션 024(<code>scripts/sql/project_db_024_urgent_notices.sql</code>)를 적용하면 사용할 수 있습니다.</p>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="ntc-wrap" id="ntc-root">
|
||||||
|
<section class="ntc-card" aria-labelledby="ntc-form-title">
|
||||||
|
<h2 id="ntc-form-title">새 긴급 공지</h2>
|
||||||
|
<input type="hidden" id="ntc-id" value="" />
|
||||||
|
<label class="ntc-field">제목
|
||||||
|
<input type="text" id="ntc-title" maxlength="200" placeholder="예: 오늘 18시 서버 점검" autocomplete="off" />
|
||||||
|
</label>
|
||||||
|
{# 내용 — 작업 설명란과 같은 편집기(서식 도구 전체·이미지 붙여넣기/버튼·크기 조절·링크·체크리스트) #}
|
||||||
|
<div class="ntc-field pj-desc-block ntc-desc">
|
||||||
|
<div class="pj-desc-toolbar"><span>내용</span><span class="pj-muted-sm" id="ntc-hint"></span></div>
|
||||||
|
{% with fmtbar_id = "ntc-fmtbar", img_input_id = "ntc-img-input" %}{% include "project/_desc_fmtbar.html" %}{% endwith %}
|
||||||
|
<div class="pj-desc-wrap">
|
||||||
|
<div class="pj-desc-editor" id="ntc-body" contenteditable="true" role="textbox" aria-multiline="true" aria-label="공지 내용"
|
||||||
|
data-placeholder="공지 내용을 쓰세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{# 띄울 날짜 — 프로젝트와 같은 날짜 팝업(공휴일·오늘·지우기), 시각은 옆 칸. 둘 다 비우면 바로 #}
|
||||||
|
<div class="ntc-field">띄울 시각 <small class="ntc-sub">한국시간 · 날짜를 비우면 바로</small>
|
||||||
|
<div class="ntc-when">
|
||||||
|
<input type="date" id="ntc-date" />
|
||||||
|
<input type="time" id="ntc-time" class="ntc-time" step="300" aria-label="띄울 시각" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ntc-field">받는 사람
|
||||||
|
<div class="ntc-targets">
|
||||||
|
<div class="ntc-to">
|
||||||
|
<label><input type="radio" name="ntc-to" value="all" checked /> 전체(로그인하는 모든 사람)</label>
|
||||||
|
<label><input type="radio" name="ntc-to" value="some" /> 고른 사람만</label>
|
||||||
|
</div>
|
||||||
|
{# 프로젝트 멤버 고르기와 같은 모양 — 아이콘 + 이름 + 체크 #}
|
||||||
|
<div class="pj-member-picker ntc-people" id="ntc-people" hidden></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="ntc-field ntc-inline" id="ntc-reshow-row" hidden>
|
||||||
|
<input type="checkbox" id="ntc-reshow" /> 이미 [확인]한 사람에게도 다시 띄우기
|
||||||
|
</label>
|
||||||
|
<div class="ntc-actions">
|
||||||
|
<button type="button" class="pj-btn" id="ntc-reset">새로 쓰기</button>
|
||||||
|
<button type="button" class="pj-btn" id="ntc-preview">미리 보기</button>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary" id="ntc-save">공지 만들기</button>
|
||||||
|
</div>
|
||||||
|
<p class="ntc-msg" id="ntc-msg" role="alert" hidden></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="ntc-card" aria-labelledby="ntc-list-title">
|
||||||
|
<h2 id="ntc-list-title">공지 목록</h2>
|
||||||
|
<div class="ntc-list" id="ntc-list">불러오는 중…</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||||
|
<script src="/static/project.js?v=20261019d" defer></script>
|
||||||
|
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# [실적] 실적 모듈 — `app/modules/performance/`, `performance_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/PERFORMANCE_MODULE.md`(큰 문서 — `grep -n '^#'` 로 목차 보고 필요한 절만 읽기).
|
||||||
|
> 정적 파일: `app/static/performance.css`, `performance.js`. 템플릿: `templates/`. 테스트: `tests/`.
|
||||||
|
> 다른 모듈과 연결: 카페24 어댑터는 `app/integrations/cafe24` 토큰 재사용 · Project 주간 회의록 머리 카드가 `performance_store` 매출을 읽기 전용으로 씀 · `APP_ENCRYPTION_KEY` 는 입출고(Gmail 토큰)와 공유.
|
||||||
|
|
||||||
|
## 구조 (네 영역 분리)
|
||||||
|
|
||||||
|
1. 수집 — `adapters/`(쇼핑몰 하나 = 어댑터 파일 하나 + `registry.py` 한 줄 + SQL seed 한 줄) + `sync.py`(공통 동기화, 같은 쇼핑몰 동시 실행 차단, 쇼핑몰별 실패 격리).
|
||||||
|
2. 보안 — `security/`(AES-256-GCM, 키 버전, 비밀값 가리기) + `credentials.py`.
|
||||||
|
3. 계산 — `calc.py`(주 = 월~일, 수수료 반올림은 `commission()` 한 곳, 요율 이력) + `db.py`.
|
||||||
|
4. 화면 — `dashboard.py`/`router.py`/템플릿.
|
||||||
|
|
||||||
|
## 규칙
|
||||||
|
|
||||||
|
- 쇼핑몰 API 인증정보는 `.env` 가 아니라 **설정 화면에서 입력 → 마스터 키 `APP_ENCRYPTION_KEY` 로 암호화해 DB 저장**, secret 원문은 화면으로 다시 보내지 않는다.
|
||||||
|
- 쇼핑몰 API 는 백엔드에서만 호출, 오류·로그·raw 는 `redact` 후 저장.
|
||||||
|
- 매출 기준일: 결제 = 결제일, 취소·반품 = 발생일(`sync.sales_date_for`). 금액은 원 단위 정수.
|
||||||
|
- 권한키 `performance`. 설정 화면은 모듈 권한자 누구나(일반 사용자는 수수료율만), 수수료 외 설정 API 는 `is_admin`.
|
||||||
|
- 1단계는 모의 데이터(`is_sample`)·구조까지, 실제 수집은 쇼핑몰별로 공식 문서 확인 후 순차 구현.
|
||||||
|
- 쇼핑몰 화면 수치와 맞출 때는 필드 추측 말고 붙여넣기 비교 + 원본 필드 합계로 진단부터.
|
||||||
|
|
||||||
|
## 매출 업데이트
|
||||||
|
|
||||||
|
- 진행 창에서 쇼핑몰별 [중지](그 쇼핑몰만 멈추고 다음 쇼핑몰로).
|
||||||
|
- **자동 업데이트**(`auto_sync.py`, 웹 프로세스 데몬 스레드) — 매일 09~19시 정각·30분마다 오늘 포함 최근 10일, 진행 창 작업으로 돌고 다른 업데이트 중이면 그 회차 건너뜀. env `PERFORMANCE_AUTO_SYNC`·`_DAYS`·`_HOURS`.
|
||||||
|
- 쿠팡은 판매자배송 발주서 + 로켓그로스 주문을 결제일로 합산(WING 판매분석 대조는 원본 데이터 확인으로).
|
||||||
|
|
||||||
|
## 수동 입력
|
||||||
|
|
||||||
|
- 설정의 쇼핑몰별 **수동 입력** 토글(마이그레이션 002 `manual_input`·`perf_manual_sales`) — 켜면 일자별 표 날짜 칸에 총매출 직접 입력, 넣은 날은 API 값 대신(`daily_amounts` 한 곳).
|
||||||
|
- 일자별 표 [엑셀 업로드] 팝업(`manual_upload.py`, `POST /performance/api/manual-sales/upload`) — 1열 날짜·2열부터 쇼핑몰 이름 머리글, 수동 입력 켜진 쇼핑몰 열의 값 있는 칸만 반영(덮어씀, 빈 칸 그대로), 잘못된 칸이 하나라도 있으면 전부 저장 안 함, 샘플 = 모듈 폴더 `upload_sample.xlsx`.
|
||||||
|
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
|
||||||
|
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
||||||
|
|
||||||
|
## 매출 실적 화면 (2026-10-19)
|
||||||
|
|
||||||
|
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음.
|
||||||
|
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
|
||||||
|
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
|
||||||
|
|
||||||
|
## 광고비 (`/performance/ads`)
|
||||||
|
|
||||||
|
- 탭은 [매출 실적]·[광고비] + 맨 오른쪽 설정 톱니.
|
||||||
|
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
|
||||||
|
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
|
||||||
|
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
|
||||||
|
- 쿠팡: 1열 날짜·19열 청구금액(+부가가치세).
|
||||||
|
- 네이버: 3열 기간·4열 총비용·12열 ROAS, 머리글 클릭 = 일자별 보고서 항목.
|
||||||
|
- 매출 대비 광고비 KPI.
|
||||||
|
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 매출 자동 업데이트 회차에 함께. 결과는 `perf_ad_spend` `source='api'`(초록 숫자, API 가 안 준 날은 예전 API 값만 지움).
|
||||||
|
- **구글 = Google Ads API**(2026-10-15) — 고객 ID·(MCC)·서비스 계정 JSON·API 버전(기본 v26). 개발자 토큰은 2026-09-09 구글 폐지 — 접근 등급은 서비스 계정의 Cloud 프로젝트, 머리글 안 보냄. 광고비 탭 [구글 광고 불러오기](보는 기간). 광고비 = 비용 × 1.1(부가세 포함)·ROAS(전환 가치 ÷ 비용, 구글 값 그대로)·항목.
|
||||||
|
- **메타 = 메타 마케팅 API**(2026-10-16, `ad_sources/meta_ads.py`, 새 마이그레이션 없음) — 광고 계정 ID(여러 개, 날짜별 합산)·액세스 토큰(ads_read, 시스템 사용자 토큰 권장)·앱 시크릿(선택)·API 버전(기본 v26.0). 광고비 = 지출 금액 그대로(메타는 이미 부가세 포함 — × 1.1 은 구글만)·ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 구매 ROAS). USD 등 외화 계정은 그날 환율로 원화 환산(`fx.py`, Frankfurter 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [메타 광고 불러오기]·자동 업데이트 회차.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""광고 API 연동(구글 광고 등) — 광고 채널 하나 = 파일 하나 + registry.py 한 줄.
|
||||||
|
|
||||||
|
쇼핑몰 어댑터(adapters/)와 같은 모양(입력칸·연결 테스트·인증정보 접근자)을 따르되, 돌려주는 것은 매출 사건이 아니라
|
||||||
|
"날짜별 광고비·ROAS·보고서 항목"(AdDay)이다. 저장은 ad_sync.py 가 perf_ad_spend(source='api')에.
|
||||||
|
"""
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""광고 API 연동 — 공통 인터페이스.
|
||||||
|
|
||||||
|
광고 채널 코드(code)는 광고비 표 채널 코드(ad_spend.CHANNELS)와 같다 — 가져온 값은 그 채널 열로 들어간다.
|
||||||
|
인증정보는 쇼핑몰 인증정보와 같은 방식(설정 화면 입력 → 마스터 키로 암호화 → perf_ad_credentials)이고,
|
||||||
|
꺼낼 때는 ctx.credentials.get(key) 로만(서버 안에서만 복호화). 오류는 adapters.base 의 AdapterError 계열 —
|
||||||
|
status 가 곧 연결 상태 코드(설정 화면 표시)다. 오류 문구에 비밀값을 넣지 않는다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from ..adapters.base import AdapterContext, CredentialField, NotConfigured
|
||||||
|
|
||||||
|
|
||||||
|
# AdDay.metrics 안의 계정별 값(여러 광고 계정을 합치는 채널 — 메타, 2026-10-16):
|
||||||
|
# {ACCOUNTS_KEY: {계정 ID: {"name", "amount", "roas", "metrics"}}} — 상세보기 [합계 | 계정…] 탭(ad_spend.detail_tabs).
|
||||||
|
# "_" 로 시작하는 metrics 키는 일자별 표 열·합계에 넣지 않는다(ad_spend.detail_table).
|
||||||
|
ACCOUNTS_KEY = "_accounts"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AdDay:
|
||||||
|
"""광고 API 가 돌려준 하루치 — 금액은 원 단위 정수, ROAS 는 %(없으면 None), 나머지 항목은 화면 이름 그대로."""
|
||||||
|
|
||||||
|
day: date
|
||||||
|
amount: int
|
||||||
|
roas: Decimal | None = None
|
||||||
|
metrics: dict[str, Any] = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class AdSource:
|
||||||
|
code: str = "" # 광고비 채널 코드(google 등)
|
||||||
|
name: str = "" # 설정 화면 이름
|
||||||
|
docs_url: str = ""
|
||||||
|
note: str = "" # 설정 창 맨 위 안내
|
||||||
|
|
||||||
|
# 인증정보 서비스(credentials.CredentialService)가 쇼핑몰 어댑터와 같은 방식으로 다루게 맞춘 속성
|
||||||
|
@property
|
||||||
|
def uses_shared_integration(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def visible_fields(self) -> list[CredentialField]:
|
||||||
|
return [f for f in self.credential_fields() if not f.internal]
|
||||||
|
|
||||||
|
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||||
|
"""저장 전 검사. values 의 "__stored__" = 저장된 값이 있음(원문은 꺼내지 않음). 값 자체를 오류 문구에 넣지 않는다."""
|
||||||
|
errors: list[str] = []
|
||||||
|
for f in self.visible_fields():
|
||||||
|
v = (values.get(f.key) or "").strip()
|
||||||
|
if f.required and not v:
|
||||||
|
errors.append(f"{f.label} 을(를) 입력하세요.")
|
||||||
|
elif v and len(v) > 20000:
|
||||||
|
errors.append(f"{f.label} 값이 너무 깁니다.")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def is_configured(self, ctx: AdapterContext) -> bool:
|
||||||
|
return all(ctx.credentials.has(f.key) for f in self.visible_fields() if f.required)
|
||||||
|
|
||||||
|
def require_configured(self, ctx: AdapterContext) -> None:
|
||||||
|
if not self.is_configured(ctx):
|
||||||
|
raise NotConfigured("필수 인증정보가 입력되지 않았습니다. 실적 설정 → 광고 API 연동에서 입력하세요.")
|
||||||
|
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
"""성공하면 사람이 읽을 짧은 문구. 실패는 AdapterError."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||||
|
"""기간(양 끝 포함)의 날짜별 광고비. 광고가 없던 날은 빠질 수 있다(저장 쪽이 그날의 예전 API 값을 지운다)."""
|
||||||
|
raise NotImplementedError
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목.
|
||||||
|
|
||||||
|
인증(2026-10-15 사용자: 서비스 계정 Explorer 승인)
|
||||||
|
- 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx.
|
||||||
|
서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다
|
||||||
|
(2024-11 부터 도메인 전체 위임 없이 직접 추가 가능).
|
||||||
|
- **개발자 토큰은 2026-09-09 폐지** — API 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙는다
|
||||||
|
(Cloud Console → Google Ads API Overview 에서 신청). developer-token 머리글은 지금은 무시되고 다음 큰 버전부터 거부되므로
|
||||||
|
보내지 않는다(입력칸도 없음, 예전에 저장한 값은 쓰지 않음).
|
||||||
|
- 요청 머리글: Authorization(Bearer) · login-customer-id(MCC 를 거쳐 들어갈 때만).
|
||||||
|
- Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
|
||||||
|
|
||||||
|
조회(REST googleAds:searchStream, GAQL)
|
||||||
|
SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks,
|
||||||
|
metrics.conversions, metrics.conversions_value FROM customer WHERE segments.date BETWEEN 'from' AND 'to'
|
||||||
|
- 날짜는 광고 계정 시간대 기준(한국 계정이면 KST). 광고가 없던 날은 행이 없을 수 있다.
|
||||||
|
- 금액(광고비) = **부가세 포함**(2026-10-15 사용자 요청) = cost_micros ÷ 1,000,000 × 1.1 을 원 단위로 반올림
|
||||||
|
(구글 광고 비용은 부가세 별도 — 쿠팡 광고비처럼 부가세 포함으로 맞춘다). 계정 통화가 KRW 가 아니면 저장하지 않는다.
|
||||||
|
- ROAS(%) = 전환 가치 ÷ 비용(부가세 별도) × 100 — 구글 광고 화면 "전환 가치/비용"과 같은 값 그대로, 비용이 0 이면 없음.
|
||||||
|
- 나머지 항목(노출수·클릭수·클릭률·전환수·전환 가치)은 광고비 탭 구글 머리글 → 일자별 표.
|
||||||
|
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 구글은 버전을 약 1년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import date
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, NotConfigured
|
||||||
|
from .base import AdDay, AdSource
|
||||||
|
|
||||||
|
SCOPE = "https://www.googleapis.com/auth/adwords"
|
||||||
|
API_BASE = "https://googleads.googleapis.com"
|
||||||
|
DEFAULT_VERSION = "v26" # 2026-10 기준 최신(구글 광고 API 는 매월 부 버전·분기마다 새 버전)
|
||||||
|
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||||
|
MAX_DAYS = 366
|
||||||
|
VAT = Decimal("1.1") # 광고비 = 구글 비용 + 부가세 10%
|
||||||
|
|
||||||
|
# 일자별 표(광고비 탭 구글 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
|
||||||
|
M_SPEND, M_COST = "광고비(부가세 포함)", "비용(부가세 별도)"
|
||||||
|
M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "노출수", "클릭수", "클릭률(%)", "전환수", "전환 가치", "ROAS(%)"
|
||||||
|
|
||||||
|
# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
|
||||||
|
_HINTS = {
|
||||||
|
"CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION": "서비스 계정이 속한 Google Cloud 프로젝트에 운영 계정 접근 승인이 없습니다. "
|
||||||
|
"Cloud Console → Google Ads API Overview 에서 그 프로젝트의 Explorer 이상 승인을 확인하세요.",
|
||||||
|
"AUTHORIZATION_ERROR": "API 접근 승인 문제입니다. 서비스 계정이 속한 Cloud 프로젝트의 Google Ads API 승인 상태를 확인하세요.",
|
||||||
|
"INVALID_LOGIN_CUSTOMER_ID": "[로그인 고객 ID(MCC)] 칸 문제입니다. 서비스 계정을 광고 계정에 직접 추가했다면 이 칸을 비우세요"
|
||||||
|
"(칸을 지우고 [연결 테스트] → [저장]). MCC 에 추가했다면 서비스 계정을 추가한 그 MCC 번호여야 하고, "
|
||||||
|
"고객 ID 의 광고 계정이 그 MCC 아래에 있어야 합니다.",
|
||||||
|
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
|
||||||
|
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
|
||||||
|
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
|
||||||
|
"NOT_ADS_USER": "서비스 계정이 구글 광고 사용자로 등록돼 있지 않습니다(액세스 및 보안에서 추가).",
|
||||||
|
"INVALID_CUSTOMER_ID": "고객 ID 가 올바르지 않습니다(광고 계정 오른쪽 위 123-456-7890 형태 번호).",
|
||||||
|
"CUSTOMER_NOT_FOUND": "고객 ID 의 광고 계정을 찾을 수 없습니다.",
|
||||||
|
"SERVICE_ACCOUNT_NOT_ALLOWED": "이 계정은 서비스 계정 접근을 허용하지 않습니다.",
|
||||||
|
}
|
||||||
|
|
||||||
|
_token_lock = threading.Lock()
|
||||||
|
_token_cache: dict[str, tuple[str, float]] = {} # (서비스 계정 이메일, 키 ID) → (액세스 토큰, 만료 시각)
|
||||||
|
|
||||||
|
|
||||||
|
def _digits(value: str) -> str:
|
||||||
|
return re.sub(r"[\s\-]", "", value or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _http(ctx: AdapterContext) -> httpx.Client:
|
||||||
|
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||||
|
return httpx.Client(timeout=ctx.timeout_sec)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_service_account(raw: str) -> dict[str, Any]:
|
||||||
|
"""서비스 계정 JSON 키 → dict. 형식이 틀리면 ValueError(문구에 키 내용을 넣지 않는다)."""
|
||||||
|
try:
|
||||||
|
info = json.loads(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("서비스 계정 키가 JSON 형식이 아닙니다(구글 클라우드에서 내려받은 .json 파일 내용을 통째로 붙여 넣으세요).") from None
|
||||||
|
if not isinstance(info, dict) or info.get("type") != "service_account":
|
||||||
|
raise ValueError("서비스 계정 키가 아닙니다(\"type\": \"service_account\" 인 JSON 이어야 합니다).")
|
||||||
|
for k in ("client_email", "private_key"):
|
||||||
|
if not str(info.get(k) or "").strip():
|
||||||
|
raise ValueError(f"서비스 계정 키에 {k} 가 없습니다.")
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
def _won(micros: int, rate: Decimal = Decimal(1)) -> int:
|
||||||
|
"""마이크로 단위 금액 × rate → 원(반올림). rate=VAT 면 부가세 포함."""
|
||||||
|
return int((Decimal(int(micros)) * rate / Decimal(1_000_000)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def _num(v: Any) -> Decimal:
|
||||||
|
"""REST 응답 숫자(int64 는 문자열, double 은 숫자, 0 은 아예 빠짐) → Decimal."""
|
||||||
|
if v is None or v == "":
|
||||||
|
return Decimal(0)
|
||||||
|
return Decimal(str(v))
|
||||||
|
|
||||||
|
|
||||||
|
def _google_error(resp: httpx.Response) -> tuple[str, str]:
|
||||||
|
"""구글 오류 응답 → (오류 코드 이름, 사람이 읽을 문구). searchStream 오류는 배열에 싸여 올 수 있다."""
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
return "", f"HTTP {resp.status_code}"
|
||||||
|
if isinstance(body, list):
|
||||||
|
body = next((b for b in body if isinstance(b, dict) and b.get("error")), body[0] if body else {})
|
||||||
|
err = (body or {}).get("error") or {}
|
||||||
|
if isinstance(err, str): # 토큰 교환 오류 {"error": "invalid_grant", "error_description": "..."}
|
||||||
|
return err, str((body or {}).get("error_description") or err)
|
||||||
|
code_name, message = "", str(err.get("message") or f"HTTP {resp.status_code}")
|
||||||
|
for d in err.get("details") or []:
|
||||||
|
for e in (d or {}).get("errors") or []:
|
||||||
|
ec = e.get("errorCode") or {}
|
||||||
|
if ec:
|
||||||
|
code_name = str(next(iter(ec.values())))
|
||||||
|
if e.get("message"):
|
||||||
|
message = str(e["message"])
|
||||||
|
break
|
||||||
|
if code_name:
|
||||||
|
break
|
||||||
|
return code_name, message
|
||||||
|
|
||||||
|
|
||||||
|
class GoogleAdsSource(AdSource):
|
||||||
|
code = "google"
|
||||||
|
name = "구글 광고"
|
||||||
|
docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts"
|
||||||
|
note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. "
|
||||||
|
"준비: ① Google Cloud 서비스 계정 JSON 키(그 Cloud 프로젝트가 Google Ads API Explorer 이상 승인) "
|
||||||
|
"② 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분). "
|
||||||
|
"개발자 토큰은 2026-09-09 폐지돼 필요 없습니다.")
|
||||||
|
|
||||||
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
return [
|
||||||
|
CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890",
|
||||||
|
help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."),
|
||||||
|
CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근",
|
||||||
|
help="서비스 계정을 관리자(MCC) 계정에 추가해 그 아래 광고 계정을 볼 때만 MCC 번호를 넣습니다."),
|
||||||
|
CredentialField("service_account_json", "서비스 계정 키(JSON)", secret=True, multiline=True,
|
||||||
|
help="Google Cloud → IAM → 서비스 계정 → 키 → JSON 으로 받은 파일 내용을 통째로 붙여 넣습니다. "
|
||||||
|
"저장 후에는 화면에 다시 보이지 않습니다."),
|
||||||
|
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
|
||||||
|
help=f"비워 두면 {DEFAULT_VERSION}. 구글이 버전 종료를 알리면 새 버전(예: v27)으로 바꿉니다."),
|
||||||
|
]
|
||||||
|
|
||||||
|
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||||
|
errors = super().validate_credentials(values)
|
||||||
|
for key, label in (("customer_id", "고객 ID"), ("login_customer_id", "로그인 고객 ID")):
|
||||||
|
v = (values.get(key) or "").strip()
|
||||||
|
if v and v != "__stored__" and not re.fullmatch(r"\d{10}", _digits(v)):
|
||||||
|
errors.append(f"{label}는 숫자 10자리여야 합니다(예: 123-456-7890).")
|
||||||
|
sa = (values.get("service_account_json") or "").strip()
|
||||||
|
if sa and sa != "__stored__":
|
||||||
|
try:
|
||||||
|
parse_service_account(sa)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
ver = (values.get("api_version") or "").strip()
|
||||||
|
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}", ver):
|
||||||
|
errors.append("API 버전은 v26 처럼 v 뒤에 숫자로 입력하세요.")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
# ── 인증 ──────────────────────────────────────────────
|
||||||
|
def _access_token(self, ctx: AdapterContext, client: httpx.Client) -> str:
|
||||||
|
try:
|
||||||
|
info = parse_service_account(ctx.credentials.get("service_account_json"))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise NotConfigured(str(exc)) from None
|
||||||
|
cache_key = f"{info['client_email']}|{info.get('private_key_id', '')}"
|
||||||
|
with _token_lock:
|
||||||
|
hit = _token_cache.get(cache_key)
|
||||||
|
if hit and hit[1] > time.time() + 120:
|
||||||
|
return hit[0]
|
||||||
|
from google.auth import crypt, jwt # noqa: WPS433 — google-auth(requirements)
|
||||||
|
|
||||||
|
try:
|
||||||
|
signer = crypt.RSASigner.from_service_account_info(info)
|
||||||
|
except Exception: # noqa: BLE001 — 키 내용은 문구에 넣지 않는다
|
||||||
|
raise AuthFailed("서비스 계정 키의 private_key 를 읽을 수 없습니다(JSON 파일 내용을 그대로 붙여 넣었는지 확인).") from None
|
||||||
|
now = int(time.time())
|
||||||
|
token_uri = str(info.get("token_uri") or TOKEN_URI)
|
||||||
|
assertion = jwt.encode(signer, {"iss": info["client_email"], "scope": SCOPE, "aud": token_uri,
|
||||||
|
"iat": now, "exp": now + 3600})
|
||||||
|
try:
|
||||||
|
resp = client.post(token_uri, data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
||||||
|
"assertion": assertion.decode() if isinstance(assertion, bytes) else assertion})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code != 200:
|
||||||
|
name, msg = _google_error(resp)
|
||||||
|
raise AuthFailed(f"서비스 계정 인증 실패({name or resp.status_code}): {msg[:200]} — 키가 삭제·사용 중지되지 않았는지 확인하세요.")
|
||||||
|
body = resp.json()
|
||||||
|
token = str(body.get("access_token") or "")
|
||||||
|
if not token:
|
||||||
|
raise AuthFailed("구글 인증 서버가 액세스 토큰을 주지 않았습니다.")
|
||||||
|
with _token_lock:
|
||||||
|
_token_cache[cache_key] = (token, time.time() + int(body.get("expires_in") or 3600))
|
||||||
|
return token
|
||||||
|
|
||||||
|
def _search(self, ctx: AdapterContext, query: str) -> list[dict[str, Any]]:
|
||||||
|
"""GAQL 한 번 — searchStream 응답(묶음 배열)의 results 를 이어 붙여 돌려준다."""
|
||||||
|
self.require_configured(ctx)
|
||||||
|
cid = _digits(ctx.credentials.get("customer_id"))
|
||||||
|
if not re.fullmatch(r"\d{10}", cid):
|
||||||
|
raise NotConfigured("고객 ID 는 숫자 10자리여야 합니다.")
|
||||||
|
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
|
||||||
|
with _http(ctx) as client:
|
||||||
|
token = self._access_token(ctx, client)
|
||||||
|
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} # 개발자 토큰 없음(2026-09-09 폐지)
|
||||||
|
login = _digits(ctx.credentials.get("login_customer_id"))
|
||||||
|
if login:
|
||||||
|
headers["login-customer-id"] = login
|
||||||
|
ctx.progress.check()
|
||||||
|
try:
|
||||||
|
resp = client.post(f"{API_BASE}/{version}/customers/{cid}/googleAds:searchStream",
|
||||||
|
headers=headers, json={"query": query})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"구글 광고 API 에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code == 404:
|
||||||
|
raise ApiError(f"구글 광고 API 버전 {version} 을(를) 쓸 수 없습니다(종료됐을 수 있음) — 실적 설정에서 API 버전을 최신으로 바꾸세요.")
|
||||||
|
if resp.status_code != 200:
|
||||||
|
name, msg = _google_error(resp)
|
||||||
|
hint = _HINTS.get(name, "")
|
||||||
|
text = f"구글 광고 API 오류({name or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
|
||||||
|
raise (AuthFailed if resp.status_code in (401, 403) else ApiError)(text)
|
||||||
|
try:
|
||||||
|
batches = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
raise ApiError("구글 광고 API 응답을 읽을 수 없습니다.") from None
|
||||||
|
if isinstance(batches, dict):
|
||||||
|
batches = [batches]
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for b in batches or []:
|
||||||
|
out.extend((b or {}).get("results") or [])
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ── 연결 테스트 · 가져오기 ─────────────────────────────
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
rows = self._search(ctx, "SELECT customer.id, customer.descriptive_name, customer.currency_code, "
|
||||||
|
"customer.time_zone FROM customer LIMIT 1")
|
||||||
|
c = (rows[0].get("customer") if rows else None) or {}
|
||||||
|
currency = c.get("currencyCode") or "?"
|
||||||
|
msg = f"연결됨 — {c.get('descriptiveName') or '광고 계정'} · 통화 {currency} · 시간대 {c.get('timeZone') or '?'}"
|
||||||
|
if currency != "KRW":
|
||||||
|
msg += " (원화 계정이 아니라 광고비를 가져올 수 없습니다)"
|
||||||
|
return msg
|
||||||
|
|
||||||
|
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||||
|
if end < start:
|
||||||
|
start, end = end, start
|
||||||
|
if (end - start).days + 1 > MAX_DAYS:
|
||||||
|
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
|
||||||
|
rows = self._search(
|
||||||
|
ctx,
|
||||||
|
"SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks, "
|
||||||
|
"metrics.conversions, metrics.conversions_value FROM customer "
|
||||||
|
f"WHERE segments.date BETWEEN '{start.isoformat()}' AND '{end.isoformat()}'",
|
||||||
|
)
|
||||||
|
sums: dict[date, dict[str, Decimal]] = {}
|
||||||
|
for r in rows:
|
||||||
|
cur = ((r.get("customer") or {}).get("currencyCode") or "").upper()
|
||||||
|
if cur and cur != "KRW":
|
||||||
|
raise ApiError(f"광고 계정 통화가 {cur} 입니다 — 원화(KRW) 계정만 광고비로 가져옵니다.")
|
||||||
|
raw_day = (r.get("segments") or {}).get("date")
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(str(raw_day))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
m = r.get("metrics") or {}
|
||||||
|
acc = sums.setdefault(day, {"cost": Decimal(0), "impr": Decimal(0), "clicks": Decimal(0),
|
||||||
|
"conv": Decimal(0), "value": Decimal(0)})
|
||||||
|
acc["cost"] += _num(m.get("costMicros"))
|
||||||
|
acc["impr"] += _num(m.get("impressions"))
|
||||||
|
acc["clicks"] += _num(m.get("clicks"))
|
||||||
|
acc["conv"] += _num(m.get("conversions"))
|
||||||
|
acc["value"] += _num(m.get("conversionsValue"))
|
||||||
|
out: list[AdDay] = []
|
||||||
|
for day in sorted(sums):
|
||||||
|
a = sums[day]
|
||||||
|
amount = _won(int(a["cost"]), VAT) # 광고비 = 부가세 포함
|
||||||
|
cost = a["cost"] / Decimal(1_000_000)
|
||||||
|
roas = (a["value"] / cost * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if cost > 0 else None
|
||||||
|
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
|
||||||
|
metrics = {
|
||||||
|
M_SPEND: amount,
|
||||||
|
M_COST: _won(int(a["cost"])),
|
||||||
|
M_IMPR: int(a["impr"]),
|
||||||
|
M_CLICKS: int(a["clicks"]),
|
||||||
|
M_CTR: float(ctr) if ctr is not None else None,
|
||||||
|
M_CONV: float(a["conv"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
|
||||||
|
M_VALUE: int(a["value"].quantize(Decimal(1), rounding=ROUND_HALF_UP)),
|
||||||
|
M_ROAS: float(roas) if roas is not None else None,
|
||||||
|
}
|
||||||
|
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
|
||||||
|
return out
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
"""메타 광고(Meta Marketing API — Insights) — 날짜별 광고비·ROAS·보고서 항목.
|
||||||
|
|
||||||
|
인증(2026-10-16 사용자: 토큰·광고 계정 ID 준비 완료)
|
||||||
|
- 액세스 토큰 하나(시스템 사용자 토큰 권장 — 만료 없음. 사용자 토큰은 약 60일 뒤 만료) + 광고 계정 ID 여러 개.
|
||||||
|
토큰에 ads_read 권한이 있어야 하고, 토큰 주인(시스템 사용자 등)이 각 광고 계정에 배정돼 있어야 한다.
|
||||||
|
- 메타 문서대로 토큰은 access_token 매개변수로 보낸다. 앱 설정에서 "앱 시크릿 필요"를 켰다면 앱 시크릿을 넣어
|
||||||
|
appsecret_proof(HMAC-SHA256)를 같이 보낸다. 토큰은 오류 문구에 넣지 않고(주소도 넣지 않음),
|
||||||
|
ad_sync 가 저장된 비밀값을 다시 한 번 가린다. httpx 요청 로그(INFO)는 주소에 토큰이 들어가므로 켜지 않는다.
|
||||||
|
|
||||||
|
조회(GET /{버전}/act_{계정}/insights)
|
||||||
|
level=account · time_increment=1(하루씩) · time_range={since, until} · fields=spend·노출·클릭·구매 전환 등.
|
||||||
|
- 날짜는 광고 계정 시간대 기준. 광고가 없던 날은 행이 없다. 여러 계정은 날짜별로 더한다.
|
||||||
|
- 원화가 아닌 계정(USD 등, 2026-10-16)은 지출 금액·구매 전환값을 그날 환율로 원화 환산(fx.krw_rates — Frankfurter 중앙은행 고시 환율 종합,
|
||||||
|
그날 값이 없으면 앞 가장 가까운 날). 계정 탭에 원래 통화 지출·적용 환율. ROAS 는 비율이라 환율과 무관.
|
||||||
|
- 기여(어트리뷰션)는 메타가 광고 관리자 설정을 그대로 따른다(2025-06 부터 API 의 기여 매개변수는 무시됨) — 화면 값과 같다.
|
||||||
|
- 구매 전환값·구매수 = action_values·actions 의 구매 항목 하나(omni_purchase → purchase → 픽셀 구매 순서로 처음 있는 것).
|
||||||
|
메타는 같은 구매를 여러 action_type 에 같은 값으로 겹쳐 주므로 더하지 않는다.
|
||||||
|
- 금액(광고비) = 지출 금액 그대로(원 반올림) — **메타 지출 금액은 이미 부가세 포함**(2026-10-16 사용자 확인).
|
||||||
|
부가세를 더하는(× 1.1) 것은 비용이 부가세 별도인 구글만이다.
|
||||||
|
- ROAS(%) = 구매 전환값 ÷ 지출 금액 × 100 — 광고 관리자 "구매 ROAS" 와 같은 값, 지출 0 이면 없음.
|
||||||
|
- 나머지 항목(노출수·클릭수·클릭률·링크 클릭·구매수·구매 전환값)은 광고비 탭 메타 머리글 → 일자별 표.
|
||||||
|
API 버전은 설정 칸(기본 DEFAULT_VERSION) — 메타는 버전을 약 2년 뒤 종료하므로 종료 안내가 오면 설정에서 올린다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from datetime import date
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from ..adapters.base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, NotConfigured, TokenExpired
|
||||||
|
from .. import fx
|
||||||
|
from .base import ACCOUNTS_KEY, AdDay, AdSource
|
||||||
|
|
||||||
|
API_BASE = "https://graph.facebook.com"
|
||||||
|
DEFAULT_VERSION = "v26.0" # 2026-07-29 출시(2026-10 기준 최신)
|
||||||
|
MAX_DAYS = 366
|
||||||
|
MAX_ACCOUNTS = 30
|
||||||
|
MAX_PAGES = 50 # 계정 하나 페이지 상한(하루 한 줄이라 366일도 몇 쪽)
|
||||||
|
PURCHASE_TYPES = ("omni_purchase", "purchase", "offsite_conversion.fb_pixel_purchase")
|
||||||
|
INSIGHT_FIELDS = "date_start,account_id,account_name,account_currency,spend,impressions,clicks,inline_link_clicks,actions,action_values"
|
||||||
|
|
||||||
|
# 일자별 표(광고비 탭 메타 머리글) 항목 — 순서 = 열 순서. 클릭률·ROAS 합계는 ad_spend.detail_table 이 이름으로 다시 계산.
|
||||||
|
M_SPEND = "지출 금액(부가세 포함)" # = 광고비(메타 지출 금액은 부가세 포함 — 구글처럼 따로 더하지 않음)
|
||||||
|
M_IMPR, M_CLICKS, M_CTR, M_LINK = "노출수", "클릭수", "클릭률(%)", "링크 클릭"
|
||||||
|
M_PURCHASES, M_VALUE, M_ROAS = "구매수", "구매 전환값", "ROAS(%)"
|
||||||
|
M_FX = "적용 환율(원)" # 외화 계정 탭에만 — 그날 1 계정 통화 = ? 원(fx.krw_rates)
|
||||||
|
|
||||||
|
# 메타 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임). 권한 오류는 연결 테스트가 원인을 진단한다(_diagnose) —
|
||||||
|
# 불러오기에서 난 오류엔 그 안내를 붙이고, 연결 테스트 자체에서는 진단 결과로 바꿔 쓴다.
|
||||||
|
_DIAG_HINT = "(실적 설정 → 광고 API 연동 → 메타 [연결 테스트]가 원인을 진단합니다)"
|
||||||
|
_HINTS = {
|
||||||
|
190: "토큰이 만료됐거나 무효입니다. 비즈니스 설정 → 시스템 사용자에서 토큰을 다시 만들어 [액세스 토큰]에 넣으세요(시스템 사용자 토큰은 만료 없음).",
|
||||||
|
102: "토큰을 읽을 수 없습니다. 토큰을 다시 복사해 넣으세요.",
|
||||||
|
200: "토큰에 권한이 없습니다. 토큰을 만들 때 ads_read 권한을 고르고, 토큰 주인(시스템 사용자)을 이 광고 계정에 배정했는지 확인하세요"
|
||||||
|
+ _DIAG_HINT + ".",
|
||||||
|
10: "토큰에 권한이 없습니다(ads_read). 앱·토큰 권한을 확인하세요.",
|
||||||
|
100: "요청 값이 올바르지 않습니다 — 광고 계정 ID 가 맞는지, 토큰 주인이 그 계정을 볼 수 있는지 확인하세요.",
|
||||||
|
803: "광고 계정 ID 를 찾을 수 없습니다(숫자만, act_ 는 있어도 됨).",
|
||||||
|
4: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
|
||||||
|
17: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
|
||||||
|
613: "메타 API 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
|
||||||
|
80000: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
|
||||||
|
80004: "광고 계정 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.",
|
||||||
|
2635: "API 버전이 종료됐습니다 — 실적 설정에서 API 버전을 최신으로 바꾸세요.",
|
||||||
|
}
|
||||||
|
_RATE_LIMIT = {4, 17, 613, 80000, 80004}
|
||||||
|
_AUTH = {10, 102, 200}
|
||||||
|
_ACCOUNT_STATUS = {1: "운영 중", 2: "사용 중지", 3: "미결제", 7: "검토 대기", 8: "결제 대기", 9: "유예 기간", 100: "종료 대기", 101: "종료"}
|
||||||
|
|
||||||
|
|
||||||
|
def _http(ctx: AdapterContext) -> httpx.Client:
|
||||||
|
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
|
||||||
|
return httpx.Client(timeout=ctx.timeout_sec)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_account_ids(raw: str) -> list[str]:
|
||||||
|
"""'act_123, 456\\n789' → ['123', '456', '789'](순서 유지·중복 제거). 형식이 틀리면 ValueError."""
|
||||||
|
out: list[str] = []
|
||||||
|
for part in re.split(r"[\s,;]+", raw or ""):
|
||||||
|
if not part:
|
||||||
|
continue
|
||||||
|
v = part[4:] if part.lower().startswith("act_") else part
|
||||||
|
if not re.fullmatch(r"\d{5,20}", v):
|
||||||
|
raise ValueError("광고 계정 ID 는 숫자여야 합니다(act_ 는 있어도 됨, 여러 개는 쉼표나 줄바꿈으로 구분).")
|
||||||
|
if v not in out:
|
||||||
|
out.append(v)
|
||||||
|
if len(out) > MAX_ACCOUNTS:
|
||||||
|
raise ValueError(f"광고 계정은 {MAX_ACCOUNTS}개까지 넣을 수 있습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _num(v: Any) -> Decimal:
|
||||||
|
"""메타 응답 숫자(문자열로 옴, 0 이면 빠지기도 함) → Decimal."""
|
||||||
|
if v is None or v == "":
|
||||||
|
return Decimal(0)
|
||||||
|
try:
|
||||||
|
return Decimal(str(v))
|
||||||
|
except ArithmeticError:
|
||||||
|
return Decimal(0)
|
||||||
|
|
||||||
|
|
||||||
|
def _won(v: Decimal) -> int:
|
||||||
|
return int(v.quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def _purchase(items: Any) -> Decimal:
|
||||||
|
"""actions / action_values 목록에서 구매 값 하나(PURCHASE_TYPES 순서로 처음 있는 것 — 겹친 값을 더하지 않는다)."""
|
||||||
|
by_type = {str((i or {}).get("action_type")): (i or {}).get("value") for i in (items or []) if isinstance(i, dict)}
|
||||||
|
for t in PURCHASE_TYPES:
|
||||||
|
if t in by_type:
|
||||||
|
return _num(by_type[t])
|
||||||
|
return Decimal(0)
|
||||||
|
|
||||||
|
|
||||||
|
def _meta_error(resp: httpx.Response) -> tuple[int, str]:
|
||||||
|
"""메타 오류 응답 {"error": {"message", "code", "error_subcode", ...}} → (코드, 문구)."""
|
||||||
|
try:
|
||||||
|
err = (resp.json() or {}).get("error") or {}
|
||||||
|
except ValueError:
|
||||||
|
return 0, f"HTTP {resp.status_code}"
|
||||||
|
if not isinstance(err, dict):
|
||||||
|
return 0, f"HTTP {resp.status_code}"
|
||||||
|
msg = str(err.get("error_user_msg") or err.get("message") or f"HTTP {resp.status_code}")
|
||||||
|
try:
|
||||||
|
code = int(err.get("code") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
code = 0
|
||||||
|
return code, msg
|
||||||
|
|
||||||
|
|
||||||
|
class MetaAdsSource(AdSource):
|
||||||
|
code = "meta"
|
||||||
|
name = "메타 광고"
|
||||||
|
docs_url = "https://developers.facebook.com/docs/marketing-api/insights"
|
||||||
|
note = ("메타 마케팅 API(Insights)로 광고 계정별 날짜별 지출 금액·구매 ROAS·노출수·클릭수·구매를 가져와 계정을 합칩니다. "
|
||||||
|
"준비: ① ads_read 권한이 있는 액세스 토큰(비즈니스 설정 → 시스템 사용자 토큰 권장 — 만료 없음) "
|
||||||
|
"② 토큰 주인을 각 광고 계정에 배정. 광고비 = 메타 지출 금액 그대로(이미 부가세 포함)입니다.")
|
||||||
|
|
||||||
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
return [
|
||||||
|
CredentialField("account_ids", "광고 계정 ID", multiline=True, placeholder="act_1234567890\nact_9876543210",
|
||||||
|
help="광고비를 가져올 광고 계정 번호(광고 관리자 주소의 act= 뒤 숫자). 여러 개면 줄바꿈이나 쉼표로 — "
|
||||||
|
"날짜별로 합쳐서 메타 한 칸에 들어갑니다."),
|
||||||
|
CredentialField("access_token", "액세스 토큰", secret=True,
|
||||||
|
help="ads_read 권한이 있는 토큰. 저장 후에는 화면에 다시 보이지 않습니다."),
|
||||||
|
CredentialField("app_secret", "앱 시크릿", secret=True, required=False, placeholder="앱에서 '앱 시크릿 필요'를 켰을 때만",
|
||||||
|
help="메타 앱 설정 → 고급에서 'API 호출에 앱 시크릿 필요'를 켰다면 넣습니다(appsecret_proof). 아니면 비워 둡니다."),
|
||||||
|
CredentialField("api_version", "API 버전", required=False, placeholder=DEFAULT_VERSION,
|
||||||
|
help=f"비워 두면 {DEFAULT_VERSION}. 메타가 버전 종료를 알리면 새 버전(예: v27.0)으로 바꿉니다."),
|
||||||
|
]
|
||||||
|
|
||||||
|
def validate_credentials(self, values: dict[str, str]) -> list[str]:
|
||||||
|
errors = super().validate_credentials(values)
|
||||||
|
ids = (values.get("account_ids") or "").strip()
|
||||||
|
if ids and ids != "__stored__":
|
||||||
|
try:
|
||||||
|
parse_account_ids(ids)
|
||||||
|
except ValueError as exc:
|
||||||
|
errors.append(str(exc))
|
||||||
|
token = (values.get("access_token") or "").strip()
|
||||||
|
if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)):
|
||||||
|
errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).")
|
||||||
|
ver = (values.get("api_version") or "").strip()
|
||||||
|
if ver and ver != "__stored__" and not re.fullmatch(r"v\d{2,3}\.0", ver):
|
||||||
|
errors.append("API 버전은 v26.0 처럼 입력하세요.")
|
||||||
|
return errors
|
||||||
|
|
||||||
|
# ── 요청 ──────────────────────────────────────────────
|
||||||
|
def _setup(self, ctx: AdapterContext) -> tuple[list[str], str, dict[str, str]]:
|
||||||
|
self.require_configured(ctx)
|
||||||
|
try:
|
||||||
|
accounts = parse_account_ids(ctx.credentials.get("account_ids"))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise NotConfigured(str(exc)) from None
|
||||||
|
if not accounts:
|
||||||
|
raise NotConfigured("광고 계정 ID 를 입력하세요.")
|
||||||
|
token = (ctx.credentials.get("access_token") or "").strip()
|
||||||
|
auth = {"access_token": token}
|
||||||
|
secret = (ctx.credentials.get("app_secret") or "").strip()
|
||||||
|
if secret:
|
||||||
|
auth["appsecret_proof"] = hmac.new(secret.encode(), token.encode(), hashlib.sha256).hexdigest()
|
||||||
|
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
|
||||||
|
return accounts, version, auth
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, client: httpx.Client, url: str, params: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
ctx.progress.check()
|
||||||
|
try:
|
||||||
|
resp = client.get(url, params=params)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"메타 API 에 연결하지 못했습니다({type(exc).__name__}).") from None # 주소(토큰 포함)는 넣지 않는다
|
||||||
|
if resp.status_code != 200:
|
||||||
|
code, msg = _meta_error(resp)
|
||||||
|
hint = _HINTS.get(code, "")
|
||||||
|
text = f"메타 API 오류({code or resp.status_code}): {msg[:200]}" + (f" — {hint}" if hint else "")
|
||||||
|
if code == 190:
|
||||||
|
raise TokenExpired(text)
|
||||||
|
auth_problem = code in _AUTH or (resp.status_code in (401, 403) and code not in _RATE_LIMIT)
|
||||||
|
raise (AuthFailed if auth_problem else ApiError)(text)
|
||||||
|
try:
|
||||||
|
body = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
raise ApiError("메타 API 응답을 읽을 수 없습니다.") from None
|
||||||
|
return body if isinstance(body, dict) else {}
|
||||||
|
|
||||||
|
# ── 권한 진단(연결 테스트가 권한 오류를 받았을 때) ─────────
|
||||||
|
def _diagnose(self, ctx: AdapterContext, client: httpx.Client, version: str, auth: dict[str, str],
|
||||||
|
accounts: list[str]) -> str:
|
||||||
|
"""토큰이 받은 권한·권한 대상 계정·볼 수 있는 광고 계정을 메타에 물어 원인을 짚는다(2026-10-16 #200 오류).
|
||||||
|
조회가 실패해도 예외를 내지 않는다(진단은 덧붙이는 정보). 토큰 값은 문구에 넣지 않는다."""
|
||||||
|
lines: list[str] = []
|
||||||
|
scopes: set[str] | None = None
|
||||||
|
ads_targets: set[str] | None = None # ads_read/ads_management 가 특정 계정에만 걸려 있으면 그 계정들
|
||||||
|
try: # ① 토큰 점검 — 앱 개발자 토큰·시스템 사용자 토큰이면 같은 토큰으로 된다
|
||||||
|
d = (self._get(ctx, client, f"{API_BASE}/{version}/debug_token",
|
||||||
|
{**auth, "input_token": auth["access_token"]}).get("data") or {})
|
||||||
|
scopes = {str(s) for s in d.get("scopes") or []}
|
||||||
|
for g in d.get("granular_scopes") or []:
|
||||||
|
if str((g or {}).get("scope")) in ("ads_read", "ads_management") and (g or {}).get("target_ids"):
|
||||||
|
ads_targets = (ads_targets or set()) | {str(t) for t in g["target_ids"]}
|
||||||
|
exp = int(d.get("expires_at") or 0)
|
||||||
|
expires = "만료 없음" if exp == 0 else date.fromtimestamp(exp).isoformat() + " 만료"
|
||||||
|
lines.append(f"토큰: 앱 {d.get('application') or d.get('app_id') or '?'}({d.get('app_id') or '?'}) · {expires}"
|
||||||
|
+ ("" if d.get("is_valid", True) else " · 무효"))
|
||||||
|
except AdapterError:
|
||||||
|
try: # ② 토큰 점검을 못 하면 받은 권한 목록만
|
||||||
|
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/permissions", dict(auth)).get("data") or []
|
||||||
|
scopes = {str(r.get("permission")) for r in rows if r.get("status") == "granted"}
|
||||||
|
except AdapterError:
|
||||||
|
pass
|
||||||
|
if scopes is not None:
|
||||||
|
has = sorted(scopes & {"ads_read", "ads_management"})
|
||||||
|
lines.append("광고 권한: " + (", ".join(has) if has else "없음(ads_read·ads_management 둘 다 없음)"))
|
||||||
|
visible: set[str] | None = None
|
||||||
|
try: # ③ 이 토큰으로 볼 수 있는 광고 계정
|
||||||
|
rows = self._get(ctx, client, f"{API_BASE}/{version}/me/adaccounts",
|
||||||
|
{**auth, "fields": "account_id,name", "limit": 200}).get("data") or []
|
||||||
|
visible = {str(r.get("account_id") or "") for r in rows}
|
||||||
|
lines.append(f"이 토큰으로 보이는 광고 계정 {len(visible)}개")
|
||||||
|
except AdapterError:
|
||||||
|
pass
|
||||||
|
missing = [a for a in accounts if visible is not None and a not in visible]
|
||||||
|
not_target = [a for a in accounts if ads_targets is not None and a not in ads_targets]
|
||||||
|
# 결론 — 가장 앞선 원인 하나
|
||||||
|
if scopes is not None and not scopes & {"ads_read", "ads_management"}:
|
||||||
|
todo = ("토큰에 ads_read 권한이 없습니다 → 토큰을 새로 만들면서 ads_read 를 체크하세요"
|
||||||
|
"(비즈니스 설정 → 사용자 → 시스템 사용자 → 새 토큰 생성 → 권한에서 ads_read).")
|
||||||
|
elif missing:
|
||||||
|
todo = ("입력한 계정 중 이 토큰 주인에게 배정되지 않은 계정: " + ", ".join("act_" + a for a in missing)
|
||||||
|
+ " → 비즈니스 설정 → 사용자 → 시스템 사용자(토큰 주인) → [자산 할당] → 광고 계정에서 그 계정을 고르고 "
|
||||||
|
"'성과 보기'(또는 전체 권한)를 켠 뒤, 토큰을 새로 만들어 넣으세요(배정 전에 만든 토큰은 권한이 안 바뀔 수 있음).")
|
||||||
|
elif not_target:
|
||||||
|
todo = ("토큰의 ads_read 권한이 다른 계정에만 걸려 있습니다(대상 아님: " + ", ".join("act_" + a for a in not_target)
|
||||||
|
+ ") → 토큰을 새로 만들 때 이 광고 계정도 대상에 포함하세요.")
|
||||||
|
elif visible is not None:
|
||||||
|
todo = ("토큰 권한·계정 배정은 맞습니다 → 앱 쪽 문제일 가능성이 큽니다: 앱이 이 광고 계정을 가진 비즈니스에 연결돼 있는지"
|
||||||
|
"(비즈니스 설정 → 계정 → 앱), 앱 대시보드에 Marketing API 제품이 추가돼 있는지, 앱이 '제한 액세스'라면 토큰 주인이 앱의 "
|
||||||
|
"관리자·개발자 역할인지 확인하세요.")
|
||||||
|
else:
|
||||||
|
todo = "토큰 정보를 메타에서 읽지 못해 원인을 좁히지 못했습니다 — 토큰 권한(ads_read)과 광고 계정 배정을 확인하세요."
|
||||||
|
return "[진단] " + " · ".join(lines + [todo])
|
||||||
|
|
||||||
|
# ── 연결 테스트 · 가져오기 ─────────────────────────────
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
accounts, version, auth = self._setup(ctx)
|
||||||
|
parts: list[str] = []
|
||||||
|
not_krw = False
|
||||||
|
with _http(ctx) as client:
|
||||||
|
for acc in accounts:
|
||||||
|
try:
|
||||||
|
info = self._get(ctx, client, f"{API_BASE}/{version}/act_{acc}",
|
||||||
|
{**auth, "fields": "name,currency,timezone_name,account_status"})
|
||||||
|
except AuthFailed as exc: # 권한 오류(#200 등) — 메타에 토큰 정보를 물어 원인을 덧붙인다
|
||||||
|
# 진단(고칠 곳)을 맨 앞에, 메타 원문은 짧게 뒤에 — 길면 화면·기록에서 뒤가 잘리므로(2026-10-16 "[진…" 잘림)
|
||||||
|
original = str(exc).split(" — ")[0]
|
||||||
|
original = re.sub(r",?\s*refer to https?://\S+(?: for details)?", "", original)
|
||||||
|
raise AuthFailed(self._diagnose(ctx, client, version, auth, accounts)
|
||||||
|
+ f" (메타 원문: {original})") from None
|
||||||
|
cur = str(info.get("currency") or "?")
|
||||||
|
not_krw = not_krw or cur != "KRW"
|
||||||
|
status = _ACCOUNT_STATUS.get(info.get("account_status"), "")
|
||||||
|
parts.append(f"{info.get('name') or acc}({cur}·{info.get('timezone_name') or '?'}{'·' + status if status else ''})")
|
||||||
|
msg = f"연결됨 — 광고 계정 {len(accounts)}개: " + ", ".join(parts)
|
||||||
|
if not_krw:
|
||||||
|
msg += f" (원화가 아닌 계정은 날마다 그날 환율로 원화로 바꿔 넣습니다 — {fx.SOURCE_LABEL})"
|
||||||
|
return msg
|
||||||
|
|
||||||
|
def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]:
|
||||||
|
if end < start:
|
||||||
|
start, end = end, start
|
||||||
|
if (end - start).days + 1 > MAX_DAYS:
|
||||||
|
raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.")
|
||||||
|
accounts, version, auth = self._setup(ctx)
|
||||||
|
params = {**auth, "level": "account", "time_increment": 1, "limit": 100, "fields": INSIGHT_FIELDS,
|
||||||
|
"time_range": json.dumps({"since": start.isoformat(), "until": end.isoformat()})}
|
||||||
|
raw: list[tuple[str, date, str, dict[str, Any]]] = [] # (계정, 날짜, 통화, insights 한 줄)
|
||||||
|
names: dict[str, str] = {}
|
||||||
|
with _http(ctx) as client:
|
||||||
|
for acc in accounts:
|
||||||
|
url: str | None = f"{API_BASE}/{version}/act_{acc}/insights"
|
||||||
|
page_params: dict[str, Any] | None = params
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, client, url, page_params)
|
||||||
|
for r in body.get("data") or []:
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(str(r.get("date_start")))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if r.get("account_name"):
|
||||||
|
names[acc] = str(r["account_name"])[:100]
|
||||||
|
raw.append((acc, day, str(r.get("account_currency") or "KRW").upper(), r))
|
||||||
|
nxt = ((body.get("paging") or {}).get("next") or "").strip()
|
||||||
|
if not nxt:
|
||||||
|
break
|
||||||
|
if not nxt.startswith(API_BASE + "/"):
|
||||||
|
raise ApiError("메타 API 다음 쪽 주소가 올바르지 않습니다.")
|
||||||
|
url, page_params = nxt, None # next 주소에 매개변수(토큰 포함)가 다 들어 있다
|
||||||
|
else:
|
||||||
|
raise ApiError("메타 API 응답 쪽수가 너무 많습니다. 기간을 줄여 다시 시도하세요.")
|
||||||
|
# 원화가 아닌 계정(USD 등) — 그날 환율로 원화 환산(2026-10-16). 통화마다 기간 환율을 한 번에.
|
||||||
|
rates: dict[str, dict[date, Decimal]] = {}
|
||||||
|
for cur in sorted({c for _a, _d, c, _r in raw if c != "KRW"}):
|
||||||
|
if not re.fullmatch(r"[A-Z]{3}", cur):
|
||||||
|
raise ApiError(f"광고 계정 통화({cur[:10]})를 알 수 없습니다.")
|
||||||
|
try:
|
||||||
|
rates[cur] = fx.krw_rates(client, cur, start, end)
|
||||||
|
except fx.FxError as exc:
|
||||||
|
raise ApiError(f"{cur} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None
|
||||||
|
sums: dict[date, dict[str, Decimal]] = {} # 날짜 → 모든 계정 합(원화)
|
||||||
|
per_acc: dict[date, dict[str, dict[str, Any]]] = {} # 날짜 → 계정 → 그 계정 값(상세보기 계정별 탭)
|
||||||
|
for acc, day, cur, r in raw:
|
||||||
|
rate = Decimal(1) if cur == "KRW" else rates[cur][day]
|
||||||
|
one = per_acc.setdefault(day, {}).setdefault(acc, {**_zero(), "cur": cur, "rate": rate, "orig": Decimal(0)})
|
||||||
|
_add(one, r, rate)
|
||||||
|
one["orig"] += _num(r.get("spend")) # 그 계정 통화 그대로의 지출 금액
|
||||||
|
_add(sums.setdefault(day, _zero()), r, rate)
|
||||||
|
out: list[AdDay] = []
|
||||||
|
for day in sorted(sums):
|
||||||
|
amount, roas, metrics = _convert(sums[day])
|
||||||
|
# 계정별 값 — 화면 표 열이 아니라 상세보기 계정별 탭용(ad_spend.detail_tabs, "_" 로 시작하는 키는 표 열에서 빠짐).
|
||||||
|
# 계정마다 따로 반올림하므로 계정 광고비 합이 합계와 1원 다를 수 있다.
|
||||||
|
accounts_out: dict[str, Any] = {}
|
||||||
|
for acc, a in per_acc.get(day, {}).items():
|
||||||
|
a_amount, a_roas, a_metrics = _convert(a)
|
||||||
|
if a["cur"] != "KRW": # 외화 계정 — 원래 통화 지출과 적용 환율도 보여 준다(계정 탭)
|
||||||
|
a_metrics[f"지출 금액({a['cur']})"] = float(a["orig"].quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
|
||||||
|
a_metrics[M_FX] = float(a["rate"])
|
||||||
|
accounts_out[acc] = {"name": names.get(acc) or f"act_{acc}", "amount": a_amount,
|
||||||
|
"roas": float(a_roas) if a_roas is not None else None, "metrics": a_metrics}
|
||||||
|
metrics[ACCOUNTS_KEY] = accounts_out
|
||||||
|
out.append(AdDay(day=day, amount=amount, roas=roas, metrics=metrics))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _zero() -> dict[str, Decimal]:
|
||||||
|
return {k: Decimal(0) for k in ("spend", "impr", "clicks", "link", "purchases", "value")}
|
||||||
|
|
||||||
|
|
||||||
|
def _add(acc: dict[str, Any], r: dict[str, Any], rate: Decimal = Decimal(1)) -> None:
|
||||||
|
"""insights 한 줄(계정 하나·하루)을 더한다 — 금액(지출·구매 전환값)은 × rate(그날 1 계정 통화 = ? 원)로 원화."""
|
||||||
|
acc["spend"] += _num(r.get("spend")) * rate
|
||||||
|
acc["impr"] += _num(r.get("impressions"))
|
||||||
|
acc["clicks"] += _num(r.get("clicks"))
|
||||||
|
acc["link"] += _num(r.get("inline_link_clicks"))
|
||||||
|
acc["purchases"] += _purchase(r.get("actions"))
|
||||||
|
acc["value"] += _purchase(r.get("action_values")) * rate
|
||||||
|
|
||||||
|
|
||||||
|
def _convert(a: dict[str, Decimal]) -> tuple[int, Decimal | None, dict[str, Any]]:
|
||||||
|
"""더한 값 → (광고비 원, ROAS %, 일자별 표 항목). 광고비 = 지출 금액 그대로(메타 지출은 부가세 포함, 2026-10-16)."""
|
||||||
|
amount = _won(a["spend"])
|
||||||
|
roas = (a["value"] / a["spend"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["spend"] > 0 else None
|
||||||
|
ctr = (a["clicks"] / a["impr"] * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if a["impr"] > 0 else None
|
||||||
|
return amount, roas, {
|
||||||
|
M_SPEND: amount,
|
||||||
|
M_IMPR: int(a["impr"]),
|
||||||
|
M_CLICKS: int(a["clicks"]),
|
||||||
|
M_CTR: float(ctr) if ctr is not None else None,
|
||||||
|
M_LINK: int(a["link"]),
|
||||||
|
M_PURCHASES: int(a["purchases"]),
|
||||||
|
M_VALUE: _won(a["value"]),
|
||||||
|
M_ROAS: float(roas) if roas is not None else None,
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""광고 API 연동 목록 — 새 광고 채널은 파일 하나 + 여기 한 줄(채널 코드는 ad_spend.CHANNELS 와 같아야 한다)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .base import AdSource
|
||||||
|
from .google_ads import GoogleAdsSource
|
||||||
|
from .meta_ads import MetaAdsSource
|
||||||
|
|
||||||
|
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
|
||||||
|
_BY_CODE = {s.code: s for s in _SOURCES}
|
||||||
|
|
||||||
|
|
||||||
|
def all_sources() -> tuple[AdSource, ...]:
|
||||||
|
return _SOURCES
|
||||||
|
|
||||||
|
|
||||||
|
def get_source(code: str) -> AdSource | None:
|
||||||
|
return _BY_CODE.get(code)
|
||||||
@@ -0,0 +1,543 @@
|
|||||||
|
"""광고비 — 채널(구글·메타·쿠팡(윙)·쿠팡(로켓))별 일 광고비 + 업로드 파일 읽기 + 화면 데이터 조립.
|
||||||
|
|
||||||
|
저장: performance_db `perf_ad_spend`(마이그레이션 005) — 채널 × 날짜 하나에 금액 하나(원 단위 정수).
|
||||||
|
- 화면 날짜 칸을 눌러 직접 입력(source=manual), 업로드 파일로 한 번에 입력(source=upload, 같은 날 덮어씀).
|
||||||
|
- 구글은 광고 API 로 가져온다(source=api, ad_sync.py — 2026-10-15). 메타는 지금은 직접 입력만.
|
||||||
|
|
||||||
|
쿠팡(윙)·쿠팡(로켓) 업로드 양식(2026-10-13·14 사용자 제공 — 둘 다 같은 쿠팡 광고 보고서 CSV/엑셀):
|
||||||
|
1행 머리글, 1열 = 날짜("2026년 10월 01일"), 19열 = 청구금액(+부가가치세) → 그날 광고비.
|
||||||
|
규칙(2026-10-14 사용자 확인): **1열에 날짜가 있는 줄의 19열 값**을 가져온다 — 19열이 빈 줄은 건너뛰고(윙 보고서는
|
||||||
|
캠페인 줄에도 날짜가 있고 19열이 비어 있다), 같은 날짜에 값이 있는 줄이 여럿이면 더한다.
|
||||||
|
1열이 빈 캠페인 줄·맨 위 "전체" 합계 줄은 건너뛴다. 날짜는 있는데 19열 값이 한 줄도 없는 날은 empty_days 로 알려 준다.
|
||||||
|
네이버 업로드 양식(2026-10-14 사용자 제공 — 네이버 광고 보고서 CSV/엑셀, 하루 한 줄):
|
||||||
|
1행 머리글, 3열 = 기간(날짜 "2026.09.30."), 4열 = 총비용 → 그날 광고비, 12열 = 구매완료 광고수익률(%) → 그날 ROAS.
|
||||||
|
나머지 열(노출수·클릭수·클릭률·전환수·구매완료 수·장바구니·총 전환매출액 …)은 머리글 이름 그대로 metrics 에 보관 —
|
||||||
|
화면에서 네이버 머리글을 누르면 일자별 표(마이그레이션 006: perf_ad_spend.roas·metrics).
|
||||||
|
|
||||||
|
HTTP·DB 와 무관한 순수 함수(읽기·조립) — 라우터가 파일 바이트와 저장소를 넘긴다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import io
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any, Callable, Mapping, Sequence
|
||||||
|
|
||||||
|
from . import calc
|
||||||
|
from .ad_sources.base import ACCOUNTS_KEY
|
||||||
|
from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES, UploadError, parse_amount, parse_date
|
||||||
|
|
||||||
|
# 채널 — 표 열 순서(2026-10-14 사용자 지정). 쇼핑몰 채널 코드는 실적 쇼핑몰 코드와 같다(쿠팡(윙)만 coupang_wing ↔ 매출 coupang).
|
||||||
|
CHANNELS: tuple[tuple[str, str], ...] = (
|
||||||
|
("google", "구글"),
|
||||||
|
("meta", "메타"),
|
||||||
|
("naver", "네이버"),
|
||||||
|
("coupang_wing", "쿠팡(윙)"),
|
||||||
|
("coupang_rocket", "쿠팡(로켓)"),
|
||||||
|
("ohouse", "오늘의집"),
|
||||||
|
("gmarket", "G마켓"),
|
||||||
|
("kakao", "카카오"),
|
||||||
|
("gsshop", "GS샵"),
|
||||||
|
("elevenst", "11번가"),
|
||||||
|
("lotteon", "롯데ON"),
|
||||||
|
("toss", "토스"),
|
||||||
|
("atomy", "애터미아자몰"),
|
||||||
|
)
|
||||||
|
CHANNEL_NAMES = dict(CHANNELS)
|
||||||
|
CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
|
||||||
|
# ROAS(매출 ÷ 광고비 × 100) 의 매출 = 이 쇼핑몰 매출 실적 총매출. 쿠팡(윙)은 매출 쪽 코드가 coupang.
|
||||||
|
# 구글·메타·네이버는 ROAS 를 계산하지 않는다 — 광고 보고서의 ROAS 값을 따로 넣는다(perf_ad_spend.roas, 2026-10-14).
|
||||||
|
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
|
||||||
|
FILE_ROAS = frozenset({"google", "meta", "naver"})
|
||||||
|
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
|
||||||
|
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS}
|
||||||
|
ROAS_SALES_CODE["coupang_wing"] = "coupang"
|
||||||
|
|
||||||
|
|
||||||
|
def roas(sales: int, spend: int) -> int | None:
|
||||||
|
"""ROAS(%) = 매출 ÷ 광고비 × 100, 정수로 반올림. 광고비가 없으면 None."""
|
||||||
|
if not spend or spend <= 0:
|
||||||
|
return None
|
||||||
|
return int((Decimal(int(sales)) * 100 / Decimal(int(spend))).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def roas_basis(code: str) -> str:
|
||||||
|
"""머리글 말풍선 — ROAS 에 쓰는 매출(구글·메타·네이버는 빈 값 = 계산 안 함, 보고서 값)."""
|
||||||
|
return "" if code not in ROAS_SALES_CODE else CHANNEL_NAMES.get(code, code)
|
||||||
|
|
||||||
|
|
||||||
|
def file_roas(code: str, file_roas_map: Mapping[tuple[date, str], Any], spends: Mapping[tuple[date, str], int],
|
||||||
|
s: date, e: date) -> int | None:
|
||||||
|
"""보고서 ROAS 채널의 기간 ROAS — Σ(ROAS × 광고비) ÷ Σ광고비(ROAS 가 있고 광고비가 있는 날만)."""
|
||||||
|
rev = Decimal(0)
|
||||||
|
spend = 0
|
||||||
|
for (d, c), r in file_roas_map.items():
|
||||||
|
if c != code or not s <= d <= e or r is None:
|
||||||
|
continue
|
||||||
|
amt = int(spends.get((d, c)) or 0)
|
||||||
|
if amt > 0:
|
||||||
|
rev += Decimal(str(r)) * amt
|
||||||
|
spend += amt
|
||||||
|
if spend <= 0:
|
||||||
|
return None
|
||||||
|
return int((rev / spend).quantize(Decimal(1), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def channel_roas(code: str, sales_of: Callable[[str], int], spend: int,
|
||||||
|
file_of: Callable[[str], int | None] | None = None) -> int | None:
|
||||||
|
"""채널 칸의 ROAS — 쇼핑몰 매출 ÷ 광고비. 구글·메타·네이버는 보고서 ROAS(file_of), 없으면 None."""
|
||||||
|
if code in FILE_ROAS:
|
||||||
|
return file_of(code) if file_of else None
|
||||||
|
mcode = ROAS_SALES_CODE.get(code)
|
||||||
|
return None if mcode is None else roas(sales_of(mcode), spend)
|
||||||
|
|
||||||
|
ROCKET_DATE_COL = 0 # 1열 날짜
|
||||||
|
ROCKET_AMOUNT_COL = 18 # 19열 청구금액(+부가가치세)
|
||||||
|
SKIP_LABELS = frozenset({"전체", "합계", "총계", "날짜"})
|
||||||
|
|
||||||
|
|
||||||
|
NAVER_DATE_COL = 2 # 3열 기간(날짜)
|
||||||
|
NAVER_AMOUNT_COL = 3 # 4열 총비용
|
||||||
|
NAVER_ROAS_COL = 11 # 12열 구매완료 광고수익률(%)
|
||||||
|
NAVER_SKIP_COLS = (0, 1, 2) # 광고 계정 이름·ID·기간은 metrics 에 넣지 않음
|
||||||
|
|
||||||
|
|
||||||
|
class AdMigrationNeeded(Exception):
|
||||||
|
"""광고비 표(마이그레이션 005: perf_ad_spend) 또는 ROAS·상세 칸(006)이 아직 없음."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParseResult:
|
||||||
|
entries: list[tuple[date, int]] = field(default_factory=list) # (날짜, 금액)
|
||||||
|
errors: list[str] = field(default_factory=list)
|
||||||
|
skipped: int = 0 # 건너뛴 줄(캠페인 줄·합계 줄)
|
||||||
|
# 보고서 ROAS·상세 항목(네이버) — 날짜 → ROAS(%) · {머리글: 값}. 비어 있으면 금액만 저장.
|
||||||
|
roas: dict[date, Decimal] = field(default_factory=dict)
|
||||||
|
metrics: dict[date, dict[str, Any]] = field(default_factory=dict)
|
||||||
|
columns: list[str] = field(default_factory=list) # 상세 항목 머리글(파일 순서)
|
||||||
|
empty_days: list[date] = field(default_factory=list) # 날짜 줄은 있는데 금액이 한 줄도 없던 날(저장 안 함)
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 파일 읽기
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _decode_csv(content: bytes) -> str:
|
||||||
|
for enc in ("utf-8-sig", "cp949"):
|
||||||
|
try:
|
||||||
|
return content.decode(enc)
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
raise UploadError("CSV 글자 인코딩을 읽을 수 없습니다(UTF-8 또는 CP949 로 저장해 주세요).")
|
||||||
|
|
||||||
|
|
||||||
|
def read_rows(content: bytes, filename: str = "") -> list[tuple[Any, ...]]:
|
||||||
|
"""CSV 또는 엑셀(.xlsx) 첫 시트 → 줄 목록(값 그대로)."""
|
||||||
|
if not content:
|
||||||
|
raise UploadError("빈 파일입니다.")
|
||||||
|
if len(content) > MAX_FILE_BYTES:
|
||||||
|
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||||
|
is_xlsx = content[:2] == b"PK" or filename.lower().endswith(".xlsx")
|
||||||
|
if not is_xlsx:
|
||||||
|
return [tuple(r) for r in csv.reader(io.StringIO(_decode_csv(content)))]
|
||||||
|
try:
|
||||||
|
import openpyxl # noqa: WPS433
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||||
|
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||||
|
raise UploadError("파일을 읽을 수 없습니다. 쿠팡 광고 보고서 CSV 또는 엑셀(.xlsx) 파일을 올려 주세요.") from None
|
||||||
|
try:
|
||||||
|
return [tuple(r or ()) for r in wb.worksheets[0].iter_rows(values_only=True)]
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_coupang_rocket(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||||||
|
"""쿠팡(윙·로켓) 광고 보고서 → (날짜, 그날 19열 청구금액(+부가가치세) 합). 1열에 날짜가 있고 19열에 값이 있는 줄만,
|
||||||
|
같은 날짜는 더한다. 잘못된 줄이 있으면 errors 에 담는다(저장은 라우터가 막음)."""
|
||||||
|
rows = read_rows(content, filename)
|
||||||
|
res = ParseResult()
|
||||||
|
sums: dict[date, int] = {}
|
||||||
|
dated: set[date] = set()
|
||||||
|
for r, row in enumerate(rows, start=1):
|
||||||
|
raw_day = row[ROCKET_DATE_COL] if len(row) > ROCKET_DATE_COL else None
|
||||||
|
text = str(raw_day or "").strip()
|
||||||
|
if not text or text.replace(" ", "") in SKIP_LABELS:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
day = parse_date(raw_day)
|
||||||
|
except ValueError:
|
||||||
|
if r == 1: # 머리글
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
res.errors.append(f"{r}행 1열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||||||
|
continue
|
||||||
|
if day is None:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
raw_amt = row[ROCKET_AMOUNT_COL] if len(row) > ROCKET_AMOUNT_COL else None
|
||||||
|
try:
|
||||||
|
amt = parse_amount(raw_amt)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{r}행 19열: 금액이 숫자가 아닙니다({str(raw_amt)[:30]}).")
|
||||||
|
continue
|
||||||
|
dated.add(day)
|
||||||
|
if amt is None:
|
||||||
|
res.skipped += 1 # 날짜는 있지만 19열이 빈 줄(캠페인 줄 등) — 건너뜀
|
||||||
|
elif abs(amt) > MAX_AMOUNT:
|
||||||
|
res.errors.append(f"{r}행 19열: 금액이 너무 큽니다.")
|
||||||
|
elif day > today:
|
||||||
|
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||||
|
else:
|
||||||
|
sums[day] = sums.get(day, 0) + amt # 같은 날짜에 값이 있는 줄이 여럿이면 더한다
|
||||||
|
if len(sums) > MAX_DATA_ROWS:
|
||||||
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||||
|
if len(res.errors) > MAX_ERRORS:
|
||||||
|
break
|
||||||
|
res.entries = sorted(sums.items())
|
||||||
|
res.empty_days = sorted(d for d in dated if d not in sums and d <= today)
|
||||||
|
# 날짜 줄은 있는데 청구금액이 한 줄도 없는 파일(그 달 광고비 0 등)은 오류가 아니라 넘어간다(2026-10-14 사용자 요청).
|
||||||
|
# 날짜 줄 자체가 없을 때만 양식 오류.
|
||||||
|
if not dated and not res.errors:
|
||||||
|
raise UploadError("광고비 날짜 줄이 없습니다. 1열 날짜(예: 2026년 10월 01일), 19열 청구금액(+부가가치세) 양식인지 확인하세요.")
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
def _number(value: Any) -> Decimal | None:
|
||||||
|
"""숫자 칸 → Decimal(쉼표·%·원 허용). 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||||
|
if value is None or (isinstance(value, str) and not value.strip()):
|
||||||
|
return None
|
||||||
|
if isinstance(value, bool):
|
||||||
|
raise ValueError
|
||||||
|
text = str(value).replace(",", "").replace("%", "").replace("원", "").strip()
|
||||||
|
try:
|
||||||
|
num = Decimal(text)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise ValueError from None
|
||||||
|
if not num.is_finite():
|
||||||
|
raise ValueError
|
||||||
|
return num
|
||||||
|
|
||||||
|
|
||||||
|
def _json_num(num: Decimal | None) -> Any:
|
||||||
|
if num is None:
|
||||||
|
return None
|
||||||
|
return int(num) if num == num.to_integral_value() else float(round(num, 2))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_naver(content: bytes, *, today: date, filename: str = "") -> ParseResult:
|
||||||
|
"""네이버 광고 보고서 → (날짜, 총비용) + 그날 ROAS(12열) + 나머지 항목. 잘못된 줄이 있으면 errors."""
|
||||||
|
rows = read_rows(content, filename)
|
||||||
|
res = ParseResult()
|
||||||
|
header: tuple[Any, ...] = ()
|
||||||
|
seen: dict[date, int] = {}
|
||||||
|
for r, row in enumerate(rows, start=1):
|
||||||
|
raw_day = row[NAVER_DATE_COL] if len(row) > NAVER_DATE_COL else None
|
||||||
|
text = str(raw_day or "").strip()
|
||||||
|
if not text or text.replace(" ", "") in SKIP_LABELS:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
day = parse_date(raw_day)
|
||||||
|
except ValueError:
|
||||||
|
if not header: # 머리글(1행 "기간")
|
||||||
|
header = tuple(str(h or "").strip() for h in row)
|
||||||
|
res.columns = [h for i, h in enumerate(header) if i not in NAVER_SKIP_COLS and h]
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
res.errors.append(f"{r}행 3열: 날짜를 읽을 수 없습니다({text[:30]}).")
|
||||||
|
continue
|
||||||
|
if day is None:
|
||||||
|
res.skipped += 1
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
amt = parse_amount(row[NAVER_AMOUNT_COL] if len(row) > NAVER_AMOUNT_COL else None)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{r}행 4열: 총비용이 숫자가 아닙니다.")
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ro = _number(row[NAVER_ROAS_COL] if len(row) > NAVER_ROAS_COL else None)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{r}행 12열: 광고수익률(ROAS)이 숫자가 아닙니다.")
|
||||||
|
continue
|
||||||
|
if amt is None:
|
||||||
|
res.errors.append(f"{r}행 4열: {day.isoformat()} 총비용이 비어 있습니다.")
|
||||||
|
elif abs(amt) > MAX_AMOUNT or (ro is not None and abs(ro) > Decimal("10000000")):
|
||||||
|
res.errors.append(f"{r}행: 금액·ROAS 가 너무 큽니다.")
|
||||||
|
elif day > today:
|
||||||
|
res.errors.append(f"{r}행: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||||
|
elif day in seen:
|
||||||
|
res.errors.append(f"{r}행: {day.isoformat()} 이 {seen[day]}행과 겹칩니다.")
|
||||||
|
else:
|
||||||
|
seen[day] = r
|
||||||
|
res.entries.append((day, amt))
|
||||||
|
if ro is not None:
|
||||||
|
res.roas[day] = ro
|
||||||
|
m: dict[str, Any] = {}
|
||||||
|
for i, v in enumerate(row):
|
||||||
|
name = header[i] if i < len(header) else f"{i + 1}열"
|
||||||
|
if i in NAVER_SKIP_COLS or not name:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
m[name] = _json_num(_number(v))
|
||||||
|
except ValueError:
|
||||||
|
m[name] = str(v)[:100]
|
||||||
|
res.metrics[day] = m
|
||||||
|
if len(res.entries) > MAX_DATA_ROWS:
|
||||||
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||||
|
if len(res.errors) > MAX_ERRORS:
|
||||||
|
break
|
||||||
|
if not res.entries and not res.errors:
|
||||||
|
raise UploadError("광고비 날짜 줄이 없습니다. 3열 기간(예: 2026.09.30.), 4열 총비용, 12열 광고수익률 양식인지 확인하세요.")
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
# 업로드 양식이 정해진 채널 → 파일 읽기 함수(채널 순서 = 업로드 창 선택 순서). 쿠팡(윙)도 로켓과 같은 양식(2026-10-14).
|
||||||
|
PARSERS: dict[str, Callable[..., ParseResult]] = {
|
||||||
|
"naver": parse_naver, "coupang_wing": parse_coupang_rocket, "coupang_rocket": parse_coupang_rocket}
|
||||||
|
_COUPANG_HELP = "쿠팡 광고 보고서(CSV 또는 엑셀) — 1열 날짜, 19열 청구금액(+부가가치세)을 그날 광고비로 넣습니다."
|
||||||
|
UPLOAD_HELP = {
|
||||||
|
"naver": "네이버 광고 보고서(CSV 또는 엑셀) — 3열 기간(날짜), 4열 총비용 = 그날 광고비, 12열 구매완료 광고수익률 = ROAS. "
|
||||||
|
"나머지 항목은 네이버 머리글을 누르면 일자별로 볼 수 있습니다.",
|
||||||
|
"coupang_wing": _COUPANG_HELP, "coupang_rocket": _COUPANG_HELP}
|
||||||
|
MAX_UPLOAD_FILES = 30
|
||||||
|
|
||||||
|
|
||||||
|
def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseResult, list[date]]:
|
||||||
|
"""여러 파일(이름, 파일 수정 시각, 읽은 결과)을 하나로 — 같은 날짜가 여러 파일에 있으면 **파일 날짜(수정 시각)가 최신인
|
||||||
|
파일** 값(같으면 나중에 올린 파일). 돌려주는 값: (합친 결과, 여러 파일에 겹친 날짜). 오류는 파일 이름을 앞에 붙여 모은다."""
|
||||||
|
merged = ParseResult()
|
||||||
|
owner: dict[date, tuple[float, int]] = {}
|
||||||
|
overlap: set[date] = set()
|
||||||
|
empty: set[date] = set()
|
||||||
|
for idx, (name, modified, res) in enumerate(parsed):
|
||||||
|
merged.errors.extend(f"[{name}] {e}" for e in res.errors)
|
||||||
|
empty.update(res.empty_days)
|
||||||
|
merged.skipped += res.skipped
|
||||||
|
for c in res.columns:
|
||||||
|
if c not in merged.columns:
|
||||||
|
merged.columns.append(c)
|
||||||
|
picked: dict[date, tuple[int, int]] = {}
|
||||||
|
for idx, (name, modified, res) in enumerate(parsed):
|
||||||
|
for day, amt in res.entries:
|
||||||
|
key = (float(modified or 0), idx)
|
||||||
|
if day in owner:
|
||||||
|
overlap.add(day)
|
||||||
|
if key < owner[day]:
|
||||||
|
continue
|
||||||
|
owner[day] = key
|
||||||
|
picked[day] = (idx, amt)
|
||||||
|
for day in sorted(picked):
|
||||||
|
idx, amt = picked[day]
|
||||||
|
res = parsed[idx][2]
|
||||||
|
merged.entries.append((day, amt))
|
||||||
|
if day in res.roas:
|
||||||
|
merged.roas[day] = res.roas[day]
|
||||||
|
if day in res.metrics:
|
||||||
|
merged.metrics[day] = res.metrics[day]
|
||||||
|
merged.empty_days = sorted(d for d in empty if d not in picked) # 어느 파일에도 값이 없던 날
|
||||||
|
return merged, sorted(overlap)
|
||||||
|
|
||||||
|
|
||||||
|
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
|
||||||
|
DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
|
||||||
|
|
||||||
|
|
||||||
|
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
"""일자별 상세(GET /api/ad-spend/{channel}/details) — rows: date·amount·roas·metrics(저장소).
|
||||||
|
열 = 파일 머리글 순서(처음 나온 순), 합계 = 숫자 열 합 + 클릭률·ROAS 는 가중 평균."""
|
||||||
|
cols: list[str] = []
|
||||||
|
for r in rows:
|
||||||
|
for k in (r.get("metrics") or {}):
|
||||||
|
if k not in cols and not k.startswith("_"): # "_" 키 = 표 열이 아닌 내부 값(계정별 등)
|
||||||
|
cols.append(k)
|
||||||
|
sums: dict[str, Decimal] = {}
|
||||||
|
for r in rows:
|
||||||
|
for k, v in (r.get("metrics") or {}).items():
|
||||||
|
if k.startswith("_"):
|
||||||
|
continue
|
||||||
|
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
||||||
|
sums[k] = sums.get(k, Decimal(0)) + Decimal(str(v))
|
||||||
|
total: dict[str, Any] = {k: _json_num(v) for k, v in sums.items()}
|
||||||
|
for k in cols:
|
||||||
|
if "클릭률" in k and sums.get("노출수"):
|
||||||
|
total[k] = float(round(sums.get("클릭수", Decimal(0)) * 100 / sums["노출수"], 2))
|
||||||
|
elif ("수익률" in k or "ROAS" in k.upper()):
|
||||||
|
spend = sum(int(r.get("amount") or 0) for r in rows if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||||||
|
rev = sum(Decimal(str(r["roas"])) * int(r.get("amount") or 0) for r in rows
|
||||||
|
if r.get("roas") is not None and int(r.get("amount") or 0) > 0)
|
||||||
|
total[k] = float(round(rev / spend, 2)) if spend else None
|
||||||
|
elif "환율" in k: # 외화 광고 계정 적용 환율(메타 USD 계정, 2026-10-16) — 더하지 않고 광고비 가중 평균
|
||||||
|
pairs = [(Decimal(str((r.get("metrics") or {})[k])), int(r.get("amount") or 0)) for r in rows
|
||||||
|
if isinstance((r.get("metrics") or {}).get(k), (int, float)) and int(r.get("amount") or 0) > 0]
|
||||||
|
weight = sum(w for _v, w in pairs)
|
||||||
|
total[k] = float(round(sum(v * w for v, w in pairs) / weight, 2)) if weight else None
|
||||||
|
out_rows = [{"date": r["date"], "amount": int(r.get("amount") or 0),
|
||||||
|
"roas": float(r["roas"]) if r.get("roas") is not None else None,
|
||||||
|
"values": {k: v for k, v in (r.get("metrics") or {}).items() if not k.startswith("_")}} for r in rows]
|
||||||
|
return {"columns": cols, "rows": out_rows, "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
def detail_tabs(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||||
|
"""상세보기 탭 — 계정별 값(ACCOUNTS_KEY)이 있는 채널(메타, 2026-10-16)은 [합계 | 계정…], 없으면 탭 없음.
|
||||||
|
계정 탭 = 그 계정이 광고를 낸 날만(그날 행의 계정 값으로 detail_table). 계정 이름은 가장 최근 날의 이름,
|
||||||
|
순서는 기간 광고비가 큰 계정부터(같으면 이름). accounts_missing = 광고비가 있는데 계정별 값이 없는 날 수
|
||||||
|
(계정별 저장 전에 가져온 날 — 다시 불러오면 생긴다)."""
|
||||||
|
per: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
names: dict[str, str] = {}
|
||||||
|
missing = 0
|
||||||
|
for r in rows:
|
||||||
|
accs = (r.get("metrics") or {}).get(ACCOUNTS_KEY)
|
||||||
|
if not isinstance(accs, dict):
|
||||||
|
if int(r.get("amount") or 0):
|
||||||
|
missing += 1
|
||||||
|
continue
|
||||||
|
for acc, a in accs.items():
|
||||||
|
if not isinstance(a, dict):
|
||||||
|
continue
|
||||||
|
names[acc] = str(a.get("name") or f"act_{acc}")
|
||||||
|
per.setdefault(acc, []).append({"date": r["date"], "amount": int(a.get("amount") or 0),
|
||||||
|
"roas": a.get("roas"), "metrics": a.get("metrics") or {}})
|
||||||
|
if not per:
|
||||||
|
return {"tabs": [], "accounts_missing": 0}
|
||||||
|
spend = {acc: sum(x["amount"] for x in days) for acc, days in per.items()}
|
||||||
|
order = sorted(per, key=lambda acc: (-spend[acc], names[acc]))
|
||||||
|
tabs = [{"key": "total", "label": "합계", **detail_table(rows)}]
|
||||||
|
tabs += [{"key": acc, "label": names[acc], "account_id": acc, **detail_table(per[acc])} for acc in order]
|
||||||
|
return {"tabs": tabs, "accounts_missing": missing}
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 화면 데이터
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||||
|
custom_from: date | None = None, custom_to: date | None = None,
|
||||||
|
holidays: Mapping[str, str] | None = None,
|
||||||
|
sales_codes: Sequence[str] = ()) -> dict[str, Any]:
|
||||||
|
"""광고비 화면 — 매출 실적과 같은 기간 이동·표(일자 × 채널, 연간은 월)·그래프·월/연 누적.
|
||||||
|
sales_codes 가 있으면 같은 기간 매출(총매출) 대비 광고비 비율도 보여 준다."""
|
||||||
|
codes = list(CHANNEL_CODES)
|
||||||
|
period = calc.resolve_period(kind, anchor, custom_from=custom_from, custom_to=custom_to)
|
||||||
|
cmp_start, cmp_end, cmp_label = period.compare_range(today)
|
||||||
|
ref = period.end if period.end < today else today if period.start <= today else period.start
|
||||||
|
month_period = calc.resolve_period("month", ref)
|
||||||
|
year_period = calc.resolve_period("year", ref)
|
||||||
|
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
|
||||||
|
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
|
||||||
|
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||||
|
q_end = max(period.end, year_period.end)
|
||||||
|
|
||||||
|
migration_needed = False
|
||||||
|
try:
|
||||||
|
amounts, sources = store.ad_amounts(q_start, q_end)
|
||||||
|
except AdMigrationNeeded:
|
||||||
|
amounts, sources, migration_needed = {}, {}, True
|
||||||
|
cells = {k: calc.Money(gross=int(v)) for k, v in amounts.items()}
|
||||||
|
roas_reader = getattr(store, "ad_roas", None)
|
||||||
|
try:
|
||||||
|
roas_map = roas_reader(q_start, q_end) if roas_reader and not migration_needed else {}
|
||||||
|
except AdMigrationNeeded:
|
||||||
|
roas_map = {}
|
||||||
|
|
||||||
|
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||||
|
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||||
|
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
|
||||||
|
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
|
||||||
|
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
|
||||||
|
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
||||||
|
|
||||||
|
# 매출(ROAS 용) — 채널별 매출 쇼핑몰 + 매출 실적에 들어가는 쇼핑몰 전부(합계 열 ROAS·매출 대비 광고비)
|
||||||
|
total_codes = list(sales_codes)
|
||||||
|
need = sorted(set(ROAS_SALES_CODE.values()) | set(total_codes))
|
||||||
|
sales = {(d, c): int(v) for (d, c), v in store.daily_amounts(q_start, q_end, need).items()}
|
||||||
|
|
||||||
|
def sales_sum(mcodes: Sequence[str], s: date, e: date) -> int:
|
||||||
|
want = set(mcodes)
|
||||||
|
return sum(v for (d, c), v in sales.items() if c in want and s <= d <= e)
|
||||||
|
|
||||||
|
sales_total = sales_sum(total_codes, period.start, period.end) if total_codes else None
|
||||||
|
ratio = round(cur.gross / sales_total * 100, 1) if sales_total and sales_total > 0 else None
|
||||||
|
|
||||||
|
word = {"day": "오늘" if period.start == today else "해당일",
|
||||||
|
"week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||||
|
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||||
|
"year": "올해" if period.start <= today <= period.end else "해당 연도",
|
||||||
|
"custom": "선택 기간"}[period.kind]
|
||||||
|
kpis = [
|
||||||
|
{"key": "spend", "label": f"{word} 광고비", "value": cur.gross, "primary": True,
|
||||||
|
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||||
|
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||||
|
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
||||||
|
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
|
||||||
|
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
|
||||||
|
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||||||
|
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
def url(k: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||||
|
if k == "custom":
|
||||||
|
return f"?period=custom&from={start.isoformat()}&to={end.isoformat()}"
|
||||||
|
return f"?period={k}&d={anchor_d.isoformat()}"
|
||||||
|
|
||||||
|
if period.kind == "custom":
|
||||||
|
from datetime import timedelta # noqa: WPS433
|
||||||
|
|
||||||
|
length = timedelta(days=period.days)
|
||||||
|
prev_url = url("custom", start=period.start - length, end=period.start - timedelta(days=1))
|
||||||
|
next_url = url("custom", start=period.end + timedelta(days=1), end=period.end + length)
|
||||||
|
else:
|
||||||
|
prev_url, next_url = url(period.kind, period.prev_anchor), url(period.kind, period.next_anchor)
|
||||||
|
nav = {"prev": prev_url, "next": next_url, "quick": [
|
||||||
|
{"label": "오늘", "url": url("day", today), "active": period.kind == "day" and period.start == today},
|
||||||
|
{"label": "이번주", "url": url("week", today), "active": period.kind == "week" and period.start <= today <= period.end},
|
||||||
|
{"label": "이번달", "url": url("month", today), "active": period.kind == "month" and period.start <= today <= period.end},
|
||||||
|
{"label": "올해", "url": url("year", today), "active": period.kind == "year" and period.start <= today <= period.end},
|
||||||
|
]}
|
||||||
|
|
||||||
|
share = calc.by_code(cells, codes, period.start, period.end)
|
||||||
|
month = calc.month_summary(month_period.start.year, month_period.start.month, codes, cells)
|
||||||
|
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||||
|
# 칸마다 ROAS — "광고비(ROAS%)" 로 보인다. 행 기간 = 그 날·주·월(합계 행은 선택 기간)
|
||||||
|
for row in table:
|
||||||
|
s = date.fromisoformat(row["from"]) if row.get("from") else period.start
|
||||||
|
e = date.fromisoformat(row["to"]) if row.get("to") else period.end
|
||||||
|
row["roas"] = {c: channel_roas(c, lambda m: sales_sum([m], s, e), row["cells"][c]["gross"],
|
||||||
|
lambda f: file_roas(f, roas_map, amounts, s, e)) for c in codes}
|
||||||
|
row["roas_total"] = roas(sales_sum(total_codes, s, e), row["total"]["gross"]) if total_codes else None
|
||||||
|
m_s, m_e = month_period.start, month_period.end
|
||||||
|
for r in month["rows"]:
|
||||||
|
r["roas"] = channel_roas(r["code"], lambda m: sales_sum([m], m_s, m_e), r["gross"],
|
||||||
|
lambda f: file_roas(f, roas_map, amounts, m_s, m_e))
|
||||||
|
month["total"]["roas"] = roas(sales_sum(total_codes, m_s, m_e), month["total"]["gross"]) if total_codes else None
|
||||||
|
year = calc.year_months(year_period.start.year, codes, cells, today=today)
|
||||||
|
for i, r in enumerate(year["rows"], start=1):
|
||||||
|
s = date(year_period.start.year, i, 1)
|
||||||
|
r["roas"] = None if r.get("future") or not total_codes else roas(sales_sum(total_codes, s, calc.month_end(s)), r["gross"] or 0)
|
||||||
|
year["total"]["roas"] = roas(sales_sum(total_codes, year_period.start, year_period.end), year["total"]["gross"]) if total_codes else None
|
||||||
|
return {
|
||||||
|
"nav": nav,
|
||||||
|
"period": period,
|
||||||
|
"period_kind": period.kind,
|
||||||
|
"today": today.isoformat(),
|
||||||
|
"codes": codes,
|
||||||
|
"names": dict(CHANNEL_NAMES),
|
||||||
|
"kpis": kpis,
|
||||||
|
"table": table,
|
||||||
|
"month": month,
|
||||||
|
"year": year,
|
||||||
|
"roas_basis": {c: roas_basis(c) for c in codes},
|
||||||
|
"detail_channels": sorted(DETAIL_CHANNELS),
|
||||||
|
"chart_daily": calc.daily_series(period, codes, cells),
|
||||||
|
"chart_share": [{"code": c, "name": CHANNEL_NAMES[c], **share[c].as_dict()} for c in codes],
|
||||||
|
# 업로드로 들어온 칸(표시용) — "날짜|채널"
|
||||||
|
"upload_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||||
|
if s == "upload" and period.start <= d <= period.end),
|
||||||
|
# 광고 API(구글 광고 등)로 가져온 칸 — 표시용(초록 숫자)
|
||||||
|
"api_cells": sorted(f"{d.isoformat()}|{c}" for (d, c), s in sources.items()
|
||||||
|
if s == "api" and period.start <= d <= period.end),
|
||||||
|
"upload_channels": [{"code": c, "name": CHANNEL_NAMES[c], "help": UPLOAD_HELP.get(c, "")} for c in PARSERS],
|
||||||
|
"migration_needed": migration_needed,
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""광고 API 가져오기 — 인증정보(perf_ad_credentials) → 광고 연동(ad_sources) → perf_ad_spend(source='api').
|
||||||
|
|
||||||
|
- 광고비 탭 [구글 광고 불러오기](보고 있는 기간) · 매출 자동 업데이트 회차(최근 N일, auto_sync) · 실적 설정 연결 테스트가 쓴다.
|
||||||
|
- 같은 광고 채널은 동시에 한 번만(프로세스 안 잠금) — 두 번째 요청은 바로 "진행 중" 오류.
|
||||||
|
- 저장은 기간 단위 한 트랜잭션(db.replace_ad_api_range): API 가 준 날은 덮어쓰고, 안 준 날은 예전 API 값만 지운다.
|
||||||
|
- 오류 문구는 저장된 비밀값을 가린 뒤 기록·반환한다(security.redact).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from .ad_sources.registry import all_sources, get_source
|
||||||
|
from .adapters.base import STATUS_LABELS, AdapterContext, AdapterError
|
||||||
|
from .credentials import CredentialService
|
||||||
|
from .db import AdCredentialTable
|
||||||
|
from .security.redact import redact_text
|
||||||
|
|
||||||
|
logger = logging.getLogger("performance.ad_sync")
|
||||||
|
|
||||||
|
AD_NS = "ad:" # 광고 인증정보 암호문 이름 공간(credentials.aad_for)
|
||||||
|
AD_MESSAGE_MAX = 1200 # 광고 연동 오류 문구 길이 한도(비밀값 가린 뒤)
|
||||||
|
_locks: dict[str, threading.Lock] = {}
|
||||||
|
_locks_guard = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _lock(code: str) -> threading.Lock:
|
||||||
|
with _locks_guard:
|
||||||
|
return _locks.setdefault(code, threading.Lock())
|
||||||
|
|
||||||
|
|
||||||
|
class AdSyncBusy(Exception):
|
||||||
|
"""같은 광고 채널 가져오기가 이미 진행 중."""
|
||||||
|
|
||||||
|
|
||||||
|
def ad_credentials(store: Any, ring_loader: Callable[[], Any]) -> CredentialService:
|
||||||
|
"""광고 API 인증정보 서비스 — 쇼핑몰과 같은 서비스, 저장소만 광고 표."""
|
||||||
|
return CredentialService(AdCredentialTable(store), ring_loader, aad_ns=AD_NS)
|
||||||
|
|
||||||
|
|
||||||
|
class AdSyncService:
|
||||||
|
def __init__(self, store: Any, creds: CredentialService) -> None:
|
||||||
|
self._store = store
|
||||||
|
self._creds = creds
|
||||||
|
|
||||||
|
def configured(self) -> dict[str, bool]:
|
||||||
|
return self._creds.configured_codes(list(all_sources()))
|
||||||
|
|
||||||
|
def _ctx(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||||
|
cleared: set[str] | None = None) -> AdapterContext:
|
||||||
|
trial = values is not None or bool(cleared)
|
||||||
|
acc = self._creds.accessor(code, overrides=values, persist=not trial, user=user, cleared=cleared)
|
||||||
|
return AdapterContext(code=code, credentials=acc, timeout_sec=30.0)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _message(exc: Exception, ctx: AdapterContext) -> str:
|
||||||
|
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
|
||||||
|
# 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 300자에서 자르면 안내가 잘린다(2026-10-16 메타 #200 진단)
|
||||||
|
return redact_text(str(getattr(exc, "message", "") or exc), known, max_len=AD_MESSAGE_MAX)
|
||||||
|
|
||||||
|
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||||
|
cleared: set[str] | None = None) -> dict[str, Any]:
|
||||||
|
"""values 가 있으면 저장하지 않은 새 입력값(빈 칸은 저장값)으로 시험, cleared = 화면에서 비운 항목(빈 값으로) —
|
||||||
|
그때는 상태를 기록하지 않는다."""
|
||||||
|
src = get_source(code)
|
||||||
|
if src is None:
|
||||||
|
return {"ok": False, "status": "api_error", "label": STATUS_LABELS["api_error"], "message": "알 수 없는 광고 연동입니다."}
|
||||||
|
ctx = self._ctx(code, values=values, user=user, cleared=cleared)
|
||||||
|
trial = bool(values) or bool(cleared)
|
||||||
|
try:
|
||||||
|
src.require_configured(ctx)
|
||||||
|
msg = src.test_connection(ctx)
|
||||||
|
ok, status = True, "ok"
|
||||||
|
except AdapterError as exc:
|
||||||
|
ok, status, msg = False, exc.status, self._message(exc, ctx)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 예상 못 한 오류도 화면에는 짧게
|
||||||
|
logger.exception("ad test failed: %s", code)
|
||||||
|
ok, status, msg = False, "api_error", f"연결 테스트 중 오류: {type(exc).__name__}"
|
||||||
|
if not trial:
|
||||||
|
self._store.record_ad_status(code, status=status, ok=ok, error="" if ok else msg, kind="test")
|
||||||
|
return {"ok": ok, "status": status, "label": STATUS_LABELS.get(status, status), "message": msg,
|
||||||
|
"unsaved": trial}
|
||||||
|
|
||||||
|
def sync(self, code: str, start: date, end: date, *, user: str = "") -> dict[str, Any]:
|
||||||
|
"""기간 가져오기 → 저장. 결과 {ok, days, total, from, to} 또는 {ok: False, status, message}. 진행 중이면 AdSyncBusy."""
|
||||||
|
src = get_source(code)
|
||||||
|
if src is None:
|
||||||
|
raise KeyError(code)
|
||||||
|
lock = _lock(code)
|
||||||
|
if not lock.acquire(blocking=False):
|
||||||
|
raise AdSyncBusy(f"{src.name} 가져오기가 이미 진행 중입니다. 잠시 뒤 다시 누르세요.")
|
||||||
|
try:
|
||||||
|
ctx = self._ctx(code, user=user)
|
||||||
|
try:
|
||||||
|
src.require_configured(ctx)
|
||||||
|
days = src.fetch_days(ctx, start, end)
|
||||||
|
except AdapterError as exc:
|
||||||
|
msg = self._message(exc, ctx)
|
||||||
|
self._store.record_ad_status(code, status=exc.status, ok=False, error=msg, kind="sync")
|
||||||
|
return {"ok": False, "code": code, "name": src.name, "status": exc.status,
|
||||||
|
"label": STATUS_LABELS.get(exc.status, exc.status), "message": msg}
|
||||||
|
saved = self._store.replace_ad_api_range(
|
||||||
|
code, start, end, [(d.day, d.amount, d.roas, d.metrics) for d in days], user=user or "광고 API")
|
||||||
|
self._store.record_ad_status(code, status="ok", ok=True, kind="sync")
|
||||||
|
return {"ok": True, "code": code, "name": src.name, "days": saved, "total": sum(d.amount for d in days),
|
||||||
|
"from": start.isoformat(), "to": end.isoformat()}
|
||||||
|
finally:
|
||||||
|
lock.release()
|
||||||
|
|
||||||
|
def sync_all(self, start: date, end: date, *, user: str = "") -> list[dict[str, Any]]:
|
||||||
|
"""설정이 끝난 광고 연동 전부(자동 업데이트 회차). 채널별로 실패를 격리한다."""
|
||||||
|
out = []
|
||||||
|
for code, ok in self.configured().items():
|
||||||
|
if not ok:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
out.append(self.sync(code, start, end, user=user))
|
||||||
|
except AdSyncBusy as exc:
|
||||||
|
out.append({"ok": False, "code": code, "skipped": True, "message": str(exc)})
|
||||||
|
except Exception as exc: # noqa: BLE001 — 다음 채널은 계속
|
||||||
|
logger.exception("ad sync failed: %s", code)
|
||||||
|
out.append({"ok": False, "code": code, "message": f"가져오기 중 오류: {type(exc).__name__}"})
|
||||||
|
return out
|
||||||
@@ -33,6 +33,7 @@ STATUS_LABELS: dict[str, str] = {
|
|||||||
"unknown": "확인 전",
|
"unknown": "확인 전",
|
||||||
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
"disabled": "사용 중지", # DB 에는 저장하지 않는 화면 전용 상태(쇼핑몰 사용 OFF)
|
||||||
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
"cancelled": "취소됨", # 화면 전용 — 매출 업데이트 창에서 [업데이트 취소](연결 상태는 바꾸지 않음)
|
||||||
|
"manual": "수동 입력", # 화면 전용 — API 없이 수동 입력만 쓰는 쇼핑몰(manual_only)
|
||||||
}
|
}
|
||||||
|
|
||||||
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
EVENT_TYPES = ("SALE", "CANCEL", "RETURN", "ADJUST")
|
||||||
@@ -82,6 +83,7 @@ class CredentialField:
|
|||||||
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
|
"""설정 화면 입력칸 하나. secret=True 면 저장 후 값을 화면으로 다시 보내지 않는다.
|
||||||
|
|
||||||
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
|
internal=True 는 화면에 안 보이는 내부 값(access/refresh token 등) — 어댑터가 직접 저장.
|
||||||
|
multiline=True 면 여러 줄 입력칸(서비스 계정 JSON 키 등).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
key: str
|
key: str
|
||||||
@@ -91,6 +93,7 @@ class CredentialField:
|
|||||||
help: str = ""
|
help: str = ""
|
||||||
placeholder: str = ""
|
placeholder: str = ""
|
||||||
internal: bool = False
|
internal: bool = False
|
||||||
|
multiline: bool = False
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -128,6 +131,16 @@ class SaleEvent:
|
|||||||
raise ValueError("취소/반품 금액은 음수(또는 0)여야 합니다.")
|
raise ValueError("취소/반품 금액은 음수(또는 0)여야 합니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def credential_fingerprint(credentials: Any, keys: Iterable[str]) -> str:
|
||||||
|
"""토큰을 발급한 인증정보 묶음의 지문(SHA-256 16진수) — 원문은 남기지 않는다(2026-10-15 검토 F04).
|
||||||
|
저장된 토큰은 이 지문이 지금 인증정보(연결 테스트의 새 입력값 포함)와 같을 때만 다시 쓴다 —
|
||||||
|
계정·키를 바꾸면 이전 계정 토큰을 쓰지 않고, 같은 값을 다시 저장하면 토큰을 새로 받지 않는다."""
|
||||||
|
import hashlib # noqa: WPS433
|
||||||
|
|
||||||
|
raw = "\x1f".join(f"{k}={(credentials.get(k) or '').strip()}" for k in keys)
|
||||||
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
class CredentialAccessor(Protocol):
|
class CredentialAccessor(Protocol):
|
||||||
def get(self, key: str) -> str: ...
|
def get(self, key: str) -> str: ...
|
||||||
|
|
||||||
@@ -175,6 +188,8 @@ class MarketplaceAdapter(ABC):
|
|||||||
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
|
auth_type: str = "api_key" # api_key / oauth / shared(공통 연동 계층 재사용)
|
||||||
docs_url: str = ""
|
docs_url: str = ""
|
||||||
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
|
implemented: bool = False # 실제 수집(fetch)이 구현됐는가
|
||||||
|
# True 면 API 연동이 없는 수동 입력 전용 쇼핑몰 — 매출 업데이트에서 빠지고, 인증 설정·연결 테스트가 없다.
|
||||||
|
manual_only: bool = False
|
||||||
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
|
# True 면 동기화 때 그 기간(sales_date)의 이 쇼핑몰 실데이터를 지우고 새로 넣는다(한 트랜잭션).
|
||||||
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
|
# 쇼핑몰 API 가 "기간 안 결제·환불"을 빠짐없이 돌려줄 때만 켠다 — 규칙이 바뀌거나
|
||||||
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
|
# 주문이 사라져도 예전 행이 남지 않는다. False 면 같은 사건 ID 만 덮어쓴다(upsert).
|
||||||
|
|||||||
@@ -8,12 +8,23 @@
|
|||||||
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 —
|
||||||
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
· 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다.
|
||||||
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
· 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다.
|
||||||
연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다.
|
|
||||||
|
|
||||||
매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다.
|
매출 수집 — 맞출 화면: WING → 비즈니스 인사이트 → **판매분석**(판매자배송 + 로켓그로스, 날짜 선택) 의 "매출(원)"
|
||||||
· 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음)
|
(2026-10-12 사용자 지정). 판매분석 자체를 주는 Open API 는 없다(2026-10-12 developers.coupang.com API 목록 확인) —
|
||||||
· 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다.
|
그래서 주문 API 두 개를 결제일(한국 시간)로 합친다:
|
||||||
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계.
|
- 판매자배송: 발주서 목록(일단위 페이징) GET /v2/providers/openapi/apis/api/v5/vendors/{vendorId}/ordersheets
|
||||||
|
?createdAtFrom=yyyy-mm-dd+09:00&createdAtTo=…&status=…&maxPerPage=50&nextToken=
|
||||||
|
— 주문일 기준·한 번에 31일까지·상태(ACCEPT·INSTRUCT·DEPARTURE·DELIVERING·FINAL_DELIVERY·NONE_TRACKING)마다 따로.
|
||||||
|
결제일(paidAt)로 다시 거른다(주문일 하루 앞부터 조회). 줄 금액 = orderPrice(판매가 × 수량, 쿠폰 할인 전).
|
||||||
|
완료된 반품·결제 전 취소된 발주서는 이 목록에 없다(쿠팡 안내).
|
||||||
|
- 로켓그로스: 주문 목록 GET /v2/providers/rg_open_api/apis/api/v1/vendors/{vendorId}/rg/orders
|
||||||
|
?paidDateFrom=yyyymmdd&paidDateTo=yyyymmdd&nextToken= — 결제일 기준·30일까지·분당 50회.
|
||||||
|
줄 금액 = unitSalesPrice × salesQuantity. 쿠팡 안내상 **출고된 주문만** 나온다(오늘 주문은 출고 뒤에 잡힐 수 있음).
|
||||||
|
- SALE = 주문 하나(판매자배송 `coupang:{orderId}`, 로켓그로스 `coupang:rg:{orderId}`), 날짜 = 결제일.
|
||||||
|
결제 뒤 취소된 줄(canceled·cancelCount)도 결제일 매출에 둔다(지난 날짜가 나중에 줄지 않게) — 금액은 참고로 따로.
|
||||||
|
판매분석 "매출" 의 정확한 정의(할인 전·후, 취소 포함 여부)는 공개 문서가 없어 **설정 → 쇼핑몰 원본 데이터 확인**
|
||||||
|
(reconcile)의 날짜별 후보 금액을 WING 숫자와 비교해 확정한다. 구매자 이름·연락처·주소는 저장·표시하지 않는다.
|
||||||
|
로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 여기에 넣지 않는다.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -21,19 +32,53 @@ from __future__ import annotations
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
from typing import Any, Iterable
|
||||||
from urllib.parse import quote, urlencode
|
from urllib.parse import quote, urlencode
|
||||||
|
|
||||||
from .base import (
|
from .base import (
|
||||||
AdapterContext,
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
ApiError,
|
ApiError,
|
||||||
AuthFailed,
|
AuthFailed,
|
||||||
CredentialField,
|
CredentialField,
|
||||||
MarketplaceAdapter,
|
MarketplaceAdapter,
|
||||||
NotConfigured,
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
)
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
HOST = "https://api-gateway.coupang.com"
|
HOST = "https://api-gateway.coupang.com"
|
||||||
|
ORDERS_PATH = "/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets"
|
||||||
|
RG_ORDERS_PATH = "/v2/providers/rg_open_api/apis/api/v1/vendors/{vendor}/rg/orders"
|
||||||
|
EVENT_PREFIX = "coupang:"
|
||||||
|
RG_PREFIX = "coupang:rg:"
|
||||||
|
STATUSES = ("ACCEPT", "INSTRUCT", "DEPARTURE", "DELIVERING", "FINAL_DELIVERY", "NONE_TRACKING")
|
||||||
|
STATUS_KO = {"ACCEPT": "결제완료", "INSTRUCT": "상품준비중", "DEPARTURE": "배송지시", "DELIVERING": "배송중",
|
||||||
|
"FINAL_DELIVERY": "배송완료", "NONE_TRACKING": "업체직송", "RG": "로켓그로스"}
|
||||||
|
ORDER_SPAN_DAYS = 31 # 발주서 목록 한 번에 조회할 수 있는 기간(시작·끝 포함)
|
||||||
|
RG_SPAN_DAYS = 30 # 로켓그로스 주문 목록 한 번에 조회할 수 있는 기간
|
||||||
|
PAGE_SIZE = 50
|
||||||
|
MAX_PAGES = 400 # 한 조회 2만 건 — 무한 반복 방지
|
||||||
|
CALL_INTERVAL_SEC = 0.25 # 발주서 목록 호출 간격
|
||||||
|
RG_CALL_INTERVAL_SEC = 1.25 # 로켓그로스 분당 50회 제한
|
||||||
|
RETRY_429 = 3
|
||||||
|
RETRY_TIMEOUT_1DAY = 2 # 하루 구간도 시간 초과면 잠깐 쉬고 다시 부르는 횟수
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
KST_OFFSET = timedelta(hours=9)
|
||||||
|
|
||||||
|
|
||||||
|
class GatewayTimeout(ApiError):
|
||||||
|
"""쿠팡 서버가 시간 안에 답하지 못함(502·503·504·응답 시간 초과) — 조회 기간을 줄이면 대개 풀린다."""
|
||||||
|
|
||||||
|
|
||||||
|
class TooManyPages(ApiError):
|
||||||
|
"""한 번 조회가 끝까지 받았는지 확인되지 않음(쪽 수 상한·커서 반복) — 조회 기간을 줄여 다시 부른다(F05)."""
|
||||||
|
|
||||||
|
|
||||||
|
# 원본 확인·저장에서 통째로 빼는 항목(구매자·수령자·통관 정보·배송 메모·직접 입력 항목)
|
||||||
|
PERSONAL_KEYS = frozenset({"orderer", "receiver", "overseaShippingInfoDto", "parcelPrintMessage"})
|
||||||
|
PERSONAL_ITEM_KEYS = frozenset({"etcInfoHeader", "etcInfoValue", "etcInfoValues"})
|
||||||
|
|
||||||
|
|
||||||
def signed_date(now: float | None = None) -> str:
|
def signed_date(now: float | None = None) -> str:
|
||||||
@@ -54,14 +99,163 @@ def build_query(params: dict[str, Any]) -> str:
|
|||||||
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":")
|
||||||
|
|
||||||
|
|
||||||
|
def _won(value: Any) -> int:
|
||||||
|
"""금액 → 원 정수. 쿠팡 Money({"units": 15000, "nanos": 0})·숫자·문자열("27800") 모두."""
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return _won(value.get("units")) + int(round((_num(value.get("nanos")) or 0) / 1e9))
|
||||||
|
n = _num(value)
|
||||||
|
return int(round(n)) if n is not None else 0
|
||||||
|
|
||||||
|
|
||||||
|
def _num(value: Any) -> float | None:
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return float(str(value).replace(",", "").strip() or 0)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _kst_day(value: Any) -> date | None:
|
||||||
|
"""결제 시각 → 한국 날짜. ISO 문자열("2025-08-01T10:06:12+09:00", 시간대 없으면 한국 시간) 또는
|
||||||
|
밀리초 타임스탬프(1746093162000, 로켓그로스)."""
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
n = _num(value) if not isinstance(value, str) or value.strip().isdigit() else None
|
||||||
|
if n is not None:
|
||||||
|
secs = n / 1000 if n > 1e11 else n
|
||||||
|
return (datetime.fromtimestamp(secs, tz=timezone.utc) + KST_OFFSET).date()
|
||||||
|
s = str(value).strip().replace("Z", "+00:00")
|
||||||
|
try:
|
||||||
|
dt = datetime.fromisoformat(s if "T" in s or " " in s else s[:10])
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(s[:10])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is not None:
|
||||||
|
dt = (dt - dt.utcoffset()).replace(tzinfo=None) + KST_OFFSET # type: ignore[operator]
|
||||||
|
return dt.date()
|
||||||
|
|
||||||
|
|
||||||
|
def spans(start: date, end: date, days: int) -> list[tuple[date, date]]:
|
||||||
|
"""[start, end] 를 days 일(시작·끝 포함) 이하 구간으로 자른다."""
|
||||||
|
out, d = [], start
|
||||||
|
while d <= end:
|
||||||
|
e = min(end, d + timedelta(days=days - 1))
|
||||||
|
out.append((d, e))
|
||||||
|
d = e + timedelta(days=1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def safe_order(o: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""개인정보 항목을 뺀 발주서(원본 확인·저장용)."""
|
||||||
|
out = {k: v for k, v in o.items() if k not in PERSONAL_KEYS}
|
||||||
|
if isinstance(out.get("orderItems"), list):
|
||||||
|
out["orderItems"] = [{k: v for k, v in it.items() if k not in PERSONAL_ITEM_KEYS}
|
||||||
|
for it in out["orderItems"] if isinstance(it, dict)]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def line_records(o: dict[str, Any]) -> list[dict[str, str]]:
|
||||||
|
"""발주서 하나 → 줄(orderItems)마다 평평한 기록 하나 — 원본 확인 표의 항목별 합계용."""
|
||||||
|
base = flatten({k: v for k, v in safe_order(o).items() if k != "orderItems"})
|
||||||
|
items = safe_order(o).get("orderItems") or [{}]
|
||||||
|
return [{**base, **flatten(it, "orderItems")} for it in items]
|
||||||
|
|
||||||
|
|
||||||
|
def seller_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""판매자배송 발주서 → 결제일이 [start, end] 인 줄. 같은 발주서가 두 번 와도(상태 사이 이동) 한 번만."""
|
||||||
|
seen: set[tuple[str, str, str, str]] = set()
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for o in orders:
|
||||||
|
oid = str(o.get("orderId") or "")
|
||||||
|
day = _kst_day(o.get("paidAt") or o.get("orderedAt"))
|
||||||
|
if not oid or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
box = str(o.get("shipmentBoxId") or "")
|
||||||
|
first = len(out)
|
||||||
|
for it in o.get("orderItems") or []:
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
key = (oid, box, str(it.get("vendorItemId") or ""), str(it.get("sequenceNo") or ""))
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
qty = _won(it.get("shippingCount"))
|
||||||
|
price = _won(it.get("orderPrice")) or _won(it.get("salesPrice")) * qty
|
||||||
|
cancel_qty = _won(it.get("cancelCount")) + _won(it.get("holdCountForCancel"))
|
||||||
|
canceled = bool(it.get("canceled")) or (qty > 0 and cancel_qty >= qty)
|
||||||
|
cancel_amt = price if canceled else (_won(it.get("salesPrice")) * min(cancel_qty, qty) if cancel_qty else 0)
|
||||||
|
out.append({
|
||||||
|
"orderId": oid, "_day": day, "order_day": _kst_day(o.get("orderedAt")), "status": str(o.get("status") or ""),
|
||||||
|
"amount": price, "discount": _won(it.get("discountPrice")), "canceled": cancel_amt, "qty": qty,
|
||||||
|
"name": str(it.get("sellerProductName") or it.get("vendorItemName") or ""),
|
||||||
|
"opt": str(it.get("sellerProductItemName") or ""), "ship": 0,
|
||||||
|
})
|
||||||
|
# 배송비는 발주서(묶음 배송)마다 한 번 — 그 발주서의 첫 새 줄에(참고용, 매출 제외). 같은 발주서가 또 오면 새 줄이 없어 안 더함
|
||||||
|
if len(out) > first:
|
||||||
|
out[first]["ship"] += _won(o.get("shippingPrice")) + _won(o.get("remotePrice"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def rg_lines(orders: Iterable[dict[str, Any]], start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""로켓그로스 주문 → 결제일이 [start, end] 인 줄. 금액 = 단가 × 수량."""
|
||||||
|
seen: set[tuple[str, str, int]] = set()
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for o in orders:
|
||||||
|
oid = str(o.get("orderId") or "")
|
||||||
|
day = _kst_day(o.get("paidAt"))
|
||||||
|
if not oid or day is None or not (start <= day <= end):
|
||||||
|
continue
|
||||||
|
for i, it in enumerate(o.get("orderItems") or []):
|
||||||
|
if not isinstance(it, dict):
|
||||||
|
continue
|
||||||
|
key = (oid, str(it.get("vendorItemId") or ""), i)
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
qty = _won(it.get("salesQuantity"))
|
||||||
|
out.append({"orderId": oid, "_day": day, "order_day": day, "status": "RG",
|
||||||
|
"amount": _won(it.get("unitSalesPrice")) * qty, "discount": 0, "canceled": 0, "qty": qty,
|
||||||
|
"name": str(it.get("productName") or ""), "opt": "", "ship": 0})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def group_lines(lines: Iterable[dict[str, Any]], prefix: str) -> dict[str, dict[str, Any]]:
|
||||||
|
"""줄 → 주문 하나(외부 사건 ID 기준)."""
|
||||||
|
orders: dict[str, dict[str, Any]] = {}
|
||||||
|
for ln in lines:
|
||||||
|
eid = f"{prefix}{ln['orderId']}"
|
||||||
|
o = orders.setdefault(eid, {"event_id": eid, "orderId": ln["orderId"], "_day": ln["_day"],
|
||||||
|
"order_day": ln.get("order_day"), "amount": 0, "discount": 0, "canceled": 0,
|
||||||
|
"ship": 0, "qty": 0, "names": [], "opt": "", "statuses": []})
|
||||||
|
for k in ("amount", "discount", "canceled", "ship", "qty"):
|
||||||
|
o[k] += int(ln.get(k) or 0)
|
||||||
|
if ln["name"] and ln["name"] not in o["names"]:
|
||||||
|
o["names"].append(ln["name"])
|
||||||
|
o["opt"] = o["opt"] or ln.get("opt") or ""
|
||||||
|
if ln["status"] and ln["status"] not in o["statuses"]:
|
||||||
|
o["statuses"].append(ln["status"])
|
||||||
|
return orders
|
||||||
|
|
||||||
|
|
||||||
class CoupangAdapter(MarketplaceAdapter):
|
class CoupangAdapter(MarketplaceAdapter):
|
||||||
code = "coupang"
|
code = "coupang"
|
||||||
name = "쿠팡"
|
name = "쿠팡(윙)"
|
||||||
auth_type = "api_key"
|
auth_type = "api_key"
|
||||||
docs_url = "https://developers.coupangcorp.com/"
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://developers.coupang.com/"
|
||||||
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
|
||||||
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
|
||||||
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
|
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인). 매출은 판매자배송 + 로켓그로스 주문을 "
|
||||||
|
"결제일로 합칩니다(WING 비즈니스 인사이트 → 판매분석 '매출'과 비교).")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
self._last_rg_call = 0.0
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
return [
|
return [
|
||||||
@@ -71,42 +265,288 @@ class CoupangAdapter(MarketplaceAdapter):
|
|||||||
]
|
]
|
||||||
|
|
||||||
# ── 호출 ──────────────────────────────────────────────
|
# ── 호출 ──────────────────────────────────────────────
|
||||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
def _vendor(self, ctx: AdapterContext) -> str:
|
||||||
|
v = ctx.credentials.get("vendor_id").strip()
|
||||||
|
if not v:
|
||||||
|
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||||
|
return v
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> dict[str, Any]:
|
||||||
|
"""GET — 호출 간격 유지(로켓그로스는 분당 50회), 429 는 잠깐 쉬고 다시."""
|
||||||
import httpx # 지연 import
|
import httpx # 지연 import
|
||||||
|
|
||||||
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip()
|
||||||
if not (access and secret):
|
if not (access and secret):
|
||||||
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.")
|
||||||
query = build_query(params)
|
query = build_query(params)
|
||||||
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
what = "로켓그로스 주문" if rg else "발주서"
|
||||||
"Content-Type": "application/json;charset=UTF-8"}
|
for attempt in range(RETRY_429 + 1):
|
||||||
try:
|
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||||
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
gap = RG_CALL_INTERVAL_SEC if rg else CALL_INTERVAL_SEC
|
||||||
except httpx.HTTPError as exc:
|
last = self._last_rg_call if rg else self._last_call
|
||||||
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
wait = gap - (time.monotonic() - last)
|
||||||
try:
|
if wait > 0:
|
||||||
body = res.json()
|
time.sleep(wait)
|
||||||
except ValueError:
|
headers = {"Authorization": authorization("GET", path, query, access, secret),
|
||||||
body = {}
|
"Content-Type": "application/json;charset=UTF-8"}
|
||||||
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()
|
try:
|
||||||
if res.status_code in (401, 403):
|
res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec)
|
||||||
raise AuthFailed(
|
except httpx.TimeoutException as exc:
|
||||||
f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
raise GatewayTimeout(f"쿠팡 {what} 응답 시간 초과: {type(exc).__name__}") from None
|
||||||
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
except httpx.HTTPError as exc:
|
||||||
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None
|
||||||
if res.status_code >= 400:
|
finally:
|
||||||
raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}")
|
if rg:
|
||||||
return body
|
self._last_rg_call = time.monotonic()
|
||||||
|
else:
|
||||||
|
self._last_call = time.monotonic()
|
||||||
|
if res.status_code == 429 and attempt < RETRY_429:
|
||||||
|
time.sleep(2.0 * (2 ** attempt))
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
body = res.json()
|
||||||
|
except ValueError:
|
||||||
|
if res.status_code < 400:
|
||||||
|
# HTTP 200 이어도 JSON 이 아니면(점검·프록시 안내 페이지 등) 수집 실패 — 빈 목록으로 보면 기간 교체 때
|
||||||
|
# 그 기간 매출이 지워진다(2026-10-15 검토 F01). 오류 응답(4xx·5xx)은 아래에서 글자로 안내한다.
|
||||||
|
raise ApiError(f"쿠팡 {what} 응답이 JSON 이 아닙니다(HTTP {res.status_code}) — 점검 중일 수 있어 "
|
||||||
|
"저장하지 않았습니다. 잠시 뒤 다시 시도하세요.") from None
|
||||||
|
body = {}
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
body = {"data": body}
|
||||||
|
msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip()[:300]
|
||||||
|
if res.status_code in (401, 403):
|
||||||
|
raise AuthFailed(
|
||||||
|
f"쿠팡 {what} 조회 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 "
|
||||||
|
"발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 "
|
||||||
|
"넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).")
|
||||||
|
if res.status_code == 429:
|
||||||
|
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
if res.status_code in (502, 503, 504):
|
||||||
|
raise GatewayTimeout(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||||
|
if res.status_code >= 400:
|
||||||
|
raise ApiError(f"쿠팡 {what} API 오류({res.status_code}): {msg}")
|
||||||
|
code = body.get("code")
|
||||||
|
if isinstance(code, int) and code >= 400:
|
||||||
|
raise ApiError(f"쿠팡 {what} API 오류({code}): {msg}")
|
||||||
|
return body
|
||||||
|
raise ApiError(f"쿠팡 {what} 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _page_rows(body: dict[str, Any], what: str) -> list[dict[str, Any]]:
|
||||||
|
"""한 쪽의 주문 목록 — `data` 가 목록이어야 한다. 목록이 아니면 빈 목록(주문 0건)과 구분해 실패로(F01):
|
||||||
|
`data` 가 없거나 다른 형식이면 오류, `data: null` 은 성공 표시(code 200·OK/SUCCESS)가 함께 있을 때만 빈 목록."""
|
||||||
|
data = body.get("data")
|
||||||
|
if isinstance(data, list):
|
||||||
|
return [r for r in data if isinstance(r, dict)]
|
||||||
|
code, msg = body.get("code"), str(body.get("message") or "").strip().upper()
|
||||||
|
if "data" in body and data is None and (code in (200, "200") or msg in ("OK", "SUCCESS")):
|
||||||
|
return []
|
||||||
|
raise ApiError(f"쿠팡 {what} 응답 형식이 예상과 다릅니다(주문 목록 data 없음) — 저장하지 않았습니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _pages(self, ctx: AdapterContext, path: str, params: dict[str, Any], *, rg: bool = False) -> list[dict[str, Any]]:
|
||||||
|
"""nextToken 으로 끝까지 받는다. 끝(다음 쪽 없음)을 확인하지 못하면 TooManyPages — 일부만 받은 목록으로
|
||||||
|
기간을 교체하지 않게(2026-10-15 검토 F05). 부르는 쪽이 기간을 나눠 다시 부른다.
|
||||||
|
- MAX_PAGES 를 다 써도 다음 쪽이 남음 · 같은 nextToken 이 다시 옴(커서 반복) → TooManyPages
|
||||||
|
- 빈 쪽인데 다음 쪽이 있으면 따라간다(예전엔 거기서 끝난 것으로 봤다)"""
|
||||||
|
what = "로켓그로스 주문" if rg else "발주서"
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token: str | None = None
|
||||||
|
seen: set[str] = set()
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, path, {**params, "nextToken": token} if token else params, rg=rg)
|
||||||
|
out.extend(self._page_rows(body, what))
|
||||||
|
nxt = str(body.get("nextToken") or "").strip()
|
||||||
|
if not nxt:
|
||||||
|
return out # 마지막 쪽 확인
|
||||||
|
if nxt in seen:
|
||||||
|
raise TooManyPages(f"쿠팡 {what} 다음 쪽 표시가 반복돼 끝까지 받았는지 확인할 수 없습니다 — 저장하지 않았습니다.")
|
||||||
|
seen.add(nxt)
|
||||||
|
token = nxt
|
||||||
|
raise TooManyPages(f"쿠팡 {what} 한 번 조회가 {MAX_PAGES}쪽을 넘었습니다 — 일부만 받은 채 저장하지 않았습니다.")
|
||||||
|
|
||||||
|
def _seller_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""판매자배송 발주서 — 주문일 [start-1, end] 를 31일씩 × 상태 6개. 결제일 필터는 seller_lines 가.
|
||||||
|
|
||||||
|
건수가 많은 상태(배송완료 등)는 31일을 한 번에 부르면 쿠팡 서버가 504(시간 초과)를 낸다 — 그러면 그 구간을
|
||||||
|
반으로 줄여 다시 부르고(하루까지), 줄인 크기는 같은 상태의 다음 구간에도 그대로 쓴다(매번 31일로 실패하지 않게)."""
|
||||||
|
path = ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
size_by_status = {st: ORDER_SPAN_DAYS for st in STATUSES}
|
||||||
|
for a, b in spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS):
|
||||||
|
for st in STATUSES:
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
d, tries = a, 0
|
||||||
|
while d <= b:
|
||||||
|
e = min(b, d + timedelta(days=size_by_status[st] - 1))
|
||||||
|
try:
|
||||||
|
part = self._pages(ctx, path, {"createdAtFrom": f"{d.isoformat()}+09:00",
|
||||||
|
"createdAtTo": f"{e.isoformat()}+09:00",
|
||||||
|
"status": st, "maxPerPage": PAGE_SIZE})
|
||||||
|
except GatewayTimeout as exc:
|
||||||
|
if size_by_status[st] > 1:
|
||||||
|
size_by_status[st] = max(1, size_by_status[st] // 2)
|
||||||
|
continue
|
||||||
|
tries += 1
|
||||||
|
if tries <= RETRY_TIMEOUT_1DAY:
|
||||||
|
time.sleep(3.0 * tries)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루도 시간 초과, 상태 {st}] "
|
||||||
|
"— 잠시 뒤 다시 시도하세요.") from None
|
||||||
|
except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패
|
||||||
|
if size_by_status[st] > 1:
|
||||||
|
size_by_status[st] = max(1, size_by_status[st] // 2)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [주문일 {d.isoformat()} 하루, 상태 {st}]") from None
|
||||||
|
except ApiError as exc: # 긴 기간을 나눠 부를 때 어느 구간에서 막혔는지 알 수 있게
|
||||||
|
raise ApiError(f"{exc.message} [주문일 {d.isoformat()}~{e.isoformat()}, 상태 {st}]") from None
|
||||||
|
rows.extend(part)
|
||||||
|
d, tries = e + timedelta(days=1), 0
|
||||||
|
out.extend(rows)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _rg_orders(self, ctx: AdapterContext, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
path = RG_ORDERS_PATH.format(vendor=self._vendor(ctx))
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for a, b in spans(start, end, RG_SPAN_DAYS):
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
d, size, tries = a, RG_SPAN_DAYS, 0
|
||||||
|
while d <= b: # 시간 초과면 판매자배송과 같이 구간을 반으로(하루까지)
|
||||||
|
e = min(b, d + timedelta(days=size - 1))
|
||||||
|
try:
|
||||||
|
part = self._pages(ctx, path, {"paidDateFrom": d.strftime("%Y%m%d"),
|
||||||
|
"paidDateTo": e.strftime("%Y%m%d")}, rg=True)
|
||||||
|
except GatewayTimeout as exc:
|
||||||
|
if size > 1:
|
||||||
|
size = max(1, size // 2)
|
||||||
|
continue
|
||||||
|
tries += 1
|
||||||
|
if tries <= RETRY_TIMEOUT_1DAY:
|
||||||
|
time.sleep(3.0 * tries)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루도 시간 초과] "
|
||||||
|
"— 잠시 뒤 다시 시도하세요.") from None
|
||||||
|
except TooManyPages as exc: # 끝까지 못 받음 — 구간을 반으로(하루까지), 하루도 넘치면 실패
|
||||||
|
if size > 1:
|
||||||
|
size = max(1, size // 2)
|
||||||
|
continue
|
||||||
|
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()} 하루]") from None
|
||||||
|
except ApiError as exc:
|
||||||
|
raise ApiError(f"{exc.message} [로켓그로스 결제일 {d.isoformat()}~{e.isoformat()}]") from None
|
||||||
|
rows.extend(part)
|
||||||
|
d, tries = e + timedelta(days=1), 0
|
||||||
|
out.extend(rows)
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _plan(self, ctx: AdapterContext, start: date, end: date) -> None:
|
||||||
|
ctx.progress.plan(len(spans(start - timedelta(days=1), end, ORDER_SPAN_DAYS)) * len(STATUSES)
|
||||||
|
+ len(spans(start, end, RG_SPAN_DAYS)), "조회")
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
self._plan(ctx, start, end)
|
||||||
|
seller = seller_lines(self._seller_orders(ctx, start, end), start, end)
|
||||||
|
rg = rg_lines(self._rg_orders(ctx, start, end), start, end)
|
||||||
|
yield from group_lines(seller, EVENT_PREFIX).values()
|
||||||
|
yield from group_lines(rg, RG_PREFIX).values()
|
||||||
|
|
||||||
|
def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
oid, day = str(o.get("orderId") or ""), o.get("_day")
|
||||||
|
if not oid or day is None:
|
||||||
|
return []
|
||||||
|
names = o.get("names") or []
|
||||||
|
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||||
|
statuses = [STATUS_KO.get(s, s) for s in o.get("statuses") or []]
|
||||||
|
if o.get("canceled"):
|
||||||
|
statuses.append("취소 포함")
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type="SALE", external_event_id=str(o["event_id"]), external_order_id=oid,
|
||||||
|
order_date=o.get("order_day"), payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)),
|
||||||
|
product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0),
|
||||||
|
discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50],
|
||||||
|
)]
|
||||||
|
|
||||||
def test_connection(self, ctx: AdapterContext) -> str:
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
from app.timezone import today_kst # noqa: WPS433
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
self.authenticate(ctx)
|
self.authenticate(ctx)
|
||||||
vendor = ctx.credentials.get("vendor_id").strip()
|
vendor = self._vendor(ctx)
|
||||||
today = today_kst().isoformat()
|
today = today_kst()
|
||||||
body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets",
|
body = self._get(ctx, ORDERS_PATH.format(vendor=vendor),
|
||||||
{"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00",
|
{"createdAtFrom": f"{today.isoformat()}+09:00", "createdAtTo": f"{today.isoformat()}+09:00",
|
||||||
"status": "ACCEPT", "maxPerPage": 1})
|
"status": "ACCEPT", "maxPerPage": 1})
|
||||||
n = len(body.get("data") or [])
|
n = len(body.get("data") or [])
|
||||||
return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). "
|
rg = self._get(ctx, RG_ORDERS_PATH.format(vendor=vendor),
|
||||||
"매출 수집은 다음 단계에서 구현됩니다.")
|
{"paidDateFrom": today.strftime("%Y%m%d"), "paidDateTo": today.strftime("%Y%m%d")}, rg=True)
|
||||||
|
m = len(rg.get("data") or [])
|
||||||
|
return (f"쿠팡 연결 정상(판매자배송 발주서·로켓그로스 주문 조회 권한 확인 — 오늘 결제완료 발주서 {'있음' if n else '없음'}, "
|
||||||
|
f"로켓그로스 오늘 주문 {m}건{'+' if rg.get('nextToken') else ''}).")
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||||
|
"""결제일 기준 기간(최대 31일)의 판매자배송 발주서·로켓그로스 주문을 실제로 불러, 날짜별 후보 금액을 나란히 —
|
||||||
|
WING 판매분석 '매출(원)'과 같은 열을 찾아 규칙을 확정하는 용도. 저장하지 않고, 개인정보 항목은 빼고 보여 준다."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||||
|
self._plan(ctx, day, to)
|
||||||
|
probes: list[dict[str, Any]] = []
|
||||||
|
seller_raw: list[dict[str, Any]] = []
|
||||||
|
rg_raw: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
seller_raw = self._seller_orders(ctx, day, to)
|
||||||
|
probes.append({"key": "seller", "label": "판매자배송 발주서(주문일 하루 앞부터, 상태 6개)",
|
||||||
|
"path": ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(seller_raw),
|
||||||
|
"fields": field_summary([r for o in seller_raw for r in line_records(o)])})
|
||||||
|
except AdapterError as exc:
|
||||||
|
probes.append({"key": "seller", "label": "판매자배송 발주서", "path": ORDERS_PATH.format(vendor="{vendorId}"),
|
||||||
|
"ok": False, "error": exc.message[:300]})
|
||||||
|
try:
|
||||||
|
rg_raw = self._rg_orders(ctx, day, to)
|
||||||
|
probes.append({"key": "rg", "label": "로켓그로스 주문(결제일, 출고된 주문만)",
|
||||||
|
"path": RG_ORDERS_PATH.format(vendor="{vendorId}"), "ok": True, "count": len(rg_raw),
|
||||||
|
"fields": field_summary([{**flatten({k: v for k, v in o.items() if k != "orderItems"}),
|
||||||
|
**flatten(it, "orderItems")}
|
||||||
|
for o in rg_raw for it in (o.get("orderItems") or [{}])])})
|
||||||
|
except AdapterError as exc:
|
||||||
|
probes.append({"key": "rg", "label": "로켓그로스 주문", "path": RG_ORDERS_PATH.format(vendor="{vendorId}"),
|
||||||
|
"ok": False, "error": exc.message[:300]})
|
||||||
|
seller = seller_lines(seller_raw, day, to)
|
||||||
|
rg = rg_lines(rg_raw, day, to)
|
||||||
|
dates = [(day + timedelta(days=i)).isoformat() for i in range((to - day).days + 1)]
|
||||||
|
|
||||||
|
def per_day(lines: list[dict[str, Any]], fn: Any) -> dict[str, int]:
|
||||||
|
out = {d: 0 for d in dates}
|
||||||
|
for ln in lines:
|
||||||
|
out[ln["_day"].isoformat()] += int(fn(ln))
|
||||||
|
return out
|
||||||
|
|
||||||
|
def count(lines: list[dict[str, Any]], d: str) -> int:
|
||||||
|
return len({ln["orderId"] for ln in lines if ln["_day"].isoformat() == d})
|
||||||
|
|
||||||
|
s_amt, s_net = per_day(seller, lambda x: x["amount"]), per_day(seller, lambda x: x["amount"] - x["discount"])
|
||||||
|
s_live = per_day(seller, lambda x: x["amount"] - x["canceled"])
|
||||||
|
s_qty, r_qty = per_day(seller, lambda x: x["qty"]), per_day(rg, lambda x: x["qty"])
|
||||||
|
s_cancel, s_ship = per_day(seller, lambda x: x["canceled"]), per_day(seller, lambda x: x["ship"])
|
||||||
|
r_amt = per_day(rg, lambda x: x["amount"])
|
||||||
|
ok = {p["key"]: p["ok"] for p in probes}
|
||||||
|
failed = {p["key"]: p.get("error", "") for p in probes if not p["ok"]}
|
||||||
|
cands = [
|
||||||
|
{"label": "① 현재 규칙: 판매자배송 판매가 + 로켓그로스", "days": {d: s_amt[d] + r_amt[d] for d in dates}},
|
||||||
|
{"label": "② 판매자배송 판매가(쿠폰 할인 전)", "days": s_amt, "error": failed.get("seller")},
|
||||||
|
{"label": "③ 판매자배송 할인 뒤(판매가 − 쿠폰·쿠팡 할인)", "days": s_net, "error": failed.get("seller")},
|
||||||
|
{"label": "④ 판매자배송 취소분 뺀 판매가", "days": s_live, "error": failed.get("seller")},
|
||||||
|
{"label": "⑤ 로켓그로스 단가 × 수량", "days": r_amt, "error": failed.get("rg")},
|
||||||
|
{"label": "판매량: 판매자배송 + 로켓그로스(개)", "days": {d: s_qty[d] + r_qty[d] for d in dates}},
|
||||||
|
]
|
||||||
|
if not all(ok.values()):
|
||||||
|
cands[0]["error"] = "일부 조회 실패 — 위 표 참고"
|
||||||
|
days = [{"date": d, "orders": count(seller, d) + count(rg, d), "amount": s_amt[d] + r_amt[d],
|
||||||
|
"claimed": s_cancel[d], "ship": s_ship[d]}
|
||||||
|
for d in dates]
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"day_cols": {"amount": "매출(현재 규칙)", "claimed": "그중 판매자배송 취소분(참고)", "ship": "판매자배송 배송비(참고, 매출 제외)"},
|
||||||
|
"refund_candidates": cands, "candidates_title": "매출 후보 비교 — WING 판매분석 '매출(원)'·'판매량'과 같은 열을 알려 주세요",
|
||||||
|
"rule": "결제일(한국 시간) 기준 — 판매자배송 발주서 orderPrice(판매가 × 수량, 쿠폰 할인 전, 결제 뒤 취소분 포함) + "
|
||||||
|
"로켓그로스 unitSalesPrice × salesQuantity(출고된 주문만). 배송비 제외"}
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ from datetime import date, datetime, timedelta
|
|||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
from .base import (
|
from .base import (
|
||||||
|
credential_fingerprint,
|
||||||
AdapterContext,
|
AdapterContext,
|
||||||
AdapterError,
|
AdapterError,
|
||||||
ApiError,
|
ApiError,
|
||||||
@@ -143,7 +144,8 @@ class GsshopAdapter(MarketplaceAdapter):
|
|||||||
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
|
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
|
# (협력사코드·운영 KEY 지문) → 통과한 (키 변형, 암호화 모드). 키를 바꾸면 예전 방식을 쓰지 않는다(검토 F04)
|
||||||
|
self._mode: dict[str, tuple[str, str]] = {}
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
|
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
|
||||||
@@ -191,7 +193,8 @@ class GsshopAdapter(MarketplaceAdapter):
|
|||||||
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
|
"""토큰 만드는 법(키 변형 × 암호화 모드)을 모르면 순서대로 시도 — 통과한 조합을 기억한다."""
|
||||||
sup, key = self._creds(ctx)
|
sup, key = self._creds(ctx)
|
||||||
known = self._mode.get(sup)
|
mode_key = self._mode_key(ctx)
|
||||||
|
known = self._mode.get(mode_key)
|
||||||
if known:
|
if known:
|
||||||
return self._call(ctx, path, params, known)
|
return self._call(ctx, path, params, known)
|
||||||
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
|
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
|
||||||
@@ -202,7 +205,7 @@ class GsshopAdapter(MarketplaceAdapter):
|
|||||||
except AuthFailed as exc:
|
except AuthFailed as exc:
|
||||||
last = exc
|
last = exc
|
||||||
continue
|
continue
|
||||||
self._mode[sup] = how
|
self._mode[mode_key] = how
|
||||||
return body
|
return body
|
||||||
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
|
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
|
||||||
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
|
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
|
||||||
@@ -220,6 +223,9 @@ class GsshopAdapter(MarketplaceAdapter):
|
|||||||
out.extend(rows)
|
out.extend(rows)
|
||||||
if not body.get("hasMorePage") or not rows:
|
if not body.get("hasMorePage") or not rows:
|
||||||
break
|
break
|
||||||
|
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 기간을 교체하지 않게(검토 F05)
|
||||||
|
raise ApiError(f"GS샵 {s.isoformat()}~{e.isoformat()} 조회가 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — "
|
||||||
|
"저장하지 않았습니다.")
|
||||||
ctx.progress.step(items=len(out))
|
ctx.progress.step(items=len(out))
|
||||||
s = e + timedelta(days=1)
|
s = e + timedelta(days=1)
|
||||||
return out
|
return out
|
||||||
@@ -261,15 +267,19 @@ class GsshopAdapter(MarketplaceAdapter):
|
|||||||
|
|
||||||
self.authenticate(ctx)
|
self.authenticate(ctx)
|
||||||
sup, _ = self._creds(ctx)
|
sup, _ = self._creds(ctx)
|
||||||
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
|
self._mode.pop(self._mode_key(ctx), None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
|
||||||
day = today_kst() - timedelta(days=1)
|
day = today_kst() - timedelta(days=1)
|
||||||
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
|
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
|
||||||
total = body.get("totalCount")
|
total = body.get("totalCount")
|
||||||
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
|
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
|
||||||
f"토큰 {self._how_label(sup)}).")
|
f"토큰 {self._how_label(ctx)}).")
|
||||||
|
|
||||||
def _how_label(self, sup: str) -> str:
|
@staticmethod
|
||||||
v, m = self._mode.get(sup, ("", ""))
|
def _mode_key(ctx: AdapterContext) -> str:
|
||||||
|
return credential_fingerprint(ctx.credentials, ("vendor_code", "api_key"))
|
||||||
|
|
||||||
|
def _how_label(self, ctx: AdapterContext) -> str:
|
||||||
|
v, m = self._mode.get(self._mode_key(ctx), ("", ""))
|
||||||
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
|
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
|
||||||
|
|
||||||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
|||||||
@@ -1,21 +1,372 @@
|
|||||||
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
|
"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인).
|
||||||
|
|
||||||
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
|
인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com
|
||||||
|
Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키
|
||||||
|
Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키
|
||||||
|
channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다)
|
||||||
|
두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."},
|
||||||
|
판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"},
|
||||||
|
연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다."
|
||||||
|
Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”).
|
||||||
|
|
||||||
|
매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함):
|
||||||
|
- 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=)
|
||||||
|
— 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음).
|
||||||
|
목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …).
|
||||||
|
- 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다.
|
||||||
|
한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시).
|
||||||
|
- 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`),
|
||||||
|
날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합.
|
||||||
|
- 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice
|
||||||
|
− adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**.
|
||||||
|
설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다.
|
||||||
|
- 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다.
|
||||||
|
- 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from .base import CredentialField, MarketplaceAdapter
|
import re
|
||||||
|
import time
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from .base import (
|
||||||
|
AdapterContext,
|
||||||
|
AdapterError,
|
||||||
|
ApiError,
|
||||||
|
AuthFailed,
|
||||||
|
CredentialField,
|
||||||
|
MarketplaceAdapter,
|
||||||
|
NotConfigured,
|
||||||
|
SaleEvent,
|
||||||
|
)
|
||||||
|
from .naver import field_summary, flatten
|
||||||
|
|
||||||
|
HOST = "https://kapi.kakao.com"
|
||||||
|
PAID_PATH = "/v2/shopping/orders/paidAt"
|
||||||
|
ORDER_PATH = "/v1/shopping/order"
|
||||||
|
EVENT_PREFIX = "kakao:"
|
||||||
|
DEFAULT_CHANNELS = "101" # 톡스토어
|
||||||
|
PAGE_SIZE = 100
|
||||||
|
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
|
||||||
|
CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히)
|
||||||
|
RETRY_429 = 3
|
||||||
|
PROBE_MAX_DAYS = 31
|
||||||
|
CACHE_MAX = 20000
|
||||||
|
|
||||||
|
# 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준).
|
||||||
|
UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"})
|
||||||
|
# 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
|
||||||
|
CLAIMED_STATUS = frozenset({
|
||||||
|
"PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete",
|
||||||
|
"ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete",
|
||||||
|
})
|
||||||
|
STATUS_KO = {
|
||||||
|
"Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중",
|
||||||
|
"PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청",
|
||||||
|
"PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료",
|
||||||
|
"UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중",
|
||||||
|
"ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료",
|
||||||
|
"ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청",
|
||||||
|
"ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료",
|
||||||
|
"TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료",
|
||||||
|
"BuyDecision": "구매 결정",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _won(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
|
||||||
|
except ValueError:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _day(value: Any) -> date | None:
|
||||||
|
""""20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간."""
|
||||||
|
s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8]
|
||||||
|
if len(s) < 8:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def line_amount(op: dict[str, Any]) -> int:
|
||||||
|
"""상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외."""
|
||||||
|
qty = max(1, _won(op.get("quantity")))
|
||||||
|
gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty
|
||||||
|
return max(0, gross - line_discount(op))
|
||||||
|
|
||||||
|
|
||||||
|
def line_discount(op: dict[str, Any]) -> int:
|
||||||
|
return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice"))
|
||||||
|
|
||||||
|
|
||||||
|
# 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김).
|
||||||
|
PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver")
|
||||||
|
PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment")
|
||||||
|
|
||||||
|
|
||||||
|
def strip_personal(det: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out: dict[str, Any] = {}
|
||||||
|
for k, v in det.items():
|
||||||
|
if k in PERSONAL_OBJECTS and isinstance(v, dict):
|
||||||
|
out[k] = {kk: "" for kk in v}
|
||||||
|
elif isinstance(v, dict):
|
||||||
|
out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()}
|
||||||
|
else:
|
||||||
|
out[k] = v
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def order_detail(body: Any) -> dict[str, Any]:
|
||||||
|
"""주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움).
|
||||||
|
감싼 모양(data/content)도 받아들인다."""
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
return {}
|
||||||
|
if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict):
|
||||||
|
return strip_personal(body)
|
||||||
|
for k in ("data", "content", "contents"):
|
||||||
|
v = body.get(k)
|
||||||
|
if isinstance(v, list) and v and isinstance(v[0], dict):
|
||||||
|
v = v[0]
|
||||||
|
if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)):
|
||||||
|
return strip_personal(v)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
|
||||||
|
"""주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
|
||||||
|
items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
|
||||||
|
pays: dict[str, dict[str, Any]] = {}
|
||||||
|
for it in items:
|
||||||
|
row, det = it.get("row") or {}, it.get("detail") or {}
|
||||||
|
base, op = det.get("orderBase") or {}, det.get("orderProduct") or {}
|
||||||
|
status = str(row.get("orderStatus") or base.get("status") or "")
|
||||||
|
day = _day(row.get("paidAt") or base.get("paidAt"))
|
||||||
|
oid = str(row.get("orderId") or base.get("id") or det.get("id") or "")
|
||||||
|
pid = str(row.get("paymentId") or base.get("paymentId") or oid)
|
||||||
|
if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op:
|
||||||
|
continue
|
||||||
|
p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
|
||||||
|
"discount": 0, "names": [], "opt": "", "statuses": [], "orders": [],
|
||||||
|
"order_day": _day(row.get("createdAt") or base.get("createdAt"))})
|
||||||
|
amt = line_amount(op)
|
||||||
|
p["amount"] += amt
|
||||||
|
if status in CLAIMED_STATUS:
|
||||||
|
p["claimed"] += amt
|
||||||
|
p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount"))
|
||||||
|
p["qty"] += max(1, _won(op.get("quantity")))
|
||||||
|
p["discount"] += line_discount(op)
|
||||||
|
p["orders"].append(oid)
|
||||||
|
name = str(op.get("name") or "")
|
||||||
|
if name and name not in p["names"]:
|
||||||
|
p["names"].append(name)
|
||||||
|
p["opt"] = p["opt"] or str(op.get("optionContent") or "")
|
||||||
|
if status and status not in p["statuses"]:
|
||||||
|
p["statuses"].append(status)
|
||||||
|
return pays
|
||||||
|
|
||||||
|
|
||||||
|
def _err_text(body: dict[str, Any], res: Any) -> str:
|
||||||
|
parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")]
|
||||||
|
ex = body.get("extras")
|
||||||
|
if isinstance(ex, dict):
|
||||||
|
parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")]
|
||||||
|
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
|
||||||
|
|
||||||
|
|
||||||
class KakaoAdapter(MarketplaceAdapter):
|
class KakaoAdapter(MarketplaceAdapter):
|
||||||
code = "kakao"
|
code = "kakao"
|
||||||
name = "카카오"
|
name = "카카오"
|
||||||
auth_type = "api_key"
|
auth_type = "api_key"
|
||||||
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
|
implemented = True
|
||||||
|
replace_range = True
|
||||||
|
event_prefix = EVENT_PREFIX
|
||||||
|
docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975"
|
||||||
|
note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. "
|
||||||
|
"그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. "
|
||||||
|
"두 키는 서로 다른 앱의 키여야 합니다.")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._last_call = 0.0
|
||||||
|
self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보)
|
||||||
|
|
||||||
def credential_fields(self) -> list[CredentialField]:
|
def credential_fields(self) -> list[CredentialField]:
|
||||||
|
# api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게.
|
||||||
return [
|
return [
|
||||||
CredentialField("seller_id", "판매자(채널) ID"),
|
CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True,
|
||||||
CredentialField("api_key", "API Key", secret=True),
|
help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"),
|
||||||
|
CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True,
|
||||||
|
help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"),
|
||||||
|
CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS,
|
||||||
|
help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# ── 호출 ──────────────────────────────────────────────
|
||||||
|
def _headers(self, ctx: AdapterContext) -> dict[str, str]:
|
||||||
|
admin = ctx.credentials.get("admin_key").strip()
|
||||||
|
seller = ctx.credentials.get("api_key").strip()
|
||||||
|
if not admin or not seller:
|
||||||
|
raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.")
|
||||||
|
channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS
|
||||||
|
return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}",
|
||||||
|
"channel-ids": channels, "Accept": "application/json"}
|
||||||
|
|
||||||
|
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내)."""
|
||||||
|
import httpx # 지연 import
|
||||||
|
|
||||||
|
headers = self._headers(ctx)
|
||||||
|
for attempt in range(RETRY_429 + 1):
|
||||||
|
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
|
||||||
|
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(wait)
|
||||||
|
try:
|
||||||
|
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise ApiError(f"카카오쇼핑 API 연결 실패: {type(exc).__name__}") from None
|
||||||
|
finally:
|
||||||
|
self._last_call = time.monotonic()
|
||||||
|
if res.status_code == 429 and attempt < RETRY_429:
|
||||||
|
time.sleep(1.0 * (2 ** attempt))
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
body = res.json()
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
body = {"contents": body}
|
||||||
|
code = _won(body.get("code")) if body.get("code") not in (None, "") else 0
|
||||||
|
text = _err_text(body, res)
|
||||||
|
if code == -2 or "target-authorization" in text.lower():
|
||||||
|
raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, "
|
||||||
|
"어드민 키가 REST API 키가 아닌지 확인하세요.")
|
||||||
|
if code == -401 or "deactivated" in text:
|
||||||
|
raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.")
|
||||||
|
if "매핑" in text or "대행사" in text:
|
||||||
|
raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 "
|
||||||
|
"끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.")
|
||||||
|
if res.status_code in (401, 403):
|
||||||
|
raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, "
|
||||||
|
"두 키가 맞는지 확인하세요.")
|
||||||
|
if res.status_code >= 400 or code < 0:
|
||||||
|
raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}")
|
||||||
|
return body
|
||||||
|
raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
|
||||||
|
|
||||||
|
def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
|
||||||
|
"""결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음."""
|
||||||
|
params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59",
|
||||||
|
"size": PAGE_SIZE}
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
token = ""
|
||||||
|
seen: set[str] = set()
|
||||||
|
for _ in range(MAX_PAGES):
|
||||||
|
body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})})
|
||||||
|
rows = [r for r in body.get("contents") or [] if isinstance(r, dict)]
|
||||||
|
out.extend(rows)
|
||||||
|
token = str(body.get("token") or "")
|
||||||
|
if not token or not rows:
|
||||||
|
break
|
||||||
|
if token in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
|
||||||
|
raise ApiError(f"카카오 {d.isoformat()} 주문 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
|
||||||
|
seen.add(token)
|
||||||
|
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음
|
||||||
|
raise ApiError(f"카카오 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
oid = str(row.get("orderId") or "")
|
||||||
|
mod = str(row.get("modifiedAt") or "")
|
||||||
|
hit = self._details.get(oid)
|
||||||
|
if hit and hit[0] == mod and mod:
|
||||||
|
return hit[1]
|
||||||
|
det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid}))
|
||||||
|
if det:
|
||||||
|
if len(self._details) >= CACHE_MAX:
|
||||||
|
self._details.clear()
|
||||||
|
self._details[oid] = (mod, det)
|
||||||
|
return det
|
||||||
|
|
||||||
|
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
"""하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}."""
|
||||||
|
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
|
||||||
|
d = start
|
||||||
|
while d <= end:
|
||||||
|
rows = self._day_rows(ctx, d)
|
||||||
|
got = []
|
||||||
|
for r in rows:
|
||||||
|
if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS:
|
||||||
|
got.append({"row": r, "detail": {}})
|
||||||
|
continue
|
||||||
|
got.append({"row": r, "detail": self._detail(ctx, r)})
|
||||||
|
ctx.progress.step(items=len(rows))
|
||||||
|
yield from got
|
||||||
|
d += timedelta(days=1)
|
||||||
|
|
||||||
|
# ── 수집 ──────────────────────────────────────────────
|
||||||
|
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
yield from group_payments(self._items(ctx, start, end), start, end).values()
|
||||||
|
|
||||||
|
def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]:
|
||||||
|
pid, day = str(p.get("paymentId") or ""), p.get("_day")
|
||||||
|
if not pid or day is None:
|
||||||
|
return []
|
||||||
|
names = p.get("names") or []
|
||||||
|
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
|
||||||
|
statuses = [STATUS_KO.get(s, s) for s in p.get("statuses") or []]
|
||||||
|
orders = p.get("orders") or []
|
||||||
|
return [SaleEvent(
|
||||||
|
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid,
|
||||||
|
external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day,
|
||||||
|
amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200],
|
||||||
|
quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)),
|
||||||
|
order_status="/".join(statuses)[:50],
|
||||||
|
)]
|
||||||
|
|
||||||
|
def test_connection(self, ctx: AdapterContext) -> str:
|
||||||
|
from app.timezone import today_kst # noqa: WPS433
|
||||||
|
|
||||||
|
self.authenticate(ctx)
|
||||||
|
rows = self._day_rows(ctx, today_kst())
|
||||||
|
return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)."
|
||||||
|
|
||||||
|
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||||||
|
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
|
||||||
|
"""결제일 기준 기간(최대 31일)의 주문과 주문정보를 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을
|
||||||
|
돌려준다(저장 안 함). 판매자센터 매출 화면과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보는 이름만."""
|
||||||
|
self.authenticate(ctx)
|
||||||
|
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
|
||||||
|
try:
|
||||||
|
items = list(self._items(ctx, day, to))
|
||||||
|
except AdapterError as exc:
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
|
||||||
|
{"key": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]}
|
||||||
|
flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items]
|
||||||
|
probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}",
|
||||||
|
"ok": True, "count": len(items), "fields": field_summary(flat)}]
|
||||||
|
by_status: dict[str, list[dict[str, str]]] = {}
|
||||||
|
for it, f in zip(items, flat):
|
||||||
|
by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f)
|
||||||
|
for st, rows in sorted(by_status.items()):
|
||||||
|
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
|
||||||
|
+ (" — 매출 제외(미결제)" if st in UNPAID_STATUS else
|
||||||
|
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus",
|
||||||
|
"ok": True, "count": len(rows),
|
||||||
|
"fields": [f for f in field_summary(rows)
|
||||||
|
if f["sum"] is not None and f["name"].startswith("orderProduct.")]})
|
||||||
|
pays = group_payments(items, day, to)
|
||||||
|
days = []
|
||||||
|
d = day
|
||||||
|
while d <= to:
|
||||||
|
day_pays = [p for p in pays.values() if p["_day"] == d]
|
||||||
|
days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays),
|
||||||
|
"claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)})
|
||||||
|
d += timedelta(days=1)
|
||||||
|
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
|
||||||
|
"rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, "
|
||||||
|
"결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""수동 입력 전용 쇼핑몰 — API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 넣는다.
|
||||||
|
|
||||||
|
어댑터는 쇼핑몰의 "종류"만 알린다: 인증 항목이 없고(manual_only), 매출 업데이트(sync_all)에서 빠진다.
|
||||||
|
DB(perf_marketplaces)에는 manual_input = TRUE 로 넣는다(마이그레이션 003).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .base import MarketplaceAdapter
|
||||||
|
|
||||||
|
|
||||||
|
class ManualOnlyAdapter(MarketplaceAdapter):
|
||||||
|
auth_type = "manual"
|
||||||
|
manual_only = True
|
||||||
|
note = "API 연동 없이 실적 일자별 표의 날짜 칸에 총매출을 직접 입력합니다."
|
||||||
|
|
||||||
|
|
||||||
|
class CoupangRocketAdapter(ManualOnlyAdapter):
|
||||||
|
code = "coupang_rocket"
|
||||||
|
name = "쿠팡(로켓)"
|
||||||
|
|
||||||
|
|
||||||
|
class AtomyAzmallAdapter(ManualOnlyAdapter):
|
||||||
|
code = "atomy"
|
||||||
|
name = "애터미아자몰"
|
||||||
@@ -28,6 +28,7 @@ from datetime import date, datetime, timedelta
|
|||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
from .base import (
|
from .base import (
|
||||||
|
credential_fingerprint,
|
||||||
AdapterContext,
|
AdapterContext,
|
||||||
AdapterError,
|
AdapterError,
|
||||||
ApiError,
|
ApiError,
|
||||||
@@ -200,9 +201,12 @@ def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dic
|
|||||||
return orders
|
return orders
|
||||||
|
|
||||||
|
|
||||||
|
# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint)
|
||||||
|
TOKEN_KEYS = ("client_id", "client_secret", "account_id")
|
||||||
|
|
||||||
class NaverAdapter(MarketplaceAdapter):
|
class NaverAdapter(MarketplaceAdapter):
|
||||||
code = "naver"
|
code = "naver"
|
||||||
name = "네이버 스마트스토어"
|
name = "네이버"
|
||||||
auth_type = "oauth"
|
auth_type = "oauth"
|
||||||
implemented = True
|
implemented = True
|
||||||
replace_range = True
|
replace_range = True
|
||||||
@@ -222,6 +226,8 @@ class NaverAdapter(MarketplaceAdapter):
|
|||||||
help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
|
help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
|
||||||
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||||
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||||
|
# 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04)
|
||||||
|
CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True),
|
||||||
]
|
]
|
||||||
|
|
||||||
# ── 인증 ──────────────────────────────────────────────
|
# ── 인증 ──────────────────────────────────────────────
|
||||||
@@ -233,7 +239,8 @@ class NaverAdapter(MarketplaceAdapter):
|
|||||||
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
exp = 0.0
|
exp = 0.0
|
||||||
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
|
same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS)
|
||||||
|
if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC:
|
||||||
return tok
|
return tok
|
||||||
return self._issue_token(ctx)
|
return self._issue_token(ctx)
|
||||||
|
|
||||||
@@ -266,6 +273,7 @@ class NaverAdapter(MarketplaceAdapter):
|
|||||||
expires_in = _won(body.get("expires_in")) or 3 * 3600
|
expires_in = _won(body.get("expires_in")) or 3 * 3600
|
||||||
ctx.credentials.set("access_token", tok)
|
ctx.credentials.set("access_token", tok)
|
||||||
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
||||||
|
ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS))
|
||||||
return tok
|
return tok
|
||||||
|
|
||||||
def authenticate(self, ctx: AdapterContext) -> None:
|
def authenticate(self, ctx: AdapterContext) -> None:
|
||||||
@@ -340,6 +348,8 @@ class NaverAdapter(MarketplaceAdapter):
|
|||||||
out.extend(items)
|
out.extend(items)
|
||||||
if not items or not has_next(body, page, len(items)):
|
if not items or not has_next(body, page, len(items)):
|
||||||
break
|
break
|
||||||
|
else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 저장하지 않게(검토 F05)
|
||||||
|
raise ApiError(f"네이버 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
|
||||||
|
|||||||
@@ -14,14 +14,17 @@ from .gmarket import GmarketAdapter
|
|||||||
from .gsshop import GsshopAdapter
|
from .gsshop import GsshopAdapter
|
||||||
from .kakao import KakaoAdapter
|
from .kakao import KakaoAdapter
|
||||||
from .lotteon import LotteonAdapter
|
from .lotteon import LotteonAdapter
|
||||||
|
from .manual import AtomyAzmallAdapter, CoupangRocketAdapter
|
||||||
from .naver import NaverAdapter
|
from .naver import NaverAdapter
|
||||||
from .ohouse import OhouseAdapter
|
from .ohouse import OhouseAdapter
|
||||||
from .toss import TossAdapter
|
from .toss import TossAdapter
|
||||||
|
|
||||||
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
_ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
||||||
|
# 화면 순서와 같게(DB sort_order 도 같은 순서 — 마이그레이션 003)
|
||||||
Cafe24Adapter(),
|
Cafe24Adapter(),
|
||||||
NaverAdapter(),
|
NaverAdapter(),
|
||||||
CoupangAdapter(),
|
CoupangAdapter(), # 쿠팡(윙)
|
||||||
|
CoupangRocketAdapter(), # 쿠팡(로켓) — 수동 입력 전용
|
||||||
OhouseAdapter(),
|
OhouseAdapter(),
|
||||||
GmarketAdapter(),
|
GmarketAdapter(),
|
||||||
KakaoAdapter(),
|
KakaoAdapter(),
|
||||||
@@ -29,6 +32,7 @@ _ADAPTERS: tuple[MarketplaceAdapter, ...] = (
|
|||||||
ElevenstAdapter(),
|
ElevenstAdapter(),
|
||||||
LotteonAdapter(),
|
LotteonAdapter(),
|
||||||
TossAdapter(),
|
TossAdapter(),
|
||||||
|
AtomyAzmallAdapter(), # 애터미아자몰 — 수동 입력 전용
|
||||||
)
|
)
|
||||||
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
_BY_CODE = {a.code: a for a in _ADAPTERS}
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from datetime import date, datetime, timedelta, timezone
|
|||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
from .base import (
|
from .base import (
|
||||||
|
credential_fingerprint,
|
||||||
AdapterContext,
|
AdapterContext,
|
||||||
AdapterError,
|
AdapterError,
|
||||||
ApiError,
|
ApiError,
|
||||||
@@ -245,6 +246,9 @@ def summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|||||||
return fields
|
return fields
|
||||||
|
|
||||||
|
|
||||||
|
# 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint)
|
||||||
|
TOKEN_KEYS = ("api_key", "api_secret")
|
||||||
|
|
||||||
class TossAdapter(MarketplaceAdapter):
|
class TossAdapter(MarketplaceAdapter):
|
||||||
code = "toss"
|
code = "toss"
|
||||||
name = "토스쇼핑"
|
name = "토스쇼핑"
|
||||||
@@ -268,6 +272,8 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
help="같은 화면의 Secret Key"),
|
help="같은 화면의 Secret Key"),
|
||||||
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
|
||||||
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True),
|
||||||
|
# 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04)
|
||||||
|
CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True),
|
||||||
]
|
]
|
||||||
|
|
||||||
# ── 인증 ──────────────────────────────────────────────
|
# ── 인증 ──────────────────────────────────────────────
|
||||||
@@ -279,7 +285,8 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
exp = float(ctx.credentials.get("access_token_expires_at") or 0)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
exp = 0.0
|
exp = 0.0
|
||||||
if tok and exp - time.time() > TOKEN_MARGIN_SEC:
|
same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS)
|
||||||
|
if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC:
|
||||||
return tok
|
return tok
|
||||||
return self._issue_token(ctx)
|
return self._issue_token(ctx)
|
||||||
|
|
||||||
@@ -308,6 +315,7 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
expires_in = _won(body.get("expires_in")) or 24 * 3600
|
expires_in = _won(body.get("expires_in")) or 24 * 3600
|
||||||
ctx.credentials.set("access_token", tok)
|
ctx.credentials.set("access_token", tok)
|
||||||
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in))
|
||||||
|
ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS))
|
||||||
return tok
|
return tok
|
||||||
|
|
||||||
def authenticate(self, ctx: AdapterContext) -> None:
|
def authenticate(self, ctx: AdapterContext) -> None:
|
||||||
@@ -383,6 +391,7 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
|
params: dict[str, Any] = {"startDate": a.isoformat(), "endDate": b.isoformat(), "limit": PAGE_SIZE}
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
cursor = None
|
cursor = None
|
||||||
|
seen: set[str] = set()
|
||||||
for _ in range(MAX_PAGES):
|
for _ in range(MAX_PAGES):
|
||||||
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
|
body = self._get(ctx, ORDERS_PATH, {**params, **({"nextCursor": cursor} if cursor else {})})
|
||||||
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
|
rows = [r for r in body.get("results") or [] if isinstance(r, dict)]
|
||||||
@@ -390,6 +399,11 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
cursor = body.get("nextCursor")
|
cursor = body.get("nextCursor")
|
||||||
if not cursor or not rows:
|
if not cursor or not rows:
|
||||||
break
|
break
|
||||||
|
if str(cursor) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
|
||||||
|
raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
|
||||||
|
seen.add(str(cursor))
|
||||||
|
else:
|
||||||
|
raise ApiError(f"토스 주문 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
def _settlement_items(self, ctx: AdapterContext, a: date, b: date) -> list[dict[str, Any]]:
|
||||||
@@ -398,6 +412,7 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
|
"toDate": b.isoformat(), "size": SETTLEMENT_SIZE}
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
token = None
|
token = None
|
||||||
|
seen: set[str] = set()
|
||||||
for _ in range(MAX_PAGES):
|
for _ in range(MAX_PAGES):
|
||||||
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
|
body = self._get(ctx, SETTLEMENT_PATH, {**params, **({"nextToken": token} if token else {})})
|
||||||
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
@@ -405,12 +420,18 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
token = body.get("nextToken")
|
token = body.get("nextToken")
|
||||||
if not token or not rows:
|
if not token or not rows:
|
||||||
break
|
break
|
||||||
|
if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
|
||||||
|
raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
|
||||||
|
seen.add(str(token))
|
||||||
|
else:
|
||||||
|
raise ApiError(f"토스 정산 {a.isoformat()}~{b.isoformat()} 이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
def _claims(self, ctx: AdapterContext) -> list[dict[str, Any]]:
|
||||||
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
|
"""클레임 목록 전체(유형·상태 조건 없음 = 전부 — 이 API 는 그 밖엔 날짜로 거를 수 없다), nextToken 으로 끝까지."""
|
||||||
out: list[dict[str, Any]] = []
|
out: list[dict[str, Any]] = []
|
||||||
token = None
|
token = None
|
||||||
|
seen: set[str] = set()
|
||||||
for _ in range(CLAIM_MAX_PAGES):
|
for _ in range(CLAIM_MAX_PAGES):
|
||||||
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
|
body = self._get(ctx, CLAIMS_PATH, {"size": CLAIM_PAGE_SIZE, **({"nextToken": token} if token else {})})
|
||||||
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
rows = [r for r in body.get("items") or [] if isinstance(r, dict)]
|
||||||
@@ -418,6 +439,11 @@ class TossAdapter(MarketplaceAdapter):
|
|||||||
token = body.get("nextToken")
|
token = body.get("nextToken")
|
||||||
if not token or not rows or body.get("hasNext") is False:
|
if not token or not rows or body.get("hasNext") is False:
|
||||||
break
|
break
|
||||||
|
if str(token) in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05)
|
||||||
|
raise ApiError("토스 클레임 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.")
|
||||||
|
seen.add(str(token))
|
||||||
|
else:
|
||||||
|
raise ApiError(f"토스 클레임 목록이 {CLAIM_MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.")
|
||||||
return out
|
return out
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
"""매출 자동 업데이트 — 웹 프로세스 안 데몬 스레드(프로젝트 마감 알림과 같은 방식).
|
||||||
|
|
||||||
|
기본: 매일 09:00 ~ 19:00(KST) 정각·30분마다, 오늘 포함 최근 10일을 [매출 업데이트] 와 같은 방식으로 다시 가져온다.
|
||||||
|
- 매출이 끝나면 설정된 광고 API(구글 광고)도 같은 기간으로 가져온다(ad_sync, 실패해도 매출과 무관).
|
||||||
|
- 진행 창 작업(jobs)으로 돌린다 — 그동안 누가 [매출 업데이트] 를 누르면 새로 시작하지 않고 이 진행 상황을 본다.
|
||||||
|
- 그 시각에 이미 다른 업데이트가 돌고 있으면 그 회차는 건너뛴다(같은 쇼핑몰 동시 실행은 어차피 막혀 있음).
|
||||||
|
- 한 회차가 30분을 넘기면 지나간 회차는 건너뛰고 다음 정각/30분을 기다린다(밀린 회차를 몰아서 돌리지 않음).
|
||||||
|
- 서버를 켠 시각의 회차는 돌리지 않고 다음 회차부터.
|
||||||
|
|
||||||
|
환경변수(.env)
|
||||||
|
PERFORMANCE_AUTO_SYNC=false 끄기(기본 켜짐)
|
||||||
|
PERFORMANCE_AUTO_SYNC_DAYS=10 가져올 기간(오늘 포함 최근 N일, 1~90)
|
||||||
|
PERFORMANCE_AUTO_SYNC_HOURS=9-19 돌리는 시간대(시작시-마지막시, 마지막 시는 정각 회차까지)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.timezone import now_kst
|
||||||
|
|
||||||
|
logger = logging.getLogger("performance.auto_sync")
|
||||||
|
|
||||||
|
AUTO_USER = "자동 업데이트"
|
||||||
|
DEFAULT_DAYS = 10
|
||||||
|
DEFAULT_HOURS = (9, 19)
|
||||||
|
SLOT_MINUTES = 30
|
||||||
|
|
||||||
|
_started = False
|
||||||
|
_start_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str) -> str:
|
||||||
|
return (os.getenv(name, "") or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def enabled() -> bool:
|
||||||
|
return _env("PERFORMANCE_AUTO_SYNC").lower() not in ("0", "false", "no", "off")
|
||||||
|
|
||||||
|
|
||||||
|
def sync_days() -> int:
|
||||||
|
try:
|
||||||
|
return max(1, min(90, int(_env("PERFORMANCE_AUTO_SYNC_DAYS") or DEFAULT_DAYS)))
|
||||||
|
except ValueError:
|
||||||
|
return DEFAULT_DAYS
|
||||||
|
|
||||||
|
|
||||||
|
def hour_window() -> tuple[int, int]:
|
||||||
|
m = re.fullmatch(r"(\d{1,2})\s*-\s*(\d{1,2})", _env("PERFORMANCE_AUTO_SYNC_HOURS"))
|
||||||
|
if not m:
|
||||||
|
return DEFAULT_HOURS
|
||||||
|
first, last = int(m.group(1)), int(m.group(2))
|
||||||
|
if not (0 <= first <= last <= 23):
|
||||||
|
return DEFAULT_HOURS
|
||||||
|
return first, last
|
||||||
|
|
||||||
|
|
||||||
|
def is_slot(t: datetime, hours: tuple[int, int]) -> bool:
|
||||||
|
"""t(분 단위로 자른 시각)가 회차인가 — 정각·30분, first시 정각 ~ last시 정각."""
|
||||||
|
first, last = hours
|
||||||
|
if t.minute % SLOT_MINUTES:
|
||||||
|
return False
|
||||||
|
return first <= t.hour < last or (t.hour == last and t.minute == 0)
|
||||||
|
|
||||||
|
|
||||||
|
def next_slot(after: datetime, hours: tuple[int, int]) -> datetime:
|
||||||
|
"""after 보다 뒤의 첫 회차 시각."""
|
||||||
|
t = after.replace(second=0, microsecond=0)
|
||||||
|
t += timedelta(minutes=SLOT_MINUTES - t.minute % SLOT_MINUTES)
|
||||||
|
for _ in range(48 * 2 + 2): # 하루치 회차를 넘기기 전에 반드시 찾는다
|
||||||
|
if is_slot(t, hours):
|
||||||
|
return t
|
||||||
|
t += timedelta(minutes=SLOT_MINUTES)
|
||||||
|
raise ValueError("회차를 찾을 수 없습니다")
|
||||||
|
|
||||||
|
|
||||||
|
def run_once(store: Any, app_state: Any, *, today: Any, days: int) -> dict[str, Any]:
|
||||||
|
"""한 회차 — 진행 창 작업으로 오늘 포함 최근 days 일 업데이트. 이미 돌고 있으면 건너뜀."""
|
||||||
|
from . import common, jobs # noqa: WPS433
|
||||||
|
from .credentials import CredentialService # noqa: WPS433
|
||||||
|
from .sync import SyncService # noqa: WPS433
|
||||||
|
|
||||||
|
if jobs.running_job() is not None:
|
||||||
|
return {"skipped": True, "reason": "다른 업데이트 진행 중"}
|
||||||
|
start, end = today - timedelta(days=days - 1), today
|
||||||
|
job = jobs.create_job(user=AUTO_USER, start=start, end=end)
|
||||||
|
sync = SyncService(store, CredentialService(store, common.key_ring), app_state=app_state)
|
||||||
|
error = ""
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
results = sync.sync_all(start=start, end=end, trigger="schedule", user=AUTO_USER, job=job)
|
||||||
|
except Exception as exc: # noqa: BLE001 — 스레드가 죽지 않게
|
||||||
|
logger.exception("auto sync failed")
|
||||||
|
error = f"업데이트 중 오류: {type(exc).__name__}"
|
||||||
|
last = None
|
||||||
|
try:
|
||||||
|
last = store.last_update_at()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
job.finish(error=error, last_update_at=last)
|
||||||
|
# 광고 API(구글 광고 등)도 같은 회차·같은 기간으로 — 설정된 연동만, 실패해도 매출 업데이트와 무관(2026-10-15)
|
||||||
|
ads: list[dict[str, Any]] = []
|
||||||
|
try:
|
||||||
|
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
|
||||||
|
|
||||||
|
ads = AdSyncService(store, ad_credentials(store, common.key_ring)).sync_all(start, end, user=AUTO_USER)
|
||||||
|
except Exception: # noqa: BLE001 — 스레드가 죽지 않게
|
||||||
|
logger.exception("auto ad sync failed")
|
||||||
|
ok = sum(1 for r in results if r.get("ok"))
|
||||||
|
return {"skipped": False, "from": start.isoformat(), "to": end.isoformat(), "ok": ok,
|
||||||
|
"failed": [r.get("code") for r in results if not r.get("ok") and not r.get("skipped")], "error": error,
|
||||||
|
"ads": [{"code": a.get("code"), "ok": bool(a.get("ok"))} for a in ads]}
|
||||||
|
|
||||||
|
|
||||||
|
def start_auto_sync_thread(app_state: Any) -> bool:
|
||||||
|
"""웹 프로세스 시작 시 1번. 저장소가 없거나 꺼져 있거나 이미 돌고 있으면 False."""
|
||||||
|
global _started # noqa: PLW0603
|
||||||
|
store = getattr(app_state, "performance_store", None)
|
||||||
|
if store is None or not enabled():
|
||||||
|
return False
|
||||||
|
with _start_lock:
|
||||||
|
if _started:
|
||||||
|
return False
|
||||||
|
_started = True
|
||||||
|
hours, days = hour_window(), sync_days()
|
||||||
|
|
||||||
|
def _loop() -> None:
|
||||||
|
due = next_slot(now_kst(), hours)
|
||||||
|
logger.info("매출 자동 업데이트 시작 — %02d~%02d시 30분마다, 최근 %d일, 다음 %s", hours[0], hours[1], days,
|
||||||
|
due.strftime("%m-%d %H:%M"))
|
||||||
|
while True:
|
||||||
|
wait = (due - now_kst()).total_seconds()
|
||||||
|
if wait > 0:
|
||||||
|
time.sleep(min(wait, 60)) # 시계 변경·절전에도 1분 안에 다시 확인
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
res = run_once(store, app_state, today=due.date(), days=days)
|
||||||
|
logger.info("매출 자동 업데이트 %s: %s", due.strftime("%H:%M"), res)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("매출 자동 업데이트 실패 — 다음 회차에 다시")
|
||||||
|
due = next_slot(max(now_kst(), due), hours)
|
||||||
|
|
||||||
|
threading.Thread(target=_loop, name="performance-auto-sync", daemon=True).start()
|
||||||
|
return True
|
||||||
@@ -16,29 +16,38 @@ from .adapters.base import MarketplaceAdapter
|
|||||||
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
|
from .security.crypto import KeyRing, decrypt, encrypt, needs_reencrypt
|
||||||
|
|
||||||
|
|
||||||
def aad_for(code: str, key: str) -> str:
|
def aad_for(code: str, key: str, ns: str = "") -> str:
|
||||||
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터."""
|
"""암호문을 (쇼핑몰, 항목)에 묶는 추가 인증 데이터. ns = 이름 공간(광고 API 인증정보는 "ad:") —
|
||||||
return f"perf:{code}:{key}"
|
쇼핑몰 암호문과 광고 암호문을 서로 바꿔 넣어도 복호화되지 않는다."""
|
||||||
|
return f"perf:{ns}{code}:{key}"
|
||||||
|
|
||||||
|
|
||||||
class CredentialAccessor:
|
class CredentialAccessor:
|
||||||
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
|
"""어댑터 전용 — 서버 안에서만 복호화. 값은 처음 꺼낼 때 한 번 복호화해 둔다."""
|
||||||
|
|
||||||
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
|
def __init__(self, store: Any, code: str, ring_loader: Callable[[], KeyRing], *,
|
||||||
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "") -> None:
|
overrides: dict[str, str] | None = None, persist: bool = True, user: str = "",
|
||||||
|
aad_ns: str = "", cleared: set[str] | None = None) -> None:
|
||||||
self._store = store
|
self._store = store
|
||||||
self._code = code
|
self._code = code
|
||||||
|
self._ns = aad_ns
|
||||||
self._ring_loader = ring_loader
|
self._ring_loader = ring_loader
|
||||||
self._rows = store.credential_rows(code) if store is not None else {}
|
self._rows = store.credential_rows(code) if store is not None else {}
|
||||||
self._cache: dict[str, str] = {}
|
self._cache: dict[str, str] = {}
|
||||||
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
|
self._overrides = {k: v for k, v in (overrides or {}).items() if v}
|
||||||
|
# 연결 테스트에서 화면 칸을 비운 항목 — 저장값이 있어도 빈 값으로(저장하지 않음)
|
||||||
|
self._cleared = {k for k in (cleared or set()) if k not in self._overrides}
|
||||||
self._persist = persist
|
self._persist = persist
|
||||||
self._user = user
|
self._user = user
|
||||||
|
|
||||||
def has(self, key: str) -> bool:
|
def has(self, key: str) -> bool:
|
||||||
|
if key in self._cleared:
|
||||||
|
return False
|
||||||
return bool(self._overrides.get(key)) or key in self._rows
|
return bool(self._overrides.get(key)) or key in self._rows
|
||||||
|
|
||||||
def get(self, key: str) -> str:
|
def get(self, key: str) -> str:
|
||||||
|
if key in self._cleared:
|
||||||
|
return ""
|
||||||
if key in self._overrides:
|
if key in self._overrides:
|
||||||
return self._overrides[key]
|
return self._overrides[key]
|
||||||
if key in self._cache:
|
if key in self._cache:
|
||||||
@@ -46,7 +55,7 @@ class CredentialAccessor:
|
|||||||
row = self._rows.get(key)
|
row = self._rows.get(key)
|
||||||
if not row:
|
if not row:
|
||||||
return ""
|
return ""
|
||||||
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key), ring=self._ring_loader())
|
value = decrypt(row["encrypted_value"], aad=aad_for(self._code, key, self._ns), ring=self._ring_loader())
|
||||||
self._cache[key] = value
|
self._cache[key] = value
|
||||||
return value
|
return value
|
||||||
|
|
||||||
@@ -57,7 +66,7 @@ class CredentialAccessor:
|
|||||||
return
|
return
|
||||||
ring = self._ring_loader()
|
ring = self._ring_loader()
|
||||||
self._store.upsert_credential(
|
self._store.upsert_credential(
|
||||||
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key), ring=ring),
|
self._code, key, encrypted_value=encrypt(value, aad=aad_for(self._code, key, self._ns), ring=ring),
|
||||||
key_version=ring.current_version, user=self._user or "system",
|
key_version=ring.current_version, user=self._user or "system",
|
||||||
)
|
)
|
||||||
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
|
self._rows[key] = {"encrypted_value": "", "key_version": ring.current_version}
|
||||||
@@ -68,14 +77,17 @@ class CredentialAccessor:
|
|||||||
|
|
||||||
|
|
||||||
class CredentialService:
|
class CredentialService:
|
||||||
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing]) -> None:
|
"""store = 인증정보 저장소(쇼핑몰: PerformanceStore, 광고 API: db.AdCredentialTable). aad_ns = 암호문 이름 공간."""
|
||||||
|
|
||||||
|
def __init__(self, store: Any, ring_loader: Callable[[], KeyRing], *, aad_ns: str = "") -> None:
|
||||||
self._store = store
|
self._store = store
|
||||||
self._ring_loader = ring_loader
|
self._ring_loader = ring_loader
|
||||||
|
self._ns = aad_ns
|
||||||
|
|
||||||
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
|
def accessor(self, code: str, *, overrides: dict[str, str] | None = None, persist: bool = True,
|
||||||
user: str = "") -> CredentialAccessor:
|
user: str = "", cleared: set[str] | None = None) -> CredentialAccessor:
|
||||||
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
|
return CredentialAccessor(self._store, code, self._ring_loader, overrides=overrides,
|
||||||
persist=persist, user=user)
|
persist=persist, user=user, aad_ns=self._ns, cleared=cleared)
|
||||||
|
|
||||||
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
|
# ── 화면용 요약(비밀 원문 없음) ─────────────────────────
|
||||||
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
|
def describe(self, adapter: MarketplaceAdapter) -> dict[str, Any]:
|
||||||
@@ -87,11 +99,12 @@ class CredentialService:
|
|||||||
item: dict[str, Any] = {
|
item: dict[str, Any] = {
|
||||||
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
|
"key": f.key, "label": f.label, "secret": f.secret, "required": f.required,
|
||||||
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
|
"help": f.help, "placeholder": f.placeholder, "has_value": row is not None,
|
||||||
|
"multiline": bool(getattr(f, "multiline", False)),
|
||||||
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
|
"updated_at": row["updated_at"].isoformat(timespec="seconds") if row and row.get("updated_at") else "",
|
||||||
}
|
}
|
||||||
if row is not None and not f.secret:
|
if row is not None and not f.secret:
|
||||||
try:
|
try:
|
||||||
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key),
|
item["value"] = decrypt(row["encrypted_value"], aad=aad_for(adapter.code, f.key, self._ns),
|
||||||
ring=self._ring_loader())
|
ring=self._ring_loader())
|
||||||
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
|
except Exception as exc: # noqa: BLE001 — 키 없음/손상: 값 없이 안내만
|
||||||
item["value"] = ""
|
item["value"] = ""
|
||||||
@@ -127,23 +140,45 @@ class CredentialService:
|
|||||||
"""빈 칸 = 기존 값 유지. clear 에 든 항목은 삭제. 저장한 항목 키 목록 반환."""
|
"""빈 칸 = 기존 값 유지. clear 에 든 항목은 삭제. 저장한 항목 키 목록 반환."""
|
||||||
allowed = {f.key for f in adapter.visible_fields()}
|
allowed = {f.key for f in adapter.visible_fields()}
|
||||||
ring = self._ring_loader()
|
ring = self._ring_loader()
|
||||||
|
rows = self._store.credential_rows(adapter.code)
|
||||||
saved = []
|
saved = []
|
||||||
|
changed = False # 화면 항목이 실제로 바뀌었나 — 바뀌었으면 그 인증정보로 받은 토큰 등 내부 값을 지운다(F04)
|
||||||
for key, raw in values.items():
|
for key, raw in values.items():
|
||||||
if key not in allowed:
|
if key not in allowed:
|
||||||
continue
|
continue
|
||||||
v = (raw or "").strip()
|
v = (raw or "").strip()
|
||||||
if not v:
|
if not v:
|
||||||
continue
|
continue
|
||||||
|
if not changed and self._stored_value(adapter.code, key, rows) != v:
|
||||||
|
changed = True
|
||||||
self._store.upsert_credential(
|
self._store.upsert_credential(
|
||||||
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key), ring=ring),
|
adapter.code, key, encrypted_value=encrypt(v, aad=aad_for(adapter.code, key, self._ns), ring=ring),
|
||||||
key_version=ring.current_version, user=user,
|
key_version=ring.current_version, user=user,
|
||||||
)
|
)
|
||||||
saved.append(key)
|
saved.append(key)
|
||||||
for key in clear or []:
|
for key in clear or []:
|
||||||
if key in allowed and key not in saved:
|
if key in allowed and key not in saved:
|
||||||
|
if key in rows:
|
||||||
|
changed = True
|
||||||
self._store.delete_credential(adapter.code, key)
|
self._store.delete_credential(adapter.code, key)
|
||||||
|
if changed:
|
||||||
|
# 계정·키가 바뀌면 예전 계정으로 받은 토큰·만료 시각을 남기지 않는다. 같은 값을 다시 저장했으면 그대로 둔다
|
||||||
|
# (토큰을 불필요하게 다시 받지 않게). 어댑터도 토큰을 발급 인증정보 지문에 묶어 한 번 더 막는다.
|
||||||
|
for f in adapter.credential_fields():
|
||||||
|
if f.internal and f.key in rows:
|
||||||
|
self._store.delete_credential(adapter.code, f.key)
|
||||||
return saved
|
return saved
|
||||||
|
|
||||||
|
def _stored_value(self, code: str, key: str, rows: dict[str, Any]) -> str | None:
|
||||||
|
"""저장된 값 원문(서버 안에서만, 비교용) — 없거나 복호화할 수 없으면 None(= 바뀐 것으로 본다)."""
|
||||||
|
row = rows.get(key)
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return decrypt(row["encrypted_value"], aad=aad_for(code, key, self._ns), ring=self._ring_loader())
|
||||||
|
except Exception: # noqa: BLE001 — 키 교체·손상 등: 비교할 수 없으니 바뀐 것으로
|
||||||
|
return None
|
||||||
|
|
||||||
# ── 마스터 키 교체 후 재암호화 ─────────────────────────
|
# ── 마스터 키 교체 후 재암호화 ─────────────────────────
|
||||||
def reencrypt_all(self) -> dict[str, int]:
|
def reencrypt_all(self) -> dict[str, int]:
|
||||||
"""예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수)."""
|
"""예전 키 버전으로 된 암호문을 현재 키로 다시 암호화. (재암호화 수, 실패 수)."""
|
||||||
@@ -155,12 +190,12 @@ class CredentialService:
|
|||||||
continue
|
continue
|
||||||
code, key = row["marketplace_code"], row["credential_key"]
|
code, key = row["marketplace_code"], row["credential_key"]
|
||||||
try:
|
try:
|
||||||
plain = decrypt(token, aad=aad_for(code, key), ring=ring)
|
plain = decrypt(token, aad=aad_for(code, key, self._ns), ring=ring)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
failed += 1
|
failed += 1
|
||||||
continue
|
continue
|
||||||
self._store.upsert_credential(
|
self._store.upsert_credential(
|
||||||
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key), ring=ring),
|
code, key, encrypted_value=encrypt(plain, aad=aad_for(code, key, self._ns), ring=ring),
|
||||||
key_version=ring.current_version, user="rekey",
|
key_version=ring.current_version, user="rekey",
|
||||||
)
|
)
|
||||||
done += 1
|
done += 1
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ HTTP 와 무관하다(store 만 주입). 라우터는 파라미터 파싱·권
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
from decimal import Decimal
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
from typing import Any, Mapping, Sequence
|
from typing import Any, Mapping, Sequence
|
||||||
|
|
||||||
from . import calc
|
from . import calc
|
||||||
@@ -25,11 +25,97 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
|
|||||||
if not marketplace.get("enabled"):
|
if not marketplace.get("enabled"):
|
||||||
return "disabled"
|
return "disabled"
|
||||||
adapter = get_adapter(marketplace["code"])
|
adapter = get_adapter(marketplace["code"])
|
||||||
|
if adapter is not None and adapter.manual_only:
|
||||||
|
return "manual"
|
||||||
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
if adapter is not None and not adapter.uses_shared_integration and not configured:
|
||||||
return "not_configured"
|
return "not_configured"
|
||||||
return (status_row or {}).get("status") or "unknown"
|
return (status_row or {}).get("status") or "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
|
||||||
|
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
|
||||||
|
UNIT_COOKIE = "perf_unit"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_unit(value: Any) -> str:
|
||||||
|
return value if value in UNITS else "won"
|
||||||
|
|
||||||
|
|
||||||
|
def amount_text(value: Any, unit: str = "won") -> str:
|
||||||
|
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
|
||||||
|
div, places, _ = UNITS[normalize_unit(unit)]
|
||||||
|
if div == 1:
|
||||||
|
return f"{int(value):,}"
|
||||||
|
q = (Decimal(int(value)) / div).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
|
||||||
|
return f"{q:,.{places}f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any],
|
||||||
|
period: Any, q_start: date, q_end: date) -> None:
|
||||||
|
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
|
||||||
|
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합).
|
||||||
|
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
|
||||||
|
from . import ad_spend # noqa: WPS433
|
||||||
|
|
||||||
|
by_code = sales_ad_channels()
|
||||||
|
want = {ch for c in codes for ch, _ in by_code.get(c, ())}
|
||||||
|
for r in table:
|
||||||
|
r["ads"], r["ads_total"] = {}, None
|
||||||
|
if not want:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
amounts, _ = store.ad_amounts(q_start, q_end)
|
||||||
|
reader = getattr(store, "ad_roas", None)
|
||||||
|
roas_map = reader(q_start, q_end) if reader else {}
|
||||||
|
except Exception: # noqa: BLE001 — 광고비 표가 없어도 매출 화면은 그대로
|
||||||
|
return
|
||||||
|
spend_by: dict[str, list[tuple[date, int]]] = {}
|
||||||
|
for (d, ch), v in amounts.items():
|
||||||
|
if ch in want and v:
|
||||||
|
spend_by.setdefault(ch, []).append((d, int(v)))
|
||||||
|
|
||||||
|
sales_by: dict[str, list[tuple[date, int]]] = {}
|
||||||
|
for (d, c), m in cells.items():
|
||||||
|
sales_by.setdefault(c, []).append((d, int(m.gross)))
|
||||||
|
|
||||||
|
def spend(ch: str, s: date, e: date) -> int:
|
||||||
|
return sum(v for d, v in spend_by.get(ch, ()) if s <= d <= e)
|
||||||
|
|
||||||
|
def sales(c: str, s: date, e: date) -> int:
|
||||||
|
return sum(v for d, v in sales_by.get(c, ()) if s <= d <= e)
|
||||||
|
|
||||||
|
for r in table:
|
||||||
|
s = date.fromisoformat(r["from"]) if r.get("from") else period.start
|
||||||
|
e = date.fromisoformat(r["to"]) if r.get("to") else period.end
|
||||||
|
tot_spend = tot_sales = 0
|
||||||
|
for c in codes:
|
||||||
|
lines = []
|
||||||
|
for ch, label in by_code.get(c, ()):
|
||||||
|
amt = spend(ch, s, e)
|
||||||
|
if not amt:
|
||||||
|
continue
|
||||||
|
rs = ad_spend.channel_roas(ch, lambda m: sales(m, s, e), amt,
|
||||||
|
lambda f: ad_spend.file_roas(f, roas_map, amounts, s, e))
|
||||||
|
lines.append({"label": label, "amount": amt, "roas": rs})
|
||||||
|
tot_spend += amt
|
||||||
|
if lines:
|
||||||
|
r["ads"][c] = lines
|
||||||
|
tot_sales += sales(c, s, e)
|
||||||
|
if tot_spend:
|
||||||
|
r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, tot_spend)}
|
||||||
|
|
||||||
|
|
||||||
|
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
|
||||||
|
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
|
||||||
|
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
|
||||||
|
from . import ad_spend # noqa: WPS433
|
||||||
|
|
||||||
|
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
|
||||||
|
for ch, c in ad_spend.ROAS_SALES_CODE.items():
|
||||||
|
out[c] = out.get(c, ()) + ((ch, ""),)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
def build_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,
|
||||||
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
|
selected: Sequence[str] = (), holidays: Mapping[str, str] | None = None,
|
||||||
@@ -58,6 +144,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||||
q_end = max(period.end, year_period.end)
|
q_end = max(period.end, year_period.end)
|
||||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
||||||
|
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
||||||
|
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
|
||||||
|
manual_amounts = getattr(store, "manual_amounts", None)
|
||||||
|
manual_cells = sorted(f"{d.isoformat()}|{c}" for d, c in
|
||||||
|
(manual_amounts(period.start, period.end, manual_codes) if manual_amounts and manual_codes else {}))
|
||||||
|
|
||||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||||
@@ -98,6 +189,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
"error": (statuses.get(m["code"]) or {}).get("last_error", "")})
|
"error": (statuses.get(m["code"]) or {}).get("last_error", "")})
|
||||||
|
|
||||||
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
||||||
|
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||||
|
_ad_lines(store, table, codes, cells, period, q_start, q_end)
|
||||||
|
|
||||||
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||||
if kind == "custom":
|
if kind == "custom":
|
||||||
@@ -137,12 +230,16 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
|||||||
"short_names": short,
|
"short_names": short,
|
||||||
"selected_all": len(codes) == len(all_codes),
|
"selected_all": len(codes) == len(all_codes),
|
||||||
"kpis": kpis,
|
"kpis": kpis,
|
||||||
"table": calc.main_table(period, codes, cells, today=today, holidays=holidays),
|
"table": table,
|
||||||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
|
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
|
||||||
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
||||||
"chart_daily": calc.daily_series(period, codes, cells),
|
"chart_daily": calc.daily_series(period, codes, cells),
|
||||||
"chart_share": [{"code": c, "name": 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],
|
||||||
"problems": problems,
|
"problems": problems,
|
||||||
|
"manual_codes": manual_codes,
|
||||||
|
"manual_cells": manual_cells,
|
||||||
|
# 엑셀 업로드 대상 — 수동 입력이 켜진 쇼핑몰 전부(쇼핑몰 선택 필터와 무관, 설정 순서)
|
||||||
|
"manual_upload_names": [m["name"] for m in markets if m.get("manual_input")],
|
||||||
"last_update_at": store.last_update_at(),
|
"last_update_at": store.last_update_at(),
|
||||||
"running": store.running_codes(),
|
"running": store.running_codes(),
|
||||||
"no_marketplaces": not all_codes,
|
"no_marketplaces": not all_codes,
|
||||||
@@ -175,10 +272,11 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
|||||||
has_rate = bool(rates.get(adapter.code))
|
has_rate = bool(rates.get(adapter.code))
|
||||||
rows.append({
|
rows.append({
|
||||||
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
"code": adapter.code, "name": m["name"], "enabled": m["enabled"],
|
||||||
"include_in_sales": m["include_in_sales"],
|
"include_in_sales": m["include_in_sales"], "manual_input": bool(m.get("manual_input")),
|
||||||
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
"rate": _fmt_rate(cur_rate) if has_rate else "",
|
||||||
"rate_history": len(rates.get(adapter.code, ())),
|
"rate_history": len(rates.get(adapter.code, ())),
|
||||||
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
"auth_type": adapter.auth_type, "shared": adapter.uses_shared_integration,
|
||||||
|
"manual_only": adapter.manual_only,
|
||||||
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
"implemented": adapter.implemented, "note": adapter.note, "docs_url": adapter.docs_url,
|
||||||
"configured": configured.get(adapter.code, False),
|
"configured": configured.get(adapter.code, False),
|
||||||
"via_cafe24": adapter.code in via_cafe24,
|
"via_cafe24": adapter.code in via_cafe24,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from datetime import date, datetime, timedelta
|
|||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from psycopg import errors as pg_errors
|
||||||
from psycopg.rows import dict_row
|
from psycopg.rows import dict_row
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from psycopg_pool import ConnectionPool
|
from psycopg_pool import ConnectionPool
|
||||||
@@ -25,6 +26,10 @@ from app.timezone import to_kst_iso
|
|||||||
STALE_RUN_AFTER = timedelta(minutes=30)
|
STALE_RUN_AFTER = timedelta(minutes=30)
|
||||||
|
|
||||||
|
|
||||||
|
class ManualMigrationNeeded(Exception):
|
||||||
|
"""수동 입력(마이그레이션 002: perf_marketplaces.manual_input · perf_manual_sales)이 아직 적용되지 않음."""
|
||||||
|
|
||||||
|
|
||||||
def _iso(v: Any) -> Any:
|
def _iso(v: Any) -> Any:
|
||||||
if isinstance(v, datetime):
|
if isinstance(v, datetime):
|
||||||
return to_kst_iso(v)
|
return to_kst_iso(v)
|
||||||
@@ -56,8 +61,12 @@ class PerformanceDBStore:
|
|||||||
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
return [{k: _iso(v) for k, v in r.items()} for r in rows]
|
||||||
|
|
||||||
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
def update_marketplace(self, code: str, *, enabled: bool | None = None,
|
||||||
include_in_sales: bool | None = None) -> dict[str, Any] | None:
|
include_in_sales: bool | None = None,
|
||||||
|
manual_input: bool | None = None) -> dict[str, Any] | None:
|
||||||
sets, params = [], []
|
sets, params = [], []
|
||||||
|
if manual_input is not None:
|
||||||
|
sets.append("manual_input = %s")
|
||||||
|
params.append(bool(manual_input))
|
||||||
if enabled is not None:
|
if enabled is not None:
|
||||||
sets.append("enabled = %s")
|
sets.append("enabled = %s")
|
||||||
params.append(bool(enabled))
|
params.append(bool(enabled))
|
||||||
@@ -67,10 +76,13 @@ class PerformanceDBStore:
|
|||||||
if not sets:
|
if not sets:
|
||||||
return None
|
return None
|
||||||
params.append(code)
|
params.append(code)
|
||||||
with self._pool.connection() as conn:
|
try:
|
||||||
row = conn.execute(
|
with self._pool.connection() as conn:
|
||||||
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
row = conn.execute(
|
||||||
).fetchone()
|
f"UPDATE perf_marketplaces SET {', '.join(sets)} WHERE code = %s RETURNING *", params
|
||||||
|
).fetchone()
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
return {k: _iso(v) for k, v in row.items()} if row else None
|
return {k: _iso(v) for k, v in row.items()} if row else None
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -281,6 +293,8 @@ class PerformanceDBStore:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
def daily_amounts(self, start: date, end: date, codes: list[str]) -> dict[tuple[date, str], int]:
|
||||||
|
"""날짜 × 쇼핑몰 총매출. 수동 입력이 켜진 쇼핑몰은 수동 값을 넣은 날 그 값이 API 수집값을 대신한다
|
||||||
|
(실적 화면·회의록 머리 카드가 같은 숫자를 보게 여기서 합친다)."""
|
||||||
if not codes:
|
if not codes:
|
||||||
return {}
|
return {}
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
@@ -290,7 +304,170 @@ class PerformanceDBStore:
|
|||||||
"GROUP BY sales_date, marketplace_code",
|
"GROUP BY sales_date, marketplace_code",
|
||||||
(start, end, codes),
|
(start, end, codes),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
out = {(r["sales_date"], r["marketplace_code"]): int(r["amount"] or 0) for r in rows}
|
||||||
|
out.update(self.manual_amounts(start, end, codes))
|
||||||
|
return out
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 수동 입력 매출(마이그레이션 002)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def manual_amounts(self, start: date, end: date, codes: list[str], *,
|
||||||
|
active_only: bool = True) -> dict[tuple[date, str], int]:
|
||||||
|
"""수동 입력 값. active_only = 그 쇼핑몰 수동 입력이 켜진 것만(집계에 쓰는 값). 002 미적용이면 비어 있음."""
|
||||||
|
if not codes:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT s.sales_date, s.marketplace_code, s.amount FROM perf_manual_sales s "
|
||||||
|
"JOIN perf_marketplaces m ON m.code = s.marketplace_code "
|
||||||
|
"WHERE s.sales_date BETWEEN %s AND %s AND s.marketplace_code = ANY(%s)"
|
||||||
|
+ (" AND m.manual_input" if active_only else ""),
|
||||||
|
(start, end, codes),
|
||||||
|
).fetchall()
|
||||||
|
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||||
|
return {}
|
||||||
|
return {(r["sales_date"], r["marketplace_code"]): int(r["amount"]) for r in rows}
|
||||||
|
|
||||||
|
def api_amount(self, code: str, day: date) -> int:
|
||||||
|
"""그날 API 수집 합계(수동 값과 무관) — 수동 입력 칸에 참고로 보여 준다."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT COALESCE(SUM(amount), 0)::BIGINT AS amount FROM perf_sales_events "
|
||||||
|
"WHERE marketplace_code = %s AND sales_date = %s", (code, day),
|
||||||
|
).fetchone()
|
||||||
|
return int(row["amount"] or 0)
|
||||||
|
|
||||||
|
def set_manual_sale(self, code: str, day: date, amount: int | None, *, user: str = "") -> None:
|
||||||
|
"""수동 값 저장(amount None = 지움 → 그날은 다시 API 값)."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
if amount is None:
|
||||||
|
conn.execute("DELETE FROM perf_manual_sales WHERE marketplace_code = %s AND sales_date = %s",
|
||||||
|
(code, day))
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||||
|
(code, day, int(amount), user),
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
|
|
||||||
|
def set_manual_sales_bulk(self, entries: list[tuple[str, date, int]], *, user: str = "") -> int:
|
||||||
|
"""엑셀 업로드 — (쇼핑몰, 날짜, 금액) 여러 개를 한 트랜잭션으로 저장(덮어씀). 하나라도 실패하면 모두 취소."""
|
||||||
|
if not entries:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_manual_sales (marketplace_code, sales_date, amount, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s) ON CONFLICT (marketplace_code, sales_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, updated_by = EXCLUDED.updated_by",
|
||||||
|
[(code, day, int(amount), user) for code, day, amount in entries],
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise ManualMigrationNeeded() from None
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 광고비(마이그레이션 005)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def ad_amounts(self, start: date, end: date) -> tuple[dict[tuple[date, str], int], dict[tuple[date, str], str]]:
|
||||||
|
"""(날짜, 채널) → 금액, (날짜, 채널) → 입력 방식(manual/upload/api). 005 미적용이면 AdMigrationNeeded."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT spend_date, channel_code, amount, source FROM perf_ad_spend "
|
||||||
|
"WHERE spend_date BETWEEN %s AND %s", (start, end),
|
||||||
|
).fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded() from None
|
||||||
|
return ({(r["spend_date"], r["channel_code"]): int(r["amount"]) for r in rows},
|
||||||
|
{(r["spend_date"], r["channel_code"]): r["source"] for r in rows})
|
||||||
|
|
||||||
|
def set_ad_spend(self, code: str, day: date, amount: int | None, *, source: str = "manual", user: str = "") -> None:
|
||||||
|
"""광고비 한 칸 저장(amount None = 지움)."""
|
||||||
|
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code: str, entries: list[tuple[date, int | None]], *, source: str = "manual",
|
||||||
|
user: str = "", roas: dict[date, Any] | None = None,
|
||||||
|
metrics: dict[date, dict[str, Any]] | None = None) -> int:
|
||||||
|
"""여러 날을 한 트랜잭션으로(같은 날은 덮어씀, 금액 None 은 지움). 하나라도 실패하면 모두 취소.
|
||||||
|
roas·metrics 를 주면(보고서 업로드, 마이그레이션 006) 그 날의 ROAS·상세 항목도 덮어쓴다 — 안 주면(직접 입력) 그대로 둔다."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
if not entries:
|
||||||
|
return 0
|
||||||
|
report = roas is not None or metrics is not None
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
gone = [(code, d) for d, a in entries if a is None]
|
||||||
|
if gone:
|
||||||
|
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s", gone)
|
||||||
|
if report:
|
||||||
|
keep6 = [(code, d, int(a), source, user, (roas or {}).get(d),
|
||||||
|
Jsonb((metrics or {}).get(d)) if (metrics or {}).get(d) is not None else None)
|
||||||
|
for d, a in entries if a is not None]
|
||||||
|
if keep6:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
|
||||||
|
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
|
||||||
|
keep6,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
keep = [(code, d, int(a), source, user) for d, a in entries if a is not None]
|
||||||
|
if keep:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by",
|
||||||
|
keep,
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded("005") from None
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
raise AdMigrationNeeded("006") from None
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
def ad_roas(self, start: date, end: date) -> dict[tuple[date, str], Decimal]:
|
||||||
|
"""(날짜, 채널) → 보고서 ROAS(%) — 값이 있는 칸만. 005·006 미적용이면 빈 값(화면은 ROAS 없이)."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT spend_date, channel_code, roas FROM perf_ad_spend "
|
||||||
|
"WHERE spend_date BETWEEN %s AND %s AND roas IS NOT NULL", (start, end),
|
||||||
|
).fetchall()
|
||||||
|
except (pg_errors.UndefinedTable, pg_errors.UndefinedColumn):
|
||||||
|
return {}
|
||||||
|
return {(r["spend_date"], r["channel_code"]): r["roas"] for r in rows}
|
||||||
|
|
||||||
|
def ad_details(self, code: str, start: date, end: date) -> list[dict[str, Any]]:
|
||||||
|
"""한 채널의 일자별 광고비·ROAS·보고서 항목(날짜 순). 006 미적용이면 AdMigrationNeeded."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT spend_date, amount, roas, metrics, source FROM perf_ad_spend "
|
||||||
|
"WHERE channel_code = %s AND spend_date BETWEEN %s AND %s ORDER BY spend_date",
|
||||||
|
(code, start, end),
|
||||||
|
).fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded("005") from None
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
raise AdMigrationNeeded("006") from None
|
||||||
|
return [{"date": r["spend_date"].isoformat(), "amount": int(r["amount"]), "roas": r["roas"],
|
||||||
|
"metrics": r["metrics"] or {}, "source": r["source"]} for r in rows]
|
||||||
|
|
||||||
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
def daily_breakdown(self, code: str, start: date, end: date, *, id_prefix: str = "") -> list[dict[str, Any]]:
|
||||||
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
"""쇼핑몰 화면(일별 매출내역) 대조용 — 날짜별 결제(SALE 합·건수)·환불(그 밖, 양수)·마지막 수집 시각.
|
||||||
@@ -383,3 +560,167 @@ class PerformanceDBStore:
|
|||||||
(STALE_RUN_AFTER,),
|
(STALE_RUN_AFTER,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [r["marketplace_code"] for r in rows]
|
return [r["marketplace_code"] for r in rows]
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# 광고 API 연동(마이그레이션 007) — 인증정보(암호문)·연결 상태·가져온 광고비
|
||||||
|
# 읽기는 007 미적용이면 빈 값(설정 화면은 안내만), 쓰기는 AdMigrationNeeded("007").
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def ad_api_ready(self) -> bool:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("SELECT 1 FROM perf_ad_credentials LIMIT 1").fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def ad_credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT credential_key, encrypted_value, key_version, updated_at, updated_by "
|
||||||
|
"FROM perf_ad_credentials WHERE channel_code = %s", (code,),
|
||||||
|
).fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return {}
|
||||||
|
return {r["credential_key"]: r for r in rows}
|
||||||
|
|
||||||
|
def ad_credential_keys_by_code(self) -> dict[str, set[str]]:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT channel_code, credential_key FROM perf_ad_credentials").fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return {}
|
||||||
|
out: dict[str, set[str]] = {}
|
||||||
|
for r in rows:
|
||||||
|
out.setdefault(r["channel_code"], set()).add(r["credential_key"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def upsert_ad_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO perf_ad_credentials (channel_code, credential_key, encrypted_value, key_version, updated_by)
|
||||||
|
VALUES (%s, %s, %s, %s, %s)
|
||||||
|
ON CONFLICT (channel_code, credential_key) DO UPDATE
|
||||||
|
SET encrypted_value = EXCLUDED.encrypted_value, key_version = EXCLUDED.key_version,
|
||||||
|
updated_by = EXCLUDED.updated_by
|
||||||
|
""",
|
||||||
|
(code, key, encrypted_value, key_version, user),
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded("007") from None
|
||||||
|
|
||||||
|
def delete_ad_credential(self, code: str, key: str) -> None:
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute("DELETE FROM perf_ad_credentials WHERE channel_code = %s AND credential_key = %s", (code, key))
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded("007") from None
|
||||||
|
|
||||||
|
def all_ad_credential_rows(self) -> list[dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
return conn.execute(
|
||||||
|
"SELECT channel_code AS marketplace_code, credential_key, encrypted_value, key_version "
|
||||||
|
"FROM perf_ad_credentials"
|
||||||
|
).fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def ad_source_statuses(self) -> dict[str, dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM perf_ad_source_status").fetchall()
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return {}
|
||||||
|
return {r["channel_code"]: {k: _iso(v) for k, v in r.items()} for r in rows}
|
||||||
|
|
||||||
|
def record_ad_status(self, code: str, *, status: str, ok: bool, error: str = "", kind: str = "test") -> None:
|
||||||
|
"""연결 테스트(kind=test) 또는 가져오기(kind=sync) 결과. 오류가 없으면 예전 오류 문구는 그대로 둔다."""
|
||||||
|
if kind == "sync":
|
||||||
|
sql = """
|
||||||
|
INSERT INTO perf_ad_source_status (channel_code, status, last_sync_at, last_success_sync_at, last_error, last_error_at)
|
||||||
|
VALUES (%(c)s, %(s)s, now(), CASE WHEN %(ok)s THEN now() END, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
|
||||||
|
ON CONFLICT (channel_code) DO UPDATE
|
||||||
|
SET status = EXCLUDED.status, last_sync_at = now(),
|
||||||
|
last_success_sync_at = CASE WHEN %(ok)s THEN now() ELSE perf_ad_source_status.last_success_sync_at END,
|
||||||
|
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
|
||||||
|
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
|
||||||
|
"""
|
||||||
|
else:
|
||||||
|
sql = """
|
||||||
|
INSERT INTO perf_ad_source_status (channel_code, status, last_test_at, last_test_ok, last_error, last_error_at)
|
||||||
|
VALUES (%(c)s, %(s)s, now(), %(ok)s, %(e)s, CASE WHEN %(e)s = '' THEN NULL ELSE now() END)
|
||||||
|
ON CONFLICT (channel_code) DO UPDATE
|
||||||
|
SET status = EXCLUDED.status, last_test_at = now(), last_test_ok = %(ok)s,
|
||||||
|
last_error = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error ELSE %(e)s END,
|
||||||
|
last_error_at = CASE WHEN %(e)s = '' THEN perf_ad_source_status.last_error_at ELSE now() END
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
conn.execute(sql, {"c": code, "s": status, "ok": ok, "e": error})
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
return # 007 미적용 — 상태 기록만 못 함(가져오기 자체는 막지 않음)
|
||||||
|
|
||||||
|
def replace_ad_api_range(self, code: str, start: date, end: date,
|
||||||
|
days: list[tuple[date, int, Any, dict[str, Any] | None]], *, user: str = "") -> int:
|
||||||
|
"""광고 API 로 가져온 기간을 한 트랜잭션으로 반영 — days 의 날은 덮어쓰고(source='api', ROAS·보고서 항목 포함,
|
||||||
|
직접 입력·업로드 값이 있던 날도 API 값으로), 기간 안에서 API 가 돌려주지 않은 날은 **예전 API 값만** 지운다
|
||||||
|
(직접 입력·업로드 값은 그대로). days = [(날짜, 금액, ROAS, 항목)]. 반영한 날 수."""
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
keep = {d for d, _, _, _ in days}
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
old = cur.execute(
|
||||||
|
"SELECT spend_date FROM perf_ad_spend WHERE channel_code = %s AND source = 'api' "
|
||||||
|
"AND spend_date BETWEEN %s AND %s", (code, start, end),
|
||||||
|
).fetchall()
|
||||||
|
gone = [(code, r["spend_date"]) for r in old if r["spend_date"] not in keep]
|
||||||
|
if gone:
|
||||||
|
cur.executemany("DELETE FROM perf_ad_spend WHERE channel_code = %s AND spend_date = %s "
|
||||||
|
"AND source = 'api'", gone)
|
||||||
|
rows = [(code, d, int(a), "api", user, r, Jsonb(m) if m is not None else None) for d, a, r, m in days]
|
||||||
|
if rows:
|
||||||
|
cur.executemany(
|
||||||
|
"INSERT INTO perf_ad_spend (channel_code, spend_date, amount, source, updated_by, roas, metrics) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (channel_code, spend_date) DO UPDATE "
|
||||||
|
"SET amount = EXCLUDED.amount, source = EXCLUDED.source, updated_by = EXCLUDED.updated_by, "
|
||||||
|
"roas = EXCLUDED.roas, metrics = EXCLUDED.metrics",
|
||||||
|
rows,
|
||||||
|
)
|
||||||
|
except pg_errors.UndefinedTable:
|
||||||
|
raise AdMigrationNeeded("005") from None
|
||||||
|
except pg_errors.UndefinedColumn:
|
||||||
|
raise AdMigrationNeeded("006") from None
|
||||||
|
return len(days)
|
||||||
|
|
||||||
|
|
||||||
|
class AdCredentialTable:
|
||||||
|
"""광고 API 인증정보 표(perf_ad_credentials)를 쇼핑몰 인증정보 저장소와 같은 이름으로 — credentials.CredentialService 가
|
||||||
|
그대로 쓴다(저장·요약·재암호화). 채널 코드가 쇼핑몰 코드 자리에 들어간다."""
|
||||||
|
|
||||||
|
def __init__(self, store: Any) -> None:
|
||||||
|
self._store = store
|
||||||
|
|
||||||
|
def credential_rows(self, code: str) -> dict[str, dict[str, Any]]:
|
||||||
|
return self._store.ad_credential_rows(code)
|
||||||
|
|
||||||
|
def credential_keys_by_code(self) -> dict[str, set[str]]:
|
||||||
|
return self._store.ad_credential_keys_by_code()
|
||||||
|
|
||||||
|
def upsert_credential(self, code: str, key: str, *, encrypted_value: str, key_version: int, user: str = "") -> None:
|
||||||
|
self._store.upsert_ad_credential(code, key, encrypted_value=encrypted_value, key_version=key_version, user=user)
|
||||||
|
|
||||||
|
def delete_credential(self, code: str, key: str) -> None:
|
||||||
|
self._store.delete_ad_credential(code, key)
|
||||||
|
|
||||||
|
def all_credential_rows(self) -> list[dict[str, Any]]:
|
||||||
|
return self._store.all_ad_credential_rows()
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
"""외화 → 원화 날짜별 환율(2026-10-16 사용자 요청: 메타 USD 광고 계정 — "그날 환율로 원화 환산").
|
||||||
|
|
||||||
|
출처: Frankfurter(https://frankfurter.dev, API 키 없음) v2 `GET /v2/rates?base=USD"es=KRW&from=&to=`
|
||||||
|
— 여러 나라 중앙은행 고시 환율을 합친 값(blended)이고 주말·공휴일 포함 매일 있다. 서울외국환중개 매매기준율과는
|
||||||
|
조금(보통 0.5% 안쪽) 다를 수 있다. 응답: [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1357.92}, …]
|
||||||
|
그날 값이 없으면(오늘처럼 아직 안 나온 날 등) 그 앞 가장 가까운 날 값을 쓴다(LOOKBACK_DAYS 안).
|
||||||
|
지난 날(2일 이상 지난) 환율은 프로세스 안에 기억해 30분마다 도는 자동 업데이트가 같은 날을 다시 묻지 않게 한다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.timezone import today_kst
|
||||||
|
|
||||||
|
FX_API = "https://api.frankfurter.dev/v2/rates"
|
||||||
|
SOURCE_LABEL = "Frankfurter(중앙은행 고시 환율 종합)"
|
||||||
|
LOOKBACK_DAYS = 10 # 그날 환율이 없으면 이만큼 앞까지 찾는다
|
||||||
|
_SETTLED_AFTER = 2 # 오늘에서 이만큼 지난 날 환율만 기억(최근 값은 나중에 고시될 수 있음)
|
||||||
|
|
||||||
|
_cache_lock = threading.Lock()
|
||||||
|
_cache: dict[tuple[str, date], Decimal] = {}
|
||||||
|
|
||||||
|
|
||||||
|
class FxError(Exception):
|
||||||
|
"""환율을 가져오지 못함 — 문구는 화면에 그대로 보인다."""
|
||||||
|
|
||||||
|
|
||||||
|
def krw_rates(client: httpx.Client, currency: str, start: date, end: date, *, today: date | None = None) -> dict[date, Decimal]:
|
||||||
|
"""start~end(양 끝 포함) 날마다 1 {currency} = ? 원. 하루라도 못 정하면 FxError(일부만 환산해 저장하지 않게)."""
|
||||||
|
cur = (currency or "").upper()
|
||||||
|
if cur == "KRW":
|
||||||
|
return {start + timedelta(days=i): Decimal(1) for i in range((end - start).days + 1)}
|
||||||
|
days = [start + timedelta(days=i) for i in range((end - start).days + 1)]
|
||||||
|
with _cache_lock:
|
||||||
|
known = {d: _cache[(cur, d)] for d in days if (cur, d) in _cache}
|
||||||
|
if len(known) == len(days):
|
||||||
|
return known
|
||||||
|
fetched = _fetch(client, cur, start - timedelta(days=LOOKBACK_DAYS), end)
|
||||||
|
today = today or today_kst()
|
||||||
|
out: dict[date, Decimal] = {}
|
||||||
|
for d in days:
|
||||||
|
rate = next((fetched[d - timedelta(days=k)] for k in range(LOOKBACK_DAYS + 1) if d - timedelta(days=k) in fetched), None)
|
||||||
|
if rate is None:
|
||||||
|
raise FxError(f"{d.isoformat()} 의 {cur}→KRW 환율을 찾지 못했습니다({SOURCE_LABEL}).")
|
||||||
|
out[d] = rate
|
||||||
|
with _cache_lock:
|
||||||
|
for d, rate in out.items():
|
||||||
|
if d in fetched and (today - d).days >= _SETTLED_AFTER:
|
||||||
|
_cache[(cur, d)] = rate
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch(client: httpx.Client, cur: str, start: date, end: date) -> dict[date, Decimal]:
|
||||||
|
try:
|
||||||
|
resp = client.get(FX_API, params={"base": cur, "quotes": "KRW", "from": start.isoformat(), "to": end.isoformat()})
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise FxError(f"환율 서버({SOURCE_LABEL})에 연결하지 못했습니다({type(exc).__name__}).") from None
|
||||||
|
if resp.status_code != 200:
|
||||||
|
try:
|
||||||
|
msg = str((resp.json() or {}).get("message") or "")
|
||||||
|
except ValueError:
|
||||||
|
msg = ""
|
||||||
|
raise FxError(f"환율을 가져오지 못했습니다(HTTP {resp.status_code}{': ' + msg[:120] if msg else ''}).")
|
||||||
|
try:
|
||||||
|
rows = resp.json()
|
||||||
|
except ValueError:
|
||||||
|
raise FxError("환율 서버 응답을 읽을 수 없습니다.") from None
|
||||||
|
out: dict[date, Decimal] = {}
|
||||||
|
for r in rows if isinstance(rows, list) else []:
|
||||||
|
if not isinstance(r, dict) or str(r.get("quote") or "").upper() != "KRW":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
d = date.fromisoformat(str(r.get("date")))
|
||||||
|
rate = Decimal(str(r.get("rate")))
|
||||||
|
except (ValueError, InvalidOperation):
|
||||||
|
continue
|
||||||
|
if rate > 0:
|
||||||
|
out[d] = rate
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def clear_cache() -> None:
|
||||||
|
"""테스트용."""
|
||||||
|
with _cache_lock:
|
||||||
|
_cache.clear()
|
||||||
@@ -93,6 +93,17 @@ class ShopProgress(Progress):
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self.state = "saving"
|
self.state = "saving"
|
||||||
|
|
||||||
|
def begin_saving(self) -> None:
|
||||||
|
"""수집이 끝나 저장으로 넘어간다 — 중지·취소 확인과 running → saving 전환을 **같은 잠금 안에서** 한다.
|
||||||
|
stop() 도 같은 잠금으로 state 를 보고 받아들이므로, [중지]가 이 전환보다 먼저면 여기서 Cancelled(저장 안 함),
|
||||||
|
나중이면 stop() 이 False(저장 중이라 중지 불가)를 돌려준다 — 둘 다 받아들여지는 틈이 없다(2026-10-15 검토 F06).
|
||||||
|
마지막 API 호출 중이나 collect() 정리 중에 받아들인 [중지]도 여기서 반영된다."""
|
||||||
|
with self._lock:
|
||||||
|
if self.cancel_requested:
|
||||||
|
raise Cancelled("사용자가 이 쇼핑몰 업데이트를 중지했습니다." if self.stopped_only else
|
||||||
|
"사용자가 업데이트를 취소했습니다.")
|
||||||
|
self.state = "saving"
|
||||||
|
|
||||||
def finish(self, *, upserted: int, message: str = "") -> None:
|
def finish(self, *, upserted: int, message: str = "") -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok"
|
self.state, self.upserted, self.message, self.status = "done", int(upserted), message, "ok"
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
"""수동 입력 매출 엑셀 업로드 — 1열 날짜, 2열부터 쇼핑몰 이름 머리글(샘플: upload_sample.xlsx).
|
||||||
|
|
||||||
|
규칙
|
||||||
|
- 머리글(1행) 2열부터 = 쇼핑몰 이름. 설정의 이름·짧은 이름(네이버/토스)·코드 어느 것이든 되고 띄어쓰기·대소문자는 무시.
|
||||||
|
- 수동 입력이 켜진 쇼핑몰 열만 반영. 꺼진 쇼핑몰·모르는 이름 열은 건너뛰고 알려 준다.
|
||||||
|
- 값이 있는 칸만 반영(빈 칸은 그날 기존 값 그대로 — 지우지 않음). 0 은 값(0원)으로 저장.
|
||||||
|
- 날짜: 엑셀 날짜, 2026-10-12 · 2026.10.12 · 2026/10/12 · 20261012(뒤 요일 표기 무시). 앞으로의 날짜는 안 됨.
|
||||||
|
- 금액: 원 단위 정수(쉼표·"원" 허용, 소수는 반올림).
|
||||||
|
- 잘못된 칸이 하나라도 있으면 아무것도 저장하지 않고 오류 목록을 돌려준다(일부만 들어가 헷갈리지 않게).
|
||||||
|
|
||||||
|
HTTP·DB 와 무관한 순수 함수 — 라우터가 파일 바이트와 쇼핑몰 목록을 넘긴다.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||||
|
from typing import Any, Iterable, Mapping
|
||||||
|
|
||||||
|
MAX_FILE_BYTES = 5 * 1024 * 1024
|
||||||
|
MAX_DATA_ROWS = 2000
|
||||||
|
MAX_ERRORS = 30
|
||||||
|
MAX_AMOUNT = 10 ** 12 # 라우터 MAX_MANUAL_AMOUNT 와 같은 상한(원)
|
||||||
|
|
||||||
|
_EXCEL_EPOCH = date(1899, 12, 30)
|
||||||
|
_DATE_RE = re.compile(r"^(\d{4})\s*[-./년]\s*(\d{1,2})\s*[-./월]\s*(\d{1,2})")
|
||||||
|
_COMPACT_RE = re.compile(r"^(\d{4})(\d{2})(\d{2})(?!\d)")
|
||||||
|
|
||||||
|
|
||||||
|
class UploadError(ValueError):
|
||||||
|
"""파일 자체를 읽을 수 없음(형식·크기·머리글)."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParseResult:
|
||||||
|
entries: list[tuple[str, date, int]] = field(default_factory=list) # (쇼핑몰 코드, 날짜, 금액)
|
||||||
|
errors: list[str] = field(default_factory=list)
|
||||||
|
ignored: list[str] = field(default_factory=list) # 건너뛴 열(머리글 + 이유)
|
||||||
|
columns: list[str] = field(default_factory=list) # 반영 대상 쇼핑몰 코드(열 순서)
|
||||||
|
|
||||||
|
|
||||||
|
def _norm(text: Any) -> str:
|
||||||
|
return re.sub(r"\s+", "", str(text or "")).lower()
|
||||||
|
|
||||||
|
|
||||||
|
def _cell_ref(row: int, col: int) -> str:
|
||||||
|
letters = ""
|
||||||
|
n = col
|
||||||
|
while n:
|
||||||
|
n, r = divmod(n - 1, 26)
|
||||||
|
letters = chr(65 + r) + letters
|
||||||
|
return f"{letters}{row}"
|
||||||
|
|
||||||
|
|
||||||
|
def parse_date(value: Any) -> date | None:
|
||||||
|
"""날짜 칸 → date. 읽을 수 없으면 ValueError, 빈 칸이면 None."""
|
||||||
|
if value is None or (isinstance(value, str) and not value.strip()):
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||||
|
n = int(value)
|
||||||
|
if 19000101 <= n <= 29991231: # 20261012
|
||||||
|
return parse_date(str(n))
|
||||||
|
if 20000 <= n <= 80000: # 엑셀 날짜 일련번호(서식 없는 날짜)
|
||||||
|
return _EXCEL_EPOCH + timedelta(days=n)
|
||||||
|
raise ValueError
|
||||||
|
text = str(value).strip()
|
||||||
|
m = _DATE_RE.match(text) or _COMPACT_RE.match(text)
|
||||||
|
if not m:
|
||||||
|
raise ValueError
|
||||||
|
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_amount(value: Any) -> int | None:
|
||||||
|
"""금액 칸 → 원 단위 정수. 빈 칸이면 None, 숫자가 아니면 ValueError."""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
raise ValueError
|
||||||
|
if isinstance(value, (int, float, Decimal)):
|
||||||
|
num = Decimal(str(value))
|
||||||
|
else:
|
||||||
|
text = re.sub(r"[,\s원₩]", "", str(value))
|
||||||
|
if text == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
num = Decimal(text)
|
||||||
|
except InvalidOperation:
|
||||||
|
raise ValueError from None
|
||||||
|
if not num.is_finite():
|
||||||
|
raise ValueError
|
||||||
|
return int(num.quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||||
|
|
||||||
|
|
||||||
|
def header_aliases(markets: Iterable[Mapping[str, Any]], extra_names: Mapping[str, Iterable[str]] | None = None) -> dict[str, str]:
|
||||||
|
"""머리글로 쓸 수 있는 이름 → 쇼핑몰 코드. markets: code·name, extra_names: 코드별 다른 이름(어댑터 이름·짧은 이름)."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
for m in markets:
|
||||||
|
code = str(m["code"])
|
||||||
|
for alias in (code, m.get("name"), *((extra_names or {}).get(code) or ())):
|
||||||
|
key = _norm(alias)
|
||||||
|
if key:
|
||||||
|
out.setdefault(key, code)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def parse_workbook(content: bytes, *, markets: list[Mapping[str, Any]], today: date,
|
||||||
|
extra_names: Mapping[str, Iterable[str]] | None = None) -> ParseResult:
|
||||||
|
"""첫 시트를 읽어 (코드, 날짜, 금액) 목록을 만든다. markets: code·name·manual_input(설정 순서)."""
|
||||||
|
if not content:
|
||||||
|
raise UploadError("빈 파일입니다.")
|
||||||
|
if len(content) > MAX_FILE_BYTES:
|
||||||
|
raise UploadError("파일이 너무 큽니다(5MB 이하).")
|
||||||
|
try:
|
||||||
|
import openpyxl # noqa: WPS433
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(io.BytesIO(content), read_only=True, data_only=True)
|
||||||
|
except Exception: # noqa: BLE001 — 형식이 다르면 어떤 오류든 같은 안내
|
||||||
|
raise UploadError("엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.") from None
|
||||||
|
try:
|
||||||
|
ws = wb.worksheets[0]
|
||||||
|
rows = ws.iter_rows(values_only=True)
|
||||||
|
header = next(rows, None)
|
||||||
|
if not header or len(header) < 2:
|
||||||
|
raise UploadError("1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.")
|
||||||
|
|
||||||
|
aliases = header_aliases(markets, extra_names)
|
||||||
|
by_code = {str(m["code"]): m for m in markets}
|
||||||
|
res = ParseResult()
|
||||||
|
col_code: dict[int, str] = {} # 열 번호(0부터) → 반영할 쇼핑몰 코드
|
||||||
|
for idx, title in enumerate(header[1:], start=1):
|
||||||
|
if title is None or not str(title).strip():
|
||||||
|
continue
|
||||||
|
label = str(title).strip()
|
||||||
|
code = aliases.get(_norm(label))
|
||||||
|
if code is None:
|
||||||
|
res.ignored.append(f"{label}(알 수 없는 쇼핑몰)")
|
||||||
|
elif not by_code[code].get("manual_input"):
|
||||||
|
res.ignored.append(f"{label}(수동 입력 꺼짐)")
|
||||||
|
elif code in col_code.values():
|
||||||
|
res.errors.append(f"{_cell_ref(1, idx + 1)} {label}: 같은 쇼핑몰 열이 두 번 있습니다.")
|
||||||
|
else:
|
||||||
|
col_code[idx] = code
|
||||||
|
res.columns.append(code)
|
||||||
|
if not col_code and not res.errors:
|
||||||
|
raise UploadError("반영할 쇼핑몰 열이 없습니다. 머리글을 수동 입력이 켜진 쇼핑몰 이름으로 적어 주세요."
|
||||||
|
+ (f" (건너뛴 열: {', '.join(res.ignored)})" if res.ignored else ""))
|
||||||
|
|
||||||
|
seen: dict[tuple[str, date], str] = {}
|
||||||
|
data_rows = 0
|
||||||
|
for r, row in enumerate(rows, start=2):
|
||||||
|
row = tuple(row or ())
|
||||||
|
cells = {i: (row[i] if i < len(row) else None) for i in col_code}
|
||||||
|
amounts: dict[int, int] = {}
|
||||||
|
for i, raw in cells.items():
|
||||||
|
try:
|
||||||
|
amt = parse_amount(raw)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 숫자가 아닙니다({raw}).")
|
||||||
|
continue
|
||||||
|
if amt is None:
|
||||||
|
continue
|
||||||
|
if abs(amt) > MAX_AMOUNT:
|
||||||
|
res.errors.append(f"{_cell_ref(r, i + 1)}: 금액이 너무 큽니다.")
|
||||||
|
continue
|
||||||
|
amounts[i] = amt
|
||||||
|
raw_day = row[0] if row else None
|
||||||
|
try:
|
||||||
|
day = parse_date(raw_day)
|
||||||
|
except ValueError:
|
||||||
|
res.errors.append(f"{_cell_ref(r, 1)}: 날짜를 읽을 수 없습니다({raw_day}).")
|
||||||
|
continue
|
||||||
|
if day is None:
|
||||||
|
if amounts:
|
||||||
|
res.errors.append(f"{r}행: 날짜가 비어 있습니다.")
|
||||||
|
continue
|
||||||
|
if not amounts:
|
||||||
|
continue
|
||||||
|
data_rows += 1
|
||||||
|
if data_rows > MAX_DATA_ROWS:
|
||||||
|
raise UploadError(f"한 번에 {MAX_DATA_ROWS:,}일까지 올릴 수 있습니다.")
|
||||||
|
if day > today:
|
||||||
|
res.errors.append(f"{_cell_ref(r, 1)}: 앞으로의 날짜({day.isoformat()})는 입력할 수 없습니다.")
|
||||||
|
continue
|
||||||
|
for i, amt in amounts.items():
|
||||||
|
code = col_code[i]
|
||||||
|
where = _cell_ref(r, i + 1)
|
||||||
|
if (code, day) in seen:
|
||||||
|
res.errors.append(f"{where}: {by_code[code]['name']} {day.isoformat()} 이 {seen[(code, day)]} 와 겹칩니다.")
|
||||||
|
continue
|
||||||
|
seen[(code, day)] = where
|
||||||
|
res.entries.append((code, day, amt))
|
||||||
|
if len(res.errors) > MAX_ERRORS:
|
||||||
|
break
|
||||||
|
return res
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
화면
|
화면
|
||||||
GET /performance/ 대시보드(모듈 권한)
|
GET /performance/ 대시보드(모듈 권한)
|
||||||
|
GET /performance/ads 광고비(모듈 권한) — 구글·메타·쿠팡(윙)·쿠팡(로켓) 연·월·일
|
||||||
GET /performance/settings 실적 설정(관리자)
|
GET /performance/settings 실적 설정(관리자)
|
||||||
JSON API — 모듈 권한
|
JSON API — 모듈 권한
|
||||||
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
POST /performance/api/sync 매출 업데이트(사용 중인 쇼핑몰 전부, 쇼핑몰별 실패 격리)
|
||||||
@@ -10,8 +11,18 @@ JSON API — 모듈 권한
|
|||||||
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
GET /performance/api/sync/current 지금 돌고 있는 업데이트(없으면 null)
|
||||||
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
POST /performance/api/sync/jobs/{id}/cancel 업데이트 취소(시작한 사람 또는 관리자)
|
||||||
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
GET /performance/api/events 금액 클릭 상세(쇼핑몰+기간)
|
||||||
|
PUT /performance/api/manual-sales/{code}/{day} 수동 입력 매출 저장/지움(그 쇼핑몰 수동 입력이 켜져 있을 때, 오늘까지)
|
||||||
|
GET /performance/api/manual-sales/sample.xlsx 수동 입력 엑셀 업로드 샘플(모듈 폴더 upload_sample.xlsx)
|
||||||
|
POST /performance/api/manual-sales/upload 수동 입력 엑셀 업로드(1열 날짜, 2열부터 쇼핑몰 이름 머리글)
|
||||||
|
PUT /performance/api/ad-spend/{channel}/{day} 광고비 한 칸 저장/지움(오늘까지)
|
||||||
|
POST /performance/api/ad-spend/upload?channel= 광고비 파일 업로드(쿠팡 윙·로켓 광고 보고서 1열 날짜·19열 청구금액,
|
||||||
|
네이버 광고 보고서 3열 기간·4열 총비용·12열 ROAS + 나머지 항목)
|
||||||
|
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
|
||||||
|
POST /performance/api/ad-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
|
||||||
JSON API — 관리자
|
JSON API — 관리자
|
||||||
PUT /performance/api/marketplaces/{code} 사용/매출 집계 여부
|
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
|
||||||
|
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
|
||||||
|
PUT /performance/api/marketplaces/{code} 사용/매출 집계/수동 입력 여부
|
||||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||||
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
GET /performance/api/marketplaces/{code}/credentials 입력칸 + 저장 여부(비밀 원문 없음)
|
||||||
@@ -26,12 +37,13 @@ JSON API — 관리자
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import date
|
from datetime import date, timedelta
|
||||||
from decimal import Decimal, InvalidOperation
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
from fastapi import APIRouter, Body, File, Form, HTTPException, Query, Request, UploadFile
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||||
|
|
||||||
from app.timezone import today_kst
|
from app.timezone import today_kst
|
||||||
|
|
||||||
@@ -44,6 +56,21 @@ 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 # 수동 입력 한 칸 상한(원)
|
||||||
|
MANUAL_SAMPLE_PATH = Path(__file__).resolve().parent / "upload_sample.xlsx"
|
||||||
|
AD_MIGRATION_HELP = ("광고비를 쓰려면 performance_db 마이그레이션 005(scripts/sql/performance_db_005_ad_spend.sql)를 "
|
||||||
|
"먼저 적용해야 합니다.")
|
||||||
|
AD_MIGRATION_HELP_006 = ("광고 보고서 ROAS·상세 항목을 쓰려면 performance_db 마이그레이션 006"
|
||||||
|
"(scripts/sql/performance_db_006_ad_roas_metrics.sql)을 먼저 적용해야 합니다.")
|
||||||
|
AD_MIGRATION_HELP_007 = ("광고 API 연동(구글 광고) 인증정보를 저장하려면 performance_db 마이그레이션 007"
|
||||||
|
"(scripts/sql/performance_db_007_ad_api.sql)을 먼저 적용해야 합니다.")
|
||||||
|
|
||||||
|
|
||||||
|
def _ad_migration_help(exc: Exception) -> str:
|
||||||
|
text = str(exc)
|
||||||
|
return AD_MIGRATION_HELP_007 if "007" in text else AD_MIGRATION_HELP_006 if "006" in text else AD_MIGRATION_HELP
|
||||||
|
MANUAL_MIGRATION_HELP = ("수동 입력을 쓰려면 performance_db 마이그레이션 002(scripts/sql/performance_db_002_manual_sales.sql)를 "
|
||||||
|
"먼저 적용해야 합니다.")
|
||||||
|
|
||||||
|
|
||||||
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||||
@@ -108,9 +135,52 @@ def dashboard_page(
|
|||||||
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())),
|
||||||
)
|
)
|
||||||
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
|
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross"
|
||||||
|
_unit_ctx(request, ctx)
|
||||||
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})
|
||||||
|
|
||||||
|
|
||||||
|
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
||||||
|
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
|
||||||
|
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
|
||||||
|
|
||||||
|
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
|
||||||
|
ctx["unit"] = unit
|
||||||
|
ctx["unit_label"] = UNITS[unit][2]
|
||||||
|
ctx["amt"] = lambda v: amount_text(v, unit)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/ads", response_class=HTMLResponse)
|
||||||
|
def ads_page(
|
||||||
|
request: Request,
|
||||||
|
period: str = "month",
|
||||||
|
d: str | None = None,
|
||||||
|
from_: str | None = Query(None, alias="from"),
|
||||||
|
to: str | None = None,
|
||||||
|
):
|
||||||
|
from app.main import render_template # noqa: WPS433
|
||||||
|
|
||||||
|
g = common.guard(request)
|
||||||
|
if not isinstance(g, tuple):
|
||||||
|
return g
|
||||||
|
store, user = g
|
||||||
|
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||||
|
from .dashboard import _sales_marketplaces # noqa: WPS433
|
||||||
|
|
||||||
|
today = today_kst()
|
||||||
|
ctx = build_ad_dashboard(
|
||||||
|
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||||
|
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||||
|
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||||
|
)
|
||||||
|
# [구글 광고 불러오기] — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동만
|
||||||
|
from .ad_sources.registry import get_source # noqa: WPS433
|
||||||
|
|
||||||
|
_, ad_sync = _ad_services(store)
|
||||||
|
ctx["ad_sync_sources"] = [{"code": c, "name": get_source(c).name} for c, ok in ad_sync.configured().items() if ok]
|
||||||
|
return render_template(request, "performance/ads.html",
|
||||||
|
{**common.base_ctx(user, active_tab="ads", 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
|
||||||
@@ -123,14 +193,38 @@ def settings_page(request: Request):
|
|||||||
from .dashboard import build_settings # noqa: WPS433
|
from .dashboard import build_settings # noqa: WPS433
|
||||||
|
|
||||||
creds, _ = common.services(request, store)
|
creds, _ = common.services(request, store)
|
||||||
|
ad_creds, ad_sync = _ad_services(store)
|
||||||
|
versions = creds.key_versions_in_use()
|
||||||
|
for v, n in ad_creds.key_versions_in_use().items(): # 광고 API 인증정보도 같은 마스터 키
|
||||||
|
versions[v] = versions.get(v, 0) + n
|
||||||
ctx = build_settings(
|
ctx = build_settings(
|
||||||
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
store, configured=creds.configured_codes(list(all_adapters())), key_info=common.key_status(),
|
||||||
key_versions_in_use=creds.key_versions_in_use(), sample_count=store.sample_count(),
|
key_versions_in_use=versions, sample_count=store.sample_count(),
|
||||||
)
|
)
|
||||||
|
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
||||||
|
ctx["ad_api_ready"] = store.ad_api_ready()
|
||||||
|
_unit_ctx(request, ctx)
|
||||||
return render_template(request, "performance/settings.html",
|
return render_template(request, "performance/settings.html",
|
||||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||||
|
|
||||||
|
|
||||||
|
def _ad_source_rows(store: Any, configured: dict[str, bool]) -> list[dict[str, Any]]:
|
||||||
|
"""실적 설정 "광고 API 연동" 표 — 연동마다 설정 여부·연결 상태·마지막 가져오기."""
|
||||||
|
from .ad_sources.registry import all_sources # noqa: WPS433
|
||||||
|
from .adapters.base import STATUS_LABELS # noqa: WPS433
|
||||||
|
|
||||||
|
statuses = store.ad_source_statuses()
|
||||||
|
rows = []
|
||||||
|
for s in all_sources():
|
||||||
|
st = statuses.get(s.code, {})
|
||||||
|
status = st.get("status") or ("unknown" if configured.get(s.code) else "not_configured")
|
||||||
|
rows.append({"code": s.code, "name": s.name, "configured": bool(configured.get(s.code)), "status": status,
|
||||||
|
"status_label": STATUS_LABELS.get(status, status), "last_test_at": st.get("last_test_at"),
|
||||||
|
"last_error": st.get("last_error") or "", "last_error_at": st.get("last_error_at"),
|
||||||
|
"last_sync_at": st.get("last_sync_at"), "last_success_sync_at": st.get("last_success_sync_at")})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# JSON API — 모듈 권한
|
# JSON API — 모듈 권한
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -270,6 +364,306 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
|||||||
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
return JSONResponse({"rows": rows, "truncated": len(rows) >= 500})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/manual-sales/{code}/{day}")
|
||||||
|
def api_manual_sale(request: Request, code: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""수동 입력 — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지. amount 가 비면 지움(그날은 다시 API 값)."""
|
||||||
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request) # 모듈 권한자 누구나(켜고 끄기는 관리자 설정)
|
||||||
|
_code_or_404(store, code)
|
||||||
|
d = _parse_date(day)
|
||||||
|
if d > today_kst():
|
||||||
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||||
|
m = next((x for x in store.list_marketplaces() if x["code"] == code), {})
|
||||||
|
if not m.get("manual_input"):
|
||||||
|
raise HTTPException(status_code=400, detail="이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).")
|
||||||
|
raw = payload.get("amount")
|
||||||
|
amount: int | None
|
||||||
|
if raw in (None, ""):
|
||||||
|
amount = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||||
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||||
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||||
|
try:
|
||||||
|
store.set_manual_sale(code, d, amount, user=user.get("email", ""))
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
|
api_amount = store.api_amount(code, d)
|
||||||
|
return JSONResponse({"ok": True, "code": code, "date": d.isoformat(), "manual": amount,
|
||||||
|
"amount": api_amount if amount is None else amount, "api_amount": api_amount})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/manual-sales/sample.xlsx")
|
||||||
|
def api_manual_sample(request: Request) -> Any:
|
||||||
|
common.require_store(request)
|
||||||
|
if not MANUAL_SAMPLE_PATH.is_file():
|
||||||
|
raise HTTPException(status_code=404, detail="샘플 파일이 없습니다.")
|
||||||
|
return FileResponse(MANUAL_SAMPLE_PATH, filename="upload_sample.xlsx",
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/manual-sales/upload")
|
||||||
|
def api_manual_upload(request: Request, file: UploadFile = File(...)) -> JSONResponse:
|
||||||
|
"""수동 입력 엑셀 업로드 — 값이 있는 칸만 반영(덮어씀). 잘못된 칸이 있으면 아무것도 저장하지 않는다."""
|
||||||
|
from . import manual_upload # noqa: WPS433
|
||||||
|
from .dashboard import _short_name # noqa: WPS433
|
||||||
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request) # 날짜 칸 수동 입력과 같은 권한(모듈 권한자 누구나)
|
||||||
|
content = file.file.read(manual_upload.MAX_FILE_BYTES + 1)
|
||||||
|
known = {a.code: a for a in all_adapters()}
|
||||||
|
markets = [m for m in store.list_marketplaces() if m["code"] in known and m["enabled"]]
|
||||||
|
extra = {m["code"]: (known[m["code"]].name, _short_name(m["name"])) for m in markets}
|
||||||
|
try:
|
||||||
|
res = manual_upload.parse_workbook(content, markets=markets, today=today_kst(), extra_names=extra)
|
||||||
|
except manual_upload.UploadError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||||
|
names = {m["code"]: m["name"] for m in markets}
|
||||||
|
if res.errors:
|
||||||
|
return JSONResponse(status_code=400, content={
|
||||||
|
"detail": f"잘못된 칸이 {len(res.errors)}개{'+' if len(res.errors) > manual_upload.MAX_ERRORS else ''} 있어 "
|
||||||
|
"아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||||
|
"errors": res.errors[:manual_upload.MAX_ERRORS], "ignored": res.ignored})
|
||||||
|
try:
|
||||||
|
saved = store.set_manual_sales_bulk(res.entries, user=user.get("email", ""))
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
for code, _, _ in res.entries:
|
||||||
|
counts[code] = counts.get(code, 0) + 1
|
||||||
|
days = sorted({d for _, d, _ in res.entries})
|
||||||
|
return JSONResponse({
|
||||||
|
"ok": True, "saved": saved,
|
||||||
|
"by_shop": [{"code": c, "name": names.get(c, c), "count": counts[c]} for c in res.columns if counts.get(c)],
|
||||||
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None,
|
||||||
|
"ignored": res.ignored,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# JSON API — 광고비(모듈 권한자 누구나)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _ad_channel(channel: str) -> str:
|
||||||
|
from .ad_spend import CHANNEL_NAMES # noqa: WPS433
|
||||||
|
|
||||||
|
if channel not in CHANNEL_NAMES:
|
||||||
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 채널입니다.")
|
||||||
|
return channel
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/ad-spend/{channel}/{day}")
|
||||||
|
def api_ad_spend(request: Request, channel: str, day: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
_ad_channel(channel)
|
||||||
|
d = _parse_date(day)
|
||||||
|
if d is None:
|
||||||
|
raise HTTPException(status_code=400, detail="날짜가 필요합니다.")
|
||||||
|
if d > today_kst():
|
||||||
|
raise HTTPException(status_code=400, detail="앞으로의 날짜는 입력할 수 없습니다.")
|
||||||
|
raw = payload.get("amount")
|
||||||
|
amount: int | None
|
||||||
|
if raw in (None, ""):
|
||||||
|
amount = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
amount = int(Decimal(str(raw).replace(",", "").strip()))
|
||||||
|
except (InvalidOperation, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="금액은 숫자(원)로 입력하세요.") from None
|
||||||
|
if abs(amount) > MAX_MANUAL_AMOUNT:
|
||||||
|
raise HTTPException(status_code=400, detail="금액이 너무 큽니다.")
|
||||||
|
try:
|
||||||
|
store.set_ad_spend(channel, d, amount, source="manual", user=user.get("email", ""))
|
||||||
|
except AdMigrationNeeded as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||||
|
return JSONResponse({"ok": True, "channel": channel, "date": d.isoformat(), "manual": amount,
|
||||||
|
"amount": amount or 0})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/ad-spend/{channel}/details")
|
||||||
|
def api_ad_spend_details(request: Request, channel: str, from_: str = Query(..., alias="from"), to: str = Query(...)) -> JSONResponse:
|
||||||
|
"""일자별 보고서 항목(네이버 — 노출수·클릭수·전환수 …) + 광고비·ROAS. 최대 366일."""
|
||||||
|
from . import ad_spend # noqa: WPS433
|
||||||
|
|
||||||
|
store, _ = common.require_store(request)
|
||||||
|
_ad_channel(channel)
|
||||||
|
if channel not in ad_spend.DETAIL_CHANNELS:
|
||||||
|
raise HTTPException(status_code=400, detail="이 채널은 일자별 상세 자료가 없습니다.")
|
||||||
|
start, end = _parse_date(from_, field="시작일"), _parse_date(to, field="종료일")
|
||||||
|
if start is None or end is None or end < start or (end - start).days > 365:
|
||||||
|
raise HTTPException(status_code=400, detail="기간을 확인하세요(최대 366일).")
|
||||||
|
try:
|
||||||
|
rows = store.ad_details(channel, start, end)
|
||||||
|
except ad_spend.AdMigrationNeeded as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||||
|
return JSONResponse({"channel": channel, "name": ad_spend.CHANNEL_NAMES[channel], "from": start.isoformat(),
|
||||||
|
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/ad-spend/upload")
|
||||||
|
def api_ad_spend_upload(
|
||||||
|
request: Request,
|
||||||
|
channel: str = Query(...),
|
||||||
|
files: list[UploadFile] | None = File(None),
|
||||||
|
file: UploadFile | None = File(None),
|
||||||
|
modified: list[str] = Form(default=[]),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""광고비 파일 업로드(여러 파일 가능, 2026-10-14) — 파일에 있는 날만 덮어쓴다. 같은 날짜가 여러 파일에 있으면
|
||||||
|
파일 날짜(브라우저가 보낸 수정 시각 modified, 파일 순서대로 ms)가 최신인 파일 값. 잘못된 줄이 하나라도 있으면 아무것도 저장하지 않는다."""
|
||||||
|
from . import ad_spend # noqa: WPS433
|
||||||
|
from .manual_upload import MAX_FILE_BYTES, UploadError # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
_ad_channel(channel)
|
||||||
|
parser = ad_spend.PARSERS.get(channel)
|
||||||
|
if parser is None:
|
||||||
|
raise HTTPException(status_code=400, detail=f"{ad_spend.CHANNEL_NAMES[channel]} 업로드 양식은 아직 정해지지 않았습니다.")
|
||||||
|
uploads = list(files or []) + ([file] if file is not None else [])
|
||||||
|
if not uploads:
|
||||||
|
raise HTTPException(status_code=400, detail="파일을 고르세요.")
|
||||||
|
if len(uploads) > ad_spend.MAX_UPLOAD_FILES:
|
||||||
|
raise HTTPException(status_code=400, detail=f"한 번에 {ad_spend.MAX_UPLOAD_FILES}개 파일까지 올릴 수 있습니다.")
|
||||||
|
parsed = []
|
||||||
|
for i, up in enumerate(uploads):
|
||||||
|
name = up.filename or f"파일{i + 1}"
|
||||||
|
try:
|
||||||
|
mtime = float(modified[i]) if i < len(modified) and str(modified[i]).strip() else 0.0
|
||||||
|
except ValueError:
|
||||||
|
mtime = 0.0
|
||||||
|
try:
|
||||||
|
parsed.append((name, mtime, parser(up.file.read(MAX_FILE_BYTES + 1), today=today_kst(), filename=name)))
|
||||||
|
except UploadError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=(f"[{name}] " if len(uploads) > 1 else "") + str(exc)) from None
|
||||||
|
res, overlap = ad_spend.merge_results(parsed)
|
||||||
|
if res.errors:
|
||||||
|
return JSONResponse(status_code=400, content={
|
||||||
|
"detail": f"잘못된 줄이 {len(res.errors)}개 있어 아무것도 저장하지 않았습니다. 고친 뒤 다시 올려 주세요.",
|
||||||
|
"errors": res.errors[:60]})
|
||||||
|
report = {"roas": res.roas, "metrics": res.metrics} if (res.roas or res.metrics) else {}
|
||||||
|
try:
|
||||||
|
saved = store.set_ad_spend_bulk(channel, list(res.entries), source="upload", user=user.get("email", ""), **report)
|
||||||
|
except ad_spend.AdMigrationNeeded as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||||
|
days = sorted(d for d, _ in res.entries)
|
||||||
|
return JSONResponse({"ok": True, "saved": saved, "channel": channel, "name": ad_spend.CHANNEL_NAMES[channel],
|
||||||
|
"total": sum(a for _, a in res.entries), "skipped": res.skipped, "files": len(uploads),
|
||||||
|
"overlap_days": len(overlap), "empty_days": [d.isoformat() for d in res.empty_days[:62]],
|
||||||
|
"from": days[0].isoformat() if days else None, "to": days[-1].isoformat() if days else None})
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# JSON API — 광고 API 연동(구글 광고). 인증정보·연결 테스트는 관리자, 가져오기는 모듈 권한자(92일 넘으면 관리자)
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
def _ad_services(store: Any):
|
||||||
|
"""(광고 인증정보 서비스, 광고 가져오기 서비스)."""
|
||||||
|
from .ad_sync import AdSyncService, ad_credentials # noqa: WPS433
|
||||||
|
|
||||||
|
creds = ad_credentials(store, common.key_ring)
|
||||||
|
return creds, AdSyncService(store, creds)
|
||||||
|
|
||||||
|
|
||||||
|
def _ad_source_or_404(code: str):
|
||||||
|
from .ad_sources.registry import get_source # noqa: WPS433
|
||||||
|
|
||||||
|
src = get_source(code)
|
||||||
|
if src is None:
|
||||||
|
raise HTTPException(status_code=404, detail="알 수 없는 광고 연동입니다.")
|
||||||
|
return src
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/ad-sources/{code}/credentials")
|
||||||
|
def api_ad_source_credentials(request: Request, code: str) -> JSONResponse:
|
||||||
|
"""입력칸 + 저장 여부만(비밀 원문 없음) — 쇼핑몰 API 설정 창과 같은 모양."""
|
||||||
|
store, _ = common.require_store(request, admin=True)
|
||||||
|
src = _ad_source_or_404(code)
|
||||||
|
creds, _ = _ad_services(store)
|
||||||
|
info = creds.describe(src)
|
||||||
|
if not store.ad_api_ready():
|
||||||
|
info["decrypt_error"] = AD_MIGRATION_HELP_007
|
||||||
|
return JSONResponse({"code": code, "name": src.name, "shared": False, "note": src.note, "docs_url": src.docs_url,
|
||||||
|
"key": common.key_status(), **info})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/ad-sources/{code}/credentials")
|
||||||
|
def api_ad_source_save(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request, admin=True)
|
||||||
|
src = _ad_source_or_404(code)
|
||||||
|
if not common.key_status()["ok"]:
|
||||||
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||||
|
creds, _ = _ad_services(store)
|
||||||
|
values = _clean_values(src, payload)
|
||||||
|
clear = [str(k) for k in (payload.get("clear") or [])]
|
||||||
|
merged = creds.merged_values(src, values)
|
||||||
|
for k in clear:
|
||||||
|
if k in merged and not values.get(k):
|
||||||
|
merged[k] = ""
|
||||||
|
errors = src.validate_credentials(merged)
|
||||||
|
if errors:
|
||||||
|
raise HTTPException(status_code=400, detail=" ".join(errors))
|
||||||
|
try:
|
||||||
|
saved = creds.save(src, values, clear=clear, user=user["email"])
|
||||||
|
except AdMigrationNeeded as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||||
|
return JSONResponse({"saved": saved, **creds.describe(src)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/ad-sources/{code}/test")
|
||||||
|
def api_ad_source_test(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값)."""
|
||||||
|
store, user = common.require_store(request, admin=True)
|
||||||
|
src = _ad_source_or_404(code)
|
||||||
|
_, ad_sync = _ad_services(store)
|
||||||
|
values = {k: v for k, v in _clean_values(src, payload).items() if v.strip()}
|
||||||
|
cleared = _cleared_keys(src, payload, values)
|
||||||
|
return JSONResponse(ad_sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/ad-sources/{code}/sync")
|
||||||
|
def api_ad_source_sync(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""광고비 탭 [구글 광고 불러오기] — 기간(from·to, 없으면 최근 N일)을 가져와 저장. 오늘 뒤는 잘라낸다.
|
||||||
|
모듈 권한자는 92일까지, 그보다 길면(최대 366일) 관리자만."""
|
||||||
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
|
from .ad_spend import AdMigrationNeeded # noqa: WPS433
|
||||||
|
from .ad_sync import AdSyncBusy # noqa: WPS433
|
||||||
|
from .auto_sync import sync_days # noqa: WPS433
|
||||||
|
|
||||||
|
store, user = common.require_store(request)
|
||||||
|
src = _ad_source_or_404(code)
|
||||||
|
today = today_kst()
|
||||||
|
end = _parse_date(payload.get("to"), field="종료일") or today
|
||||||
|
start = _parse_date(payload.get("from"), field="시작일") or (end - timedelta(days=sync_days() - 1))
|
||||||
|
if end < start:
|
||||||
|
start, end = end, start
|
||||||
|
end = min(end, today)
|
||||||
|
if start > end:
|
||||||
|
raise HTTPException(status_code=400, detail="앞으로의 기간은 가져올 수 없습니다.")
|
||||||
|
days = (end - start).days + 1
|
||||||
|
if days > MAX_BACKFILL_DAYS:
|
||||||
|
raise HTTPException(status_code=400, detail=f"한 번에 {MAX_BACKFILL_DAYS}일까지 가져올 수 있습니다.")
|
||||||
|
if days > MAX_USER_SYNC_DAYS and not is_admin(user):
|
||||||
|
raise HTTPException(status_code=403, detail=f"{MAX_USER_SYNC_DAYS}일보다 긴 기간은 관리자만 가져올 수 있습니다.")
|
||||||
|
_, ad_sync = _ad_services(store)
|
||||||
|
if not ad_sync.configured().get(code):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{src.name} API 가 설정되지 않았습니다. 관리자가 실적 설정 → 광고 API 연동에서 입력해야 합니다.")
|
||||||
|
try:
|
||||||
|
res = ad_sync.sync(code, start, end, user=user["email"])
|
||||||
|
except AdSyncBusy as exc:
|
||||||
|
raise HTTPException(status_code=409, detail=str(exc)) from None
|
||||||
|
except AdMigrationNeeded as exc:
|
||||||
|
raise HTTPException(status_code=503, detail=_ad_migration_help(exc)) from None
|
||||||
|
if not res.get("ok"):
|
||||||
|
return JSONResponse(status_code=502, content={"detail": f"{src.name} 가져오기 실패 — {res.get('message')}", **res})
|
||||||
|
return JSONResponse(res)
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
# JSON API — 설정(수수료율은 모듈 권한자 누구나, 나머지는 관리자)
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -277,11 +671,21 @@ def api_events(request: Request, code: str, from_: str = Query(..., alias="from"
|
|||||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
store, _ = common.require_store(request, admin=True)
|
store, _ = common.require_store(request, admin=True)
|
||||||
_code_or_404(store, code)
|
_code_or_404(store, code)
|
||||||
row = store.update_marketplace(
|
from .db import ManualMigrationNeeded # noqa: WPS433
|
||||||
code,
|
|
||||||
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
adapter = get_adapter(code)
|
||||||
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
if adapter is not None and adapter.manual_only and payload.get("manual_input") is False:
|
||||||
)
|
raise HTTPException(status_code=400, detail="수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
row = store.update_marketplace(
|
||||||
|
code,
|
||||||
|
enabled=bool(payload["enabled"]) if "enabled" in payload else None,
|
||||||
|
include_in_sales=bool(payload["include_in_sales"]) if "include_in_sales" in payload else None,
|
||||||
|
manual_input=bool(payload["manual_input"]) if "manual_input" in payload else None,
|
||||||
|
)
|
||||||
|
except ManualMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail=MANUAL_MIGRATION_HELP) from None
|
||||||
return JSONResponse({"marketplace": row})
|
return JSONResponse({"marketplace": row})
|
||||||
|
|
||||||
|
|
||||||
@@ -366,15 +770,23 @@ def api_save_credentials(request: Request, code: str, payload: dict[str, Any] =
|
|||||||
|
|
||||||
@router.post("/api/marketplaces/{code}/test")
|
@router.post("/api/marketplaces/{code}/test")
|
||||||
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
def api_test_connection(request: Request, code: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용)."""
|
"""values 가 있으면 저장하지 않은 새 입력값으로 시험(빈 칸은 저장된 값 사용), clear = 화면에서 비운 항목은 빈 값으로.
|
||||||
|
광고 API 시험(/api/ad-sources/{code}/test)과 같은 요청·응답 계약 — 공통 설정 창이 둘 다 쓴다(검토 F09)."""
|
||||||
store, user = common.require_store(request, admin=True)
|
store, user = common.require_store(request, admin=True)
|
||||||
adapter = _code_or_404(store, code)
|
adapter = _code_or_404(store, code)
|
||||||
_, sync = common.services(request, store)
|
_, sync = common.services(request, store)
|
||||||
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
|
values = {k: v for k, v in _clean_values(adapter, payload).items() if v.strip()}
|
||||||
result = sync.test_connection(code, values=values or None, user=user["email"])
|
cleared = _cleared_keys(adapter, payload, values)
|
||||||
|
result = sync.test_connection(code, values=values or None, user=user["email"], cleared=cleared or None)
|
||||||
return JSONResponse(result)
|
return JSONResponse(result)
|
||||||
|
|
||||||
|
|
||||||
|
def _cleared_keys(source: Any, payload: dict[str, Any], values: dict[str, str]) -> set[str]:
|
||||||
|
"""요청의 clear 중 이 연동의 화면 항목이면서 새 값이 없는 것 — 연결 시험에서 빈 값으로 본다."""
|
||||||
|
allowed = {f.key for f in source.visible_fields()}
|
||||||
|
return {str(k) for k in (payload.get("clear") or []) if str(k) in allowed and str(k) not in values}
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/marketplaces/{code}/reconcile")
|
@router.get("/api/marketplaces/{code}/reconcile")
|
||||||
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
|
def api_reconcile(request: Request, code: str, date_: str = Query(..., alias="date"), to: str | None = None) -> JSONResponse:
|
||||||
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
|
"""쇼핑몰 화면(예: 카페24 일별 매출내역)과 비교용 — 그날 원천 금액 항목별 합계. DB 는 바꾸지 않는다."""
|
||||||
@@ -428,4 +840,10 @@ def api_rekey(request: Request) -> JSONResponse:
|
|||||||
if not common.key_status()["ok"]:
|
if not common.key_status()["ok"]:
|
||||||
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
raise HTTPException(status_code=503, detail=common.key_status()["message"])
|
||||||
creds, _ = common.services(request, store)
|
creds, _ = common.services(request, store)
|
||||||
return JSONResponse({**creds.reencrypt_all(), "versions_in_use": creds.key_versions_in_use()})
|
ad_creds, _ = _ad_services(store)
|
||||||
|
shop, ad = creds.reencrypt_all(), ad_creds.reencrypt_all() # 광고 API 인증정보도 같은 마스터 키
|
||||||
|
versions = creds.key_versions_in_use()
|
||||||
|
for v, n in ad_creds.key_versions_in_use().items():
|
||||||
|
versions[v] = versions.get(v, 0) + n
|
||||||
|
return JSONResponse({"reencrypted": shop["reencrypted"] + ad["reencrypted"], "failed": shop["failed"] + ad["failed"],
|
||||||
|
"versions_in_use": versions})
|
||||||
|
|||||||
@@ -58,8 +58,8 @@ class SyncService:
|
|||||||
self._app_state = app_state
|
self._app_state = app_state
|
||||||
|
|
||||||
def _ctx(self, adapter: MarketplaceAdapter, *, overrides: dict[str, str] | None = None,
|
def _ctx(self, adapter: MarketplaceAdapter, *, overrides: dict[str, str] | None = None,
|
||||||
persist: bool = True, user: str = "") -> AdapterContext:
|
persist: bool = True, user: str = "", cleared: set[str] | None = None) -> AdapterContext:
|
||||||
acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user)
|
acc = self._creds.accessor(adapter.code, overrides=overrides, persist=persist, user=user, cleared=cleared)
|
||||||
return AdapterContext(code=adapter.code, credentials=acc, app_state=self._app_state)
|
return AdapterContext(code=adapter.code, credentials=acc, app_state=self._app_state)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -72,15 +72,17 @@ class SyncService:
|
|||||||
return "api_error", redact_text(f"예상하지 못한 오류: {type(exc).__name__}: {exc}", known)
|
return "api_error", redact_text(f"예상하지 못한 오류: {type(exc).__name__}: {exc}", known)
|
||||||
|
|
||||||
# ── 연결 테스트 ─────────────────────────────────────────
|
# ── 연결 테스트 ─────────────────────────────────────────
|
||||||
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "") -> dict[str, Any]:
|
def test_connection(self, code: str, *, values: dict[str, str] | None = None, user: str = "",
|
||||||
"""values 를 주면 저장하지 않은 새 입력값으로 시험(저장된 상태는 바꾸지 않음)."""
|
cleared: set[str] | None = None) -> dict[str, Any]:
|
||||||
|
"""values 를 주면 저장하지 않은 새 입력값으로, cleared = 화면에서 비운 항목은 저장값 대신 빈 값으로 시험한다.
|
||||||
|
둘 중 하나라도 있으면 저장하지 않은 시험이라 연결 상태·토큰을 저장하지 않는다(광고 API 시험과 같은 계약, 검토 F09)."""
|
||||||
adapter = get_adapter(code)
|
adapter = get_adapter(code)
|
||||||
if adapter is None:
|
if adapter is None:
|
||||||
return {"ok": False, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
return {"ok": False, "status": "api_error", "message": "알 수 없는 쇼핑몰입니다."}
|
||||||
unsaved = bool(values)
|
unsaved = bool(values) or bool(cleared)
|
||||||
ctx = None
|
ctx = None
|
||||||
try:
|
try:
|
||||||
ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user)
|
ctx = self._ctx(adapter, overrides=values, persist=not unsaved, user=user, cleared=cleared)
|
||||||
message = adapter.test_connection(ctx)
|
message = adapter.test_connection(ctx)
|
||||||
status, ok = "ok", True
|
status, ok = "ok", True
|
||||||
except Exception as exc: # noqa: BLE001 — 어떤 오류든 상태로 바꿔 화면에 보여 준다
|
except Exception as exc: # noqa: BLE001 — 어떤 오류든 상태로 바꿔 화면에 보여 준다
|
||||||
@@ -119,7 +121,8 @@ class SyncService:
|
|||||||
ctx.progress = progress
|
ctx.progress = progress
|
||||||
fetched, events = adapter.collect(ctx, start, end)
|
fetched, events = adapter.collect(ctx, start, end)
|
||||||
if progress is not None:
|
if progress is not None:
|
||||||
progress.saving()
|
# 중지 확인과 저장 시작을 한 잠금에서 — collect() 끝 무렵에 받아들인 [중지]면 여기서 Cancelled(저장 안 함)
|
||||||
|
progress.begin_saving()
|
||||||
known = ctx.credentials.known_secrets()
|
known = ctx.credentials.known_secrets()
|
||||||
rows = [event_row(ev, known) for ev in events]
|
rows = [event_row(ev, known) for ev in events]
|
||||||
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
|
# 다른 쇼핑몰 열로 보낸 사건 — 등록된 쇼핑몰이 아니면 이 쇼핑몰 열에 둔다(합계가 빠지지 않게).
|
||||||
@@ -162,7 +165,9 @@ class SyncService:
|
|||||||
end = end or today_kst()
|
end = end or today_kst()
|
||||||
start = start or (end - timedelta(days=sync_days() - 1))
|
start = start or (end - timedelta(days=sync_days() - 1))
|
||||||
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
|
enabled = {m["code"] for m in self._store.list_marketplaces() if m["enabled"]}
|
||||||
targets = [a for a in all_adapters() if a.code in enabled and (not codes or a.code in codes)]
|
# 수동 입력 전용 쇼핑몰(manual_only)은 가져올 API 가 없어 매출 업데이트에서 뺀다
|
||||||
|
targets = [a for a in all_adapters()
|
||||||
|
if a.code in enabled and not a.manual_only and (not codes or a.code in codes)]
|
||||||
progress: dict[str, Any] = {}
|
progress: dict[str, Any] = {}
|
||||||
if job is not None:
|
if job is not None:
|
||||||
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
# 수집이 구현되고 인증정보가 있는 쇼핑몰만 막대로(active), 나머지는 "건너뜀" 한 줄로 — 바로 끝나는
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
{# 실적 모듈 탭 — 설정 탭은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
{# 실적 모듈 탭 — [매출 실적] [광고비] 큰 탭 둘(아이콘 + 색으로 구분) + 맨 오른쪽 설정 톱니(프로젝트 모듈과 같은 아이콘).
|
||||||
|
설정은 모듈 권한자 모두(일반 사용자 화면은 수수료율만, 나머지는 관리자). #}
|
||||||
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
<nav class="perf-tabs" aria-label="실적 메뉴">
|
<nav class="perf-tabs" aria-label="실적 메뉴">
|
||||||
<a class="perf-tab{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/">실적</a>
|
<div class="perf-tabs-main" role="tablist">
|
||||||
<a class="perf-tab{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings">{{ '설정' if is_admin else '수수료 설정' }}</a>
|
<a class="perf-tab perf-tab-sales{% if active_tab == 'dashboard' %} is-active{% endif %}" href="/performance/"
|
||||||
|
role="tab" aria-selected="{{ 'true' if active_tab == 'dashboard' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">monitoring</span>매출 실적</a>
|
||||||
|
<a class="perf-tab perf-tab-ads{% if active_tab == 'ads' %} is-active{% endif %}" href="/performance/ads"
|
||||||
|
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||||
|
</div>
|
||||||
|
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="/performance/settings"
|
||||||
|
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
|
||||||
|
|
||||||
|
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||||
|
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||||
|
|
||||||
|
{%- macro won(v) -%}
|
||||||
|
{%- if v is none -%}<span class="perf-na"></span>
|
||||||
|
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||||
|
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
||||||
|
{%- endmacro -%}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||||
|
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross">
|
||||||
|
{% include "performance/_tabs.html" %}
|
||||||
|
|
||||||
|
<div class="perf-toolbar">
|
||||||
|
<div class="perf-quick" role="group" aria-label="기간 선택">
|
||||||
|
{% for q in nav.quick %}
|
||||||
|
<a class="perf-seg{% if q.active %} is-active{% endif %}" href="{{ q.url }}">{{ q.label }}</a>
|
||||||
|
{% endfor %}
|
||||||
|
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="perf-nav">
|
||||||
|
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||||
|
<span class="perf-nav-label">{{ period.label }}</span>
|
||||||
|
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||||
|
<input type="hidden" name="period" value="custom" />
|
||||||
|
<input class="erp-input perf-date" type="date" name="from" value="{{ period.start.isoformat() }}" required />
|
||||||
|
<span class="perf-muted">~</span>
|
||||||
|
<input class="erp-input perf-date" type="date" name="to" value="{{ period.end.isoformat() }}" required />
|
||||||
|
<button class="erp-btn erp-btn-outline" type="submit">조회</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if migration_needed %}
|
||||||
|
<div class="perf-notice is-warn">광고비 저장 표가 아직 없습니다. 관리자가 performance_db 마이그레이션 005
|
||||||
|
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<!-- ── KPI ── -->
|
||||||
|
<div class="perf-kpis">
|
||||||
|
{% for k in kpis %}
|
||||||
|
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||||
|
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||||
|
{% if k.key == 'ratio' %}
|
||||||
|
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
||||||
|
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
||||||
|
{% else %}
|
||||||
|
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
||||||
|
<div class="perf-kpi-delta">
|
||||||
|
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||||
|
{% else %}
|
||||||
|
{% set up = k.delta > 0 %}
|
||||||
|
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||||
|
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||||
|
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── 일자 × 채널 ── -->
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">{% if period_kind == 'year' %}월별 × 광고 채널{% else %}일자별 × 광고 채널{% endif %}</h2>
|
||||||
|
<div class="perf-ad-actions">
|
||||||
|
{% for s in ad_sync_sources %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-ad-sync-btn" data-ad-sync="{{ s.code }}"
|
||||||
|
title="{{ s.name }} API 로 지금 보는 기간(오늘까지)의 광고비·ROAS 를 가져옵니다 — 같은 날은 덮어씀">
|
||||||
|
<span class="material-symbols-outlined" aria-hidden="true">sync</span>{{ s.name }} 불러오기</button>
|
||||||
|
{% endfor %}
|
||||||
|
{% if upload_channels %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn perf-ad-upload-btn" id="perf-ad-upload"
|
||||||
|
title="광고 보고서 파일로 일별 광고비를 한 번에 입력">파일 업로드</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="erp-table-wrap perf-table-wrap">
|
||||||
|
<table class="perf-table perf-main">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||||
|
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||||
|
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in table %}
|
||||||
|
<tr class="perf-row-{{ r.kind }}{% if r.weekday == 5 %} is-sat{% endif %}{% if r.weekday == 6 or r.holiday %} is-sun{% endif %}{% if r.today %} is-today{% endif %}{% if r.future %} is-future{% endif %}">
|
||||||
|
<th class="perf-td-label" scope="row"{% if r.holiday %} title="{{ r.holiday }}"{% endif %}>
|
||||||
|
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||||
|
</th>
|
||||||
|
{% for c in codes %}
|
||||||
|
{% set v = r.cells[c].gross %}
|
||||||
|
{% if r.kind == 'day' and not r.future and not migration_needed %}
|
||||||
|
{% set up = (r.date ~ '|' ~ c) in upload_cells %}
|
||||||
|
{% set ap = (r.date ~ '|' ~ c) in api_cells %}
|
||||||
|
<td class="perf-num is-manual-cell{% if v and not up and not ap %} is-manual{% endif %}{% if up %} is-upload{% endif %}{% if ap %} is-api{% endif %}"
|
||||||
|
data-manual-code="{{ c }}" data-date="{{ r.date }}" data-manual-value="{{ v if v else '' }}" tabindex="0"
|
||||||
|
title="{% if ap %}광고 API 값 — 눌러 고치기(다음 불러오기 때 다시 API 값으로){% elif up %}파일 업로드 값 — 눌러 고치기{% else %}눌러 광고비 입력(비우고 저장하면 지움){% endif %}"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||||
|
{% else %}
|
||||||
|
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||||
|
{% endif %}
|
||||||
|
{% endfor %}
|
||||||
|
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% if period_kind != 'year' %}
|
||||||
|
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||||
|
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
|
||||||
|
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
|
||||||
|
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
|
||||||
|
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── 그래프 ── -->
|
||||||
|
<div class="perf-grid2">
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">{% if period_kind == 'year' %}월별{% else %}일별{% endif %} 광고비 추이</h2></div>
|
||||||
|
<div class="perf-chart" id="perf-chart-daily"></div>
|
||||||
|
</div>
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">채널별 비중</h2>
|
||||||
|
<span class="perf-muted">{{ period.label }}</span></div>
|
||||||
|
<div class="perf-chart" id="perf-chart-share"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ── 월 누적 · 연간 누적 ── -->
|
||||||
|
<div class="perf-grid2">
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 채널별 광고비</h2></div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="perf-table">
|
||||||
|
<thead><tr><th class="perf-th-label">채널</th><th>광고비</th><th>ROAS</th><th>비중</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in month.rows %}
|
||||||
|
<tr>
|
||||||
|
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
||||||
|
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||||
|
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
<td class="perf-num perf-share">
|
||||||
|
{% if r.share is not none %}<span class="perf-bar" style="--w: {{ [r.share, 0] | max }}%"></span>{{ "%.1f" | format(r.share) }}%{% else %}<span class="perf-zero">–</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr class="perf-row-total">
|
||||||
|
<th class="perf-td-label" scope="row">합계</th>
|
||||||
|
<td class="perf-num">{{ won(month.total.gross) }}</td>
|
||||||
|
<td class="perf-num">{% if month.total.roas is not none %}{{ "{:,}".format(month.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
<td class="perf-num">{% if month.total.share is not none %}100%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="erp-card perf-card">
|
||||||
|
<div class="perf-card-head"><h2 class="perf-h">{{ year.year }}년 누적 광고비</h2></div>
|
||||||
|
<div class="perf-year-sum">
|
||||||
|
<div><span>광고비</span><b>₩{{ "{:,}".format(year.total.gross) }}</b></div>
|
||||||
|
</div>
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="perf-table perf-year">
|
||||||
|
<thead><tr><th class="perf-th-label">월</th><th>광고비</th><th>ROAS</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in year.rows %}
|
||||||
|
<tr class="{% if r.future %}is-future{% endif %}">
|
||||||
|
<th class="perf-td-label" scope="row">{{ r.label }}</th>
|
||||||
|
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||||
|
<td class="perf-num">{% if r.roas is not none %}{{ "{:,}".format(r.roas) }}%{% elif not r.future %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr class="perf-row-total">
|
||||||
|
<th class="perf-td-label" scope="row">합계</th>
|
||||||
|
<td class="perf-num">{{ won(year.total.gross) }}</td>
|
||||||
|
<td class="perf-num">{% if year.total.roas is not none %}{{ "{:,}".format(year.total.roas) }}%{% else %}<span class="perf-zero">–</span>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="perf-foot perf-muted">
|
||||||
|
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
|
||||||
|
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
|
||||||
|
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||||
|
메타는 지금은 직접 입력합니다.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script type="application/json" id="perf-data">{{ {
|
||||||
|
"names": names,
|
||||||
|
"codes": codes,
|
||||||
|
"daily": chart_daily,
|
||||||
|
"share": chart_share,
|
||||||
|
"period_kind": period_kind,
|
||||||
|
"today": today,
|
||||||
|
"manual_api": "/performance/api/ad-spend/",
|
||||||
|
"manual_word": "광고비",
|
||||||
|
"period_start": period.start.isoformat(),
|
||||||
|
"period_end": period.end.isoformat(),
|
||||||
|
"period_label": period.label,
|
||||||
|
"empty_text": "기간 내 광고비가 없습니다.",
|
||||||
|
"upload_channels": upload_channels
|
||||||
|
} | tojson }}</script>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
{% extends "erp_base.html" %}
|
{% extends "erp_base.html" %}
|
||||||
|
|
||||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261001b" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% 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>
|
||||||
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
{%- elif v == 0 -%}<span class="perf-zero">–</span>
|
||||||
{%- else -%}{{ "{:,}".format(v) }}{%- endif -%}
|
{%- else -%}{{ amt(v) }}{%- endif -%}
|
||||||
|
{%- endmacro -%}
|
||||||
|
{#- 큰 금액(KPI·연 누적) — 원 단위면 ₩1,234, 천원·백만원이면 1,234천원 -#}
|
||||||
|
{%- macro money(v) -%}
|
||||||
|
{%- if unit == 'won' -%}₩{{ amt(v) }}{%- else -%}{{ amt(v) }}<small class="perf-unit-suffix">{{ unit_label }}</small>{%- endif -%}
|
||||||
|
{%- endmacro -%}
|
||||||
|
{#- 매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값·색. 카페24 = 구글·메타 두 줄(이름 붙임) -#}
|
||||||
|
{%- macro adl(lines) -%}
|
||||||
|
{%- for a in lines or [] -%}<span class="perf-adl" title="{{ (a.label ~ ' ') if a.label }}광고비 {{ '{:,}'.format(a.amount) }}원{% if a.roas is not none %} · ROAS {{ '{:,}'.format(a.roas) }}%{% endif %}">{% if a.label %}<i>{{ a.label }}</i>{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}<em>({{ "{:,}".format(a.roas) }}%)</em>{% endif %}</span>{%- endfor -%}
|
||||||
{%- endmacro -%}
|
{%- endmacro -%}
|
||||||
|
|
||||||
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
|
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
|
||||||
@@ -89,7 +97,7 @@
|
|||||||
{% for k in kpis %}
|
{% for k in kpis %}
|
||||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
<div class="perf-kpi-value">{{ money(k.value) }}</div>
|
||||||
<div class="perf-kpi-delta">
|
<div class="perf-kpi-delta">
|
||||||
{% 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 %}
|
||||||
@@ -107,6 +115,12 @@
|
|||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<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-adl-note" title="매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 카페24 는 구글·메타"><span class="perf-adl-key"></span>광고비(ROAS%)</span></span>
|
||||||
|
{% if manual_upload_names %}
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm perf-manual-upload-btn" id="perf-manual-upload"
|
||||||
|
title="수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력">엑셀 업로드</button>
|
||||||
|
{% endif %}
|
||||||
<div class="perf-metric" role="group" aria-label="표시 기준">
|
<div class="perf-metric" role="group" aria-label="표시 기준">
|
||||||
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
|
<button type="button" class="perf-seg" data-metric="gross">총매출</button>
|
||||||
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
<button type="button" class="perf-seg" data-metric="commission">수수료</button>
|
||||||
@@ -118,7 +132,7 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||||
{% for c in codes %}<th title="{{ names[c] }}">{{ short_names[c] }}</th>{% endfor %}
|
{% for c in codes %}<th title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}</th>{% endfor %}
|
||||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -130,15 +144,26 @@
|
|||||||
</th>
|
</th>
|
||||||
{% for c in codes %}
|
{% for c in codes %}
|
||||||
{% set m = r.cells[c] %}
|
{% set m = r.cells[c] %}
|
||||||
|
{% if r.kind == 'day' and c in manual_codes and not r.future %}
|
||||||
|
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
||||||
|
<td class="perf-num is-manual-cell{% if is_manual %} is-manual{% endif %}" data-manual-code="{{ c }}" data-date="{{ r.date }}"
|
||||||
|
data-manual-value="{{ m.gross if is_manual else '' }}" tabindex="0"
|
||||||
|
title="{% if is_manual %}수동 입력값 — 눌러 고치기(비우고 저장하면 API 값){% else %}눌러 총매출 직접 입력{% endif %}">{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
|
||||||
|
{% else %}
|
||||||
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
|
<td class="perf-num{% if r['from'] and (m.gross or m.commission) %} is-link{% endif %}"
|
||||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}</td>
|
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
|
||||||
|
{% endif %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}</td>
|
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
{% if manual_codes and period_kind != 'year' %}
|
||||||
|
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
|
||||||
|
비우고 저장하면 다시 API 수집값. 파란 숫자 = 수동 입력값. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ── 그래프 ── -->
|
<!-- ── 그래프 ── -->
|
||||||
@@ -158,7 +183,7 @@
|
|||||||
<!-- ── 월 누적 · 연간 누적 ── -->
|
<!-- ── 월 누적 · 연간 누적 ── -->
|
||||||
<div class="perf-grid2">
|
<div class="perf-grid2">
|
||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2></div>
|
<div class="perf-card-head"><h2 class="perf-h">{{ month.label }} 쇼핑몰별 누적 실적</h2>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</div>
|
||||||
<div class="erp-table-wrap">
|
<div class="erp-table-wrap">
|
||||||
<table class="perf-table">
|
<table class="perf-table">
|
||||||
<thead><tr><th class="perf-th-label">쇼핑몰</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th><th>매출 비중</th></tr></thead>
|
<thead><tr><th class="perf-th-label">쇼핑몰</th><th>총매출</th><th>수수료</th><th>수수료 차감 매출</th><th>매출 비중</th></tr></thead>
|
||||||
@@ -189,11 +214,11 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<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>{% if unit != 'won' %}<span class="perf-muted perf-unit-note">단위: {{ unit_label }}</span>{% endif %}</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(year.total.gross) }}</b></div>
|
||||||
<div><span>수수료</span><b>₩{{ "{:,}".format(year.total.commission) }}</b></div>
|
<div><span>수수료</span><b>{{ money(year.total.commission) }}</b></div>
|
||||||
<div><span>수수료 차감 매출</span><b>₩{{ "{:,}".format(year.total.net) }}</b></div>
|
<div><span>수수료 차감 매출</span><b>{{ money(year.total.net) }}</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">
|
||||||
@@ -235,8 +260,10 @@
|
|||||||
"period_kind": period_kind,
|
"period_kind": period_kind,
|
||||||
"period_start": period.start.isoformat(),
|
"period_start": period.start.isoformat(),
|
||||||
"period_end": period.end.isoformat(),
|
"period_end": period.end.isoformat(),
|
||||||
"today": today
|
"today": today,
|
||||||
|
"unit": unit,
|
||||||
|
"manual_upload_names": manual_upload_names
|
||||||
} | tojson }}</script>
|
} | tojson }}</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261019a" 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=20261001b" />{% endblock %}
|
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019a" />{% endblock %}
|
||||||
|
|
||||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||||
|
|
||||||
@@ -20,7 +20,8 @@
|
|||||||
<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 인증정보는 [설정]에서 입력합니다.</span>
|
<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||||
|
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있습니다.</span>
|
||||||
{% else %}
|
{% else %}
|
||||||
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -31,7 +32,8 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<th class="perf-th-label">쇼핑몰</th>
|
<th class="perf-th-label">쇼핑몰</th>
|
||||||
{% if is_admin %}<th>사용</th>
|
{% if is_admin %}<th>사용</th>
|
||||||
<th>매출 집계</th>{% endif %}
|
<th>매출 집계</th>
|
||||||
|
<th>수동 입력</th>{% endif %}
|
||||||
<th>수수료율</th>
|
<th>수수료율</th>
|
||||||
{% if is_admin %}<th>API 설정</th>
|
{% if is_admin %}<th>API 설정</th>
|
||||||
<th>연결 상태</th>{% endif %}
|
<th>연결 상태</th>{% endif %}
|
||||||
@@ -54,6 +56,11 @@
|
|||||||
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
<input type="checkbox" data-field="include_in_sales"{% if r.include_in_sales %} checked{% endif %} /><span></span>
|
||||||
</label>
|
</label>
|
||||||
</td>
|
</td>
|
||||||
|
<td class="perf-center">
|
||||||
|
<label class="perf-switch" title="{% if r.manual_only %}수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다{% else %}수동 입력 사용 — 켜면 실적 일자별 표에서 날짜 칸에 매출을 직접 입력(입력한 날은 API 값 대신){% endif %}">
|
||||||
|
<input type="checkbox" data-field="manual_input"{% if r.manual_input or r.manual_only %} checked{% endif %}{% if r.manual_only %} disabled{% endif %} /><span></span>
|
||||||
|
</label>
|
||||||
|
</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<td class="perf-rate-cell">
|
<td class="perf-rate-cell">
|
||||||
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
<span class="perf-rate">{% if r.rate %}{{ r.rate }}%{% else %}<span class="perf-muted">미설정</span>{% endif %}</span>
|
||||||
@@ -62,7 +69,8 @@
|
|||||||
</td>
|
</td>
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
<td>
|
<td>
|
||||||
{% if r.shared %}<span class="perf-pill">공통 연동</span>
|
{% if r.manual_only %}<span class="perf-pill">수동 입력 전용</span>
|
||||||
|
{% elif r.shared %}<span class="perf-pill">공통 연동</span>
|
||||||
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
{% elif r.configured %}<span class="perf-pill is-ok">설정완료</span>
|
||||||
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
{% else %}<span class="perf-pill">미설정</span>{% endif %}
|
||||||
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
{% if r.via_cafe24 %}<span class="perf-pill is-ok" title="카페24 마켓 통합관리로 들어온 이 쇼핑몰 주문을 카페24 수집 때 함께 반영합니다">카페24 경유</span>{% endif %}
|
||||||
@@ -77,8 +85,10 @@
|
|||||||
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(r.last_sync_at) }}">{{ when(r.last_success_sync_at) }}</td>
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
<td class="perf-nowrap">
|
<td class="perf-nowrap">
|
||||||
|
{% if not r.manual_only %}
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||||
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
@@ -92,7 +102,71 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
|
||||||
|
<div class="erp-card perf-card" id="perf-view-opts">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">보기 설정</h2>
|
||||||
|
<span class="perf-muted">매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
|
||||||
|
</div>
|
||||||
|
<div class="perf-opt-row">
|
||||||
|
<span class="perf-opt-label">매출 단위</span>
|
||||||
|
<div class="perf-quick" role="radiogroup" aria-label="매출 단위">
|
||||||
|
{% for k, label in [('won', '원'), ('thousand', '천원'), ('million', '백만원')] %}
|
||||||
|
<button type="button" class="perf-seg{% if unit == k %} is-active{% endif %}" role="radio"
|
||||||
|
aria-checked="{{ 'true' if unit == k else 'false' }}" data-unit="{{ k }}">{{ label }}</button>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
|
||||||
|
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
|
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고·메타 광고(2026-10-16). 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
||||||
|
가져온 광고비·ROAS 는 광고비 탭(초록 숫자). [설정]·[연결 테스트]는 쇼핑몰 표와 같은 창(/api/ad-sources/…). #}
|
||||||
|
<div class="erp-card perf-card" id="perf-ad-sources">
|
||||||
|
<div class="perf-card-head">
|
||||||
|
<h2 class="perf-h">광고 API 연동</h2>
|
||||||
|
<span class="perf-muted">광고비 탭의 광고비·ROAS 를 광고 API 로 가져옵니다. 인증정보는 [설정]에서 입력하면 암호화해 저장합니다.
|
||||||
|
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
|
||||||
|
</div>
|
||||||
|
{% if not ad_api_ready %}
|
||||||
|
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
|
||||||
|
(scripts/sql/performance_db_007_ad_api.sql)을 적용해야 저장할 수 있습니다.</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="erp-table-wrap">
|
||||||
|
<table class="perf-table perf-set-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th class="perf-th-label">광고</th><th>API 설정</th><th>연결 상태</th><th>마지막 가져오기</th><th></th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for a in ad_sources %}
|
||||||
|
<tr data-code="{{ a.code }}" data-name="{{ a.name }}" data-api="ad-sources">
|
||||||
|
<th class="perf-td-label" scope="row">{{ a.name }}</th>
|
||||||
|
<td>{% if a.configured %}<span class="perf-pill is-ok">설정완료</span>{% else %}<span class="perf-pill">미설정</span>{% endif %}</td>
|
||||||
|
<td>
|
||||||
|
<span class="perf-status st-{{ a.status }}"
|
||||||
|
title="마지막 연결 테스트: {{ when(a.last_test_at) }}{% if a.last_error %} 최근 오류({{ when(a.last_error_at) }}): {{ a.last_error }}{% endif %}">
|
||||||
|
<i></i>{{ a.status_label }}</span>
|
||||||
|
{% if a.last_error and a.status not in ('ok',) %}<div class="perf-err">{{ a.last_error }}</div>{% endif %}
|
||||||
|
</td>
|
||||||
|
<td class="perf-muted perf-nowrap" title="마지막 시도: {{ when(a.last_sync_at) }}">{{ when(a.last_success_sync_at) }}</td>
|
||||||
|
<td class="perf-nowrap">
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="creds">설정</button>
|
||||||
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-act="test">연결 테스트</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="perf-foot perf-muted">
|
||||||
|
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.<br>
|
||||||
|
메타 광고: 광고비 = 광고 관리자의 "지출 금액" 그대로(메타 금액은 이미 부가세 포함), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 "구매 ROAS"). 광고 계정이 여러 개면 날짜별로 합칩니다. 날짜는 광고 계정 시간대 기준이며, 달러 등 외화 계정은 그날 환율로 원화로 바꿔 넣습니다(중앙은행 고시 환율 종합, 그날 값이 없으면 직전 값).
|
||||||
|
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="perf-grid2">
|
<div class="perf-grid2">
|
||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
<div class="perf-card-head"><h2 class="perf-h">인증정보 암호화</h2></div>
|
||||||
@@ -110,7 +184,7 @@
|
|||||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
|
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="perf-rekey">현재 키로 다시 암호화</button></p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<p class="perf-foot perf-muted">
|
<p class="perf-foot perf-muted">
|
||||||
API 인증정보는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
|
API 인증정보(쇼핑몰·광고)는 서버에서 AES-256-GCM 으로 암호화해 DB 에 저장합니다. 마스터 키(APP_ENCRYPTION_KEY)는 DB 가 아닌
|
||||||
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
|
서버 환경변수에만 있으며, 키를 잃으면 저장된 인증정보를 복구할 수 없으니 별도로 안전하게 보관하세요.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -128,53 +202,6 @@
|
|||||||
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
<div class="perf-notice" id="perf-backfill-result" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="erp-card perf-card perf-card-wide">
|
|
||||||
<div class="perf-card-head"><h2 class="perf-h">쇼핑몰 원본 데이터 확인</h2></div>
|
|
||||||
<p class="perf-muted">쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음).
|
|
||||||
쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다.
|
|
||||||
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
|
|
||||||
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
|
|
||||||
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).<br>
|
|
||||||
· <b>GS샵</b>: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.<br>
|
|
||||||
· <b>토스쇼핑</b>: 날짜별 매출·환불·순 거래액(= 저장되는 매출)과 주문 상태별·정산 항목 합계 — 토스쇼핑 파트너스의 같은 날 숫자와 비교해 주세요.</p>
|
|
||||||
<div class="perf-sample-form">
|
|
||||||
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
|
|
||||||
<option value="naver">네이버 스마트스토어</option>
|
|
||||||
<option value="elevenst">11번가</option>
|
|
||||||
<option value="gsshop">GS샵</option>
|
|
||||||
<option value="toss">토스쇼핑</option>
|
|
||||||
</select>
|
|
||||||
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
|
|
||||||
<span class="perf-muted">~</span>
|
|
||||||
<input class="erp-input perf-date" type="date" id="perf-probe-to" value="{{ default_sample_to }}" />
|
|
||||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe">불러오기</button>
|
|
||||||
</div>
|
|
||||||
<div id="perf-probe-result"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="erp-card perf-card perf-card-wide">
|
|
||||||
<div class="perf-card-head"><h2 class="perf-h">카페24 매출 대조</h2></div>
|
|
||||||
<p class="perf-muted">카페24 관리자 → 통계 → 일별 매출내역과 같은 날짜를 비교합니다. 그날 결제 주문과 환불을 카페24 API 에서
|
|
||||||
바로 합산하며(저장하지 않음), 자체몰과 다른 마켓 연동 주문을 나눠 보여 줍니다.</p>
|
|
||||||
<div class="perf-sample-form">
|
|
||||||
<input class="erp-input perf-date" type="date" id="perf-recon-date" value="{{ default_sample_to }}" />
|
|
||||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-recon">대조</button>
|
|
||||||
</div>
|
|
||||||
<div id="perf-recon-result"></div>
|
|
||||||
|
|
||||||
<h3 class="perf-h" style="margin:18px 0 6px">일별 한 번에 비교</h3>
|
|
||||||
<p class="perf-muted">카페24 일별 매출내역 표를 그대로 복사해 붙여 넣으면 날짜마다 결제합계·환불합계를 저장된 값과 비교합니다.
|
|
||||||
[API 값도 계산]을 켜면 지금 규칙으로 카페24에서 다시 계산한 값(저장 안 함)도 함께 보여 줘, 저장값만 틀린 날(다시 가져오면 해결)과
|
|
||||||
규칙이 틀린 날을 나눠 볼 수 있습니다. 날짜를 누르면 위 대조를 그날로 엽니다.</p>
|
|
||||||
<textarea class="erp-input perf-paste" id="perf-daily-paste" rows="5"
|
|
||||||
placeholder="2026-09-29(화) 47 116 2,475,300 … 2,477,800 158,000 2,319,800"></textarea>
|
|
||||||
<div class="perf-sample-form" style="margin-top:6px">
|
|
||||||
<label class="perf-muted"><input type="checkbox" id="perf-daily-live" /> API 값도 계산(느림)</label>
|
|
||||||
<button type="button" class="erp-btn erp-btn-outline" id="perf-daily-check">비교</button>
|
|
||||||
</div>
|
|
||||||
<div id="perf-daily-result"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="erp-card perf-card">
|
<div class="erp-card perf-card">
|
||||||
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
|
<div class="perf-card-head"><h2 class="perf-h">테스트 데이터</h2>
|
||||||
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
|
<span class="perf-muted">현재 {{ "{:,}".format(sample_count) }}건</span></div>
|
||||||
@@ -192,4 +219,4 @@
|
|||||||
</section>
|
</section>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block scripts %}<script src="/static/performance.js?v=20261001g" defer></script>{% endblock %}
|
{% block scripts %}<script src="/static/performance.js?v=20261019a" defer></script>{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,393 @@
|
|||||||
|
"""광고비 — 쿠팡(로켓) 광고 보고서 읽기(CSV·엑셀) · 화면 데이터 조립."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import ad_spend as ads
|
||||||
|
from app.modules.performance.manual_upload import UploadError
|
||||||
|
|
||||||
|
TODAY = date(2026, 10, 13)
|
||||||
|
|
||||||
|
# 사용자 제공 양식(2026-10-13) 그대로 — 머리글, "전체" 합계 줄, 날짜 줄 + 그 아래 캠페인 줄
|
||||||
|
ROCKET_CSV = """날짜,배송유형,부가세 유형,생성자,담당자,광고 유형,광고 목표,캠페인 ID,캠페인명,청구가능 금액 유형,예산 유형,광고 예산,소진 광고비,소진 광고비 중 조정 금액,조정 후 소진 광고비,초과 소진 금액,청구 가능 광고비,부가가치세,청구금액(+부가가치세)
|
||||||
|
전체,RETAIL,,,,,,,,,,,2400506,0,2400506,2396813,2396813,239681,2636494
|
||||||
|
2026년 10월 01일,RETAIL,Taxable,,,,,,,,,,200404,0,200404,200000,200000,20000,220000
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200404,0,200404,200000,200000,,
|
||||||
|
2026년 10월 06일,RETAIL,Taxable,,,,,,,,,,196997,0,196997,196997,196997,19700,216697
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,196997,0,196997,196997,196997,,
|
||||||
|
2026년 10월 12일,RETAIL,Taxable,,,,,,,,,,200210,0,200210,200210,200210,20021,220231
|
||||||
|
,,,,VENDOR,PA,매출 성장,103529103,[쿠팡로켓] 스마트AI,Adcost,DAILY_SOFT,200000,200210,0,200210,200210,200210,,
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _xlsx(text: str) -> bytes:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
for line in text.strip().splitlines():
|
||||||
|
ws.append([int(v) if v.isdigit() else (v or None) for v in line.split(",")])
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("content,name", [
|
||||||
|
(ROCKET_CSV.encode("utf-8-sig"), "report.csv"),
|
||||||
|
(ROCKET_CSV.encode("cp949"), "report.csv"),
|
||||||
|
(_xlsx(ROCKET_CSV), "report.xlsx"),
|
||||||
|
])
|
||||||
|
def test_rocket_report_reads_date_and_col19(content, name):
|
||||||
|
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
|
||||||
|
assert not res.errors
|
||||||
|
assert res.entries == [(date(2026, 10, 1), 220000), (date(2026, 10, 6), 216697), (date(2026, 10, 12), 220231)]
|
||||||
|
assert res.skipped == 5 # 머리글 + 전체 + 캠페인 줄 3개
|
||||||
|
|
||||||
|
|
||||||
|
def test_rocket_report_errors_block_everything():
|
||||||
|
bad = ROCKET_CSV + "2026년 13월 40일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,1\n" # 날짜 오류
|
||||||
|
bad += "2026년 10월 08일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n" # 금액이 숫자 아님
|
||||||
|
bad += "2026년 10월 20일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,5\n" # 앞으로의 날짜
|
||||||
|
res = ads.parse_coupang_rocket(bad.encode("utf-8"), today=TODAY)
|
||||||
|
joined = " / ".join(res.errors)
|
||||||
|
assert len(res.errors) == 3, res.errors
|
||||||
|
assert "날짜를 읽을 수 없습니다" in joined and "숫자가 아닙니다" in joined and "앞으로의 날짜" in joined
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_report_date_rows_col19_summed_empty_skipped():
|
||||||
|
"""쿠팡(윙) 보고서처럼 캠페인 줄에도 1열 날짜가 있고 19열이 비어 있어도 — 날짜가 있는 줄의 19열 값만, 같은 날은 더한다
|
||||||
|
(2026-10-14 사용자 확인: "쿠팡은 모두 1열에서 날짜가 있는 행의 19열 값"). 값이 한 줄도 없는 날은 empty_days."""
|
||||||
|
head = ROCKET_CSV.splitlines()[0]
|
||||||
|
wing = "\n".join([
|
||||||
|
head,
|
||||||
|
"2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 날짜 있고 19열 빈 줄
|
||||||
|
"2026-03-01,,,,VENDOR,PA,매출 성장,2,캠페인B,Adcost,DAILY_SOFT,1000,20,0,20,0,20,,",
|
||||||
|
"2026-03-01,RETAIL,Taxable,,,,,,,,,,30,0,30,30,30,3,33", # 값 있는 줄
|
||||||
|
"2026-03-01,RETAIL,Tax-free,,,,,,,,,,5,0,5,5,5,0,5", # 같은 날 값 한 줄 더 → 더함
|
||||||
|
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,10,0,10,0,10,,", # 값 없는 날
|
||||||
|
"2026-03-03,RETAIL,Taxable,,,,,,,,,,1,0,1,1,1,0,1,100", # 19열 = 1 (20열은 무시)
|
||||||
|
]) + "\n"
|
||||||
|
for content, name in ((wing.encode("utf-8"), "w.csv"), (_xlsx(wing), "w.xlsx")):
|
||||||
|
res = ads.parse_coupang_rocket(content, today=TODAY, filename=name)
|
||||||
|
assert not res.errors, res.errors
|
||||||
|
assert res.entries == [(date(2026, 3, 1), 38), (date(2026, 3, 3), 1)]
|
||||||
|
assert res.empty_days == [date(2026, 3, 2)]
|
||||||
|
# 청구금액이 한 줄도 없는 파일(날짜 줄만) — 오류 없이 넘어감(반영할 날 없음)
|
||||||
|
none = "\n".join([head, "2026-03-01,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,",
|
||||||
|
"2026-03-02,,,,VENDOR,PA,매출 성장,1,캠페인A,Adcost,DAILY_SOFT,1000,0,0,0,0,0,,"]) + "\n"
|
||||||
|
r0 = ads.parse_coupang_rocket(_xlsx(none), today=TODAY, filename="march.xlsx")
|
||||||
|
assert r0.entries == [] and not r0.errors and r0.empty_days == [date(2026, 3, 1), date(2026, 3, 2)]
|
||||||
|
m, _ = ads.merge_results([("a.xlsx", 1.0, ads.parse_coupang_rocket(wing.encode("utf-8"), today=TODAY)),
|
||||||
|
("b.csv", 2.0, ads.ParseResult(entries=[(date(2026, 3, 2), 7)]))])
|
||||||
|
assert m.empty_days == [] and dict(m.entries)[date(2026, 3, 2)] == 7 # 다른 파일에 값이 있으면 빈 날 아님
|
||||||
|
|
||||||
|
|
||||||
|
def test_rocket_report_wrong_file():
|
||||||
|
with pytest.raises(UploadError):
|
||||||
|
ads.parse_coupang_rocket(b"", today=TODAY)
|
||||||
|
with pytest.raises(UploadError): # 날짜 줄이 하나도 없음
|
||||||
|
ads.parse_coupang_rocket("날짜,금액\n전체,3\n".encode("utf-8"), today=TODAY)
|
||||||
|
other = ads.parse_coupang_rocket("이름,금액\n홍길동,3\n".encode("utf-8"), today=TODAY) # 다른 양식 → 줄 오류
|
||||||
|
assert not other.entries and "날짜를 읽을 수 없습니다" in other.errors[0]
|
||||||
|
with pytest.raises(UploadError):
|
||||||
|
ads.parse_coupang_rocket(b"PK\x03\x04broken", today=TODAY, filename="x.xlsx")
|
||||||
|
|
||||||
|
|
||||||
|
class _Store:
|
||||||
|
def __init__(self, missing=False):
|
||||||
|
self.missing = missing
|
||||||
|
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded()
|
||||||
|
rows = {(date(2026, 10, 1), "coupang_rocket"): (220000, "upload"),
|
||||||
|
(date(2026, 10, 2), "google"): (50000, "manual"),
|
||||||
|
(date(2026, 9, 1), "meta"): (100000, "manual")}
|
||||||
|
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
return {k: v[0] for k, v in rows.items()}, {k: v[1] for k, v in rows.items()}
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
rows = {(date(2026, 10, 5), "cafe24"): 2_700_000, (date(2026, 10, 1), "coupang_rocket"): 550_000,
|
||||||
|
(date(2026, 10, 3), "coupang_rocket"): 110_000}
|
||||||
|
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_dashboard_month():
|
||||||
|
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||||
|
sales_codes=["cafe24"])
|
||||||
|
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||||
|
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||||
|
k = {x["key"]: x for x in ctx["kpis"]}
|
||||||
|
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
|
||||||
|
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
|
||||||
|
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||||
|
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
||||||
|
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
|
||||||
|
assert ctx["api_cells"] == []
|
||||||
|
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-01")
|
||||||
|
assert day1["cells"]["coupang_rocket"]["gross"] == 220000 and day1["total"]["gross"] == 220000
|
||||||
|
assert ctx["table"][-1]["kind"] == "total" and ctx["table"][-1]["total"]["gross"] == 270000
|
||||||
|
# ROAS = 그 쇼핑몰 매출 ÷ 광고비 — 로켓 10/1: 550,000 ÷ 220,000 = 250%, 구글 10/2: 카페24 그날 매출 0 → 0%
|
||||||
|
assert day1["roas"]["coupang_rocket"] == 250 and day1["roas"]["google"] is None
|
||||||
|
day2 = next(r for r in ctx["table"] if r.get("date") == "2026-10-02")
|
||||||
|
assert day2["roas"]["google"] is None # 구글·메타는 ROAS 계산 안 함(따로 입력)
|
||||||
|
total = ctx["table"][-1]
|
||||||
|
assert total["roas"]["coupang_rocket"] == 300 and total["roas"]["google"] is None # 660,000÷220,000
|
||||||
|
assert total["roas_total"] == 1000 # 2,700,000 ÷ 270,000 (합계 = sales_codes)
|
||||||
|
m = {r["code"]: r for r in ctx["month"]["rows"]}
|
||||||
|
assert m["coupang_rocket"]["roas"] == 300 and m["naver"]["roas"] is None and ctx["month"]["total"]["roas"] == 1000
|
||||||
|
assert ctx["year"]["rows"][9]["roas"] == 1000 and ctx["year"]["rows"][10]["roas"] is None # 11월 = 앞으로
|
||||||
|
assert ctx["roas_basis"]["google"] == "" and ctx["roas_basis"]["coupang_wing"] == "쿠팡(윙)"
|
||||||
|
assert {r["code"]: r for r in ctx["month"]["rows"]}["google"]["roas"] is None
|
||||||
|
assert ads.roas(1, 3) == 33 and ads.roas(1, 200) == 1 and ads.roas(5, 0) is None # 0.5% 반올림 → 1
|
||||||
|
assert ctx["nav"]["quick"][2]["active"] # 이번달
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_dashboard_year_and_missing_table():
|
||||||
|
ctx = ads.build_ad_dashboard(_Store(), kind="year", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
rows = {r["label"]: r for r in ctx["table"]}
|
||||||
|
assert rows["9월"]["total"]["gross"] == 100000 and rows["10월"]["total"]["gross"] == 270000
|
||||||
|
assert {x["key"]: x for x in ctx["kpis"]}["ratio"]["pct"] is None # 매출 없음
|
||||||
|
miss = ads.build_ad_dashboard(_Store(missing=True), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
assert miss["migration_needed"] and miss["kpis"][0]["value"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_spend_endpoints(monkeypatch):
|
||||||
|
"""라우터: 업로드 정상 → 한 번에 저장(source=upload), 잘못된 줄 → 400 + 목록·저장 안 함, 양식 없는 채널 400,
|
||||||
|
칸 저장(source=manual)·지우기, 모르는 채널 404, 앞으로의 날 400, 005 미적용 503."""
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self):
|
||||||
|
self.saved, self.missing = [], False
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||||
|
self.report = (roas, metrics)
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded()
|
||||||
|
self.saved.extend((code, d, a, source) for d, a in entries)
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
def set_ad_spend(self, code, day, amount, *, source="manual", user=""):
|
||||||
|
self.set_ad_spend_bulk(code, [(day, amount)], source=source, user=user)
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert r.json()["saved"] == 3 and r.json()["total"] == 220000 + 216697 + 220231 and r.json()["to"] == "2026-10-12"
|
||||||
|
assert store.saved[0] == ("coupang_rocket", date(2026, 10, 1), 220000, "upload")
|
||||||
|
store.saved.clear()
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_wing", files={"file": ("w.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200 and r.json()["name"] == "쿠팡(윙)" # 윙도 같은 양식
|
||||||
|
assert store.saved[0] == ("coupang_wing", date(2026, 10, 1), 220000, "upload") and len(store.saved) == 3
|
||||||
|
store.saved.clear()
|
||||||
|
bad = ROCKET_CSV + "2026년 10월 06일,RETAIL,,,,,,,,,,,1,0,1,1,1,0,abc\n"
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", bad.encode("utf-8"))})
|
||||||
|
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=google", files={"file": ("r.csv", b"x")})
|
||||||
|
assert r.status_code == 400 and "양식" in r.json()["detail"]
|
||||||
|
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "33,000"}).json()["amount"] == 33000
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-11", json={"amount": ""}).status_code == 200
|
||||||
|
assert store.saved == [("meta", date(2026, 10, 12), 33000, "manual"), ("meta", date(2026, 10, 11), None, "manual")]
|
||||||
|
assert client.put("/performance/api/ad-spend/cafe24/2026-10-12", json={"amount": 1}).status_code == 404
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-14", json={"amount": 1}).status_code == 400
|
||||||
|
assert client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": "abc"}).status_code == 400
|
||||||
|
store.missing = True
|
||||||
|
r = client.put("/performance/api/ad-spend/meta/2026-10-12", json={"amount": 1})
|
||||||
|
assert r.status_code == 503 and "005" in r.json()["detail"]
|
||||||
|
|
||||||
|
# 사용자 제공 네이버 광고 보고서(2026-10-14) — 앞 9줄 + 머리글
|
||||||
|
NAVER_CSV = """광고 계정 이름,광고 계정 ID,기간,총비용,노출수,클릭수,클릭률(%),총 전환수,구매완료 수,장바구니 담기 수,총 전환매출액,구매완료 광고수익률(%)
|
||||||
|
0_미라네주방,38461,2026.09.30.,0,0,0,0.00,46,6,40,8218000,0.00
|
||||||
|
0_미라네주방,38461,2026.09.24.,0,0,0,0.00,36,6,30,6331500,0.00
|
||||||
|
0_미라네주방,38461,2026.09.23.,300672,30043,461,1.53,71,13,58,7830100,67.58
|
||||||
|
0_미라네주방,38461,2026.09.22.,299817,31061,441,1.42,125,20,105,15040200,198.79
|
||||||
|
0_미라네주방,38461,2026.09.21.,299199,25641,416,1.62,159,44,115,19878020,501.11
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def test_naver_report_reads_date_cost_roas_and_metrics():
|
||||||
|
for content, name in ((NAVER_CSV.encode("utf-8-sig"), "n.csv"), (NAVER_CSV.encode("cp949"), "n.csv"), (_xlsx(NAVER_CSV), "n.xlsx")):
|
||||||
|
res = ads.parse_naver(content, today=TODAY, filename=name)
|
||||||
|
assert not res.errors, res.errors
|
||||||
|
assert res.entries[:3] == [(date(2026, 9, 30), 0), (date(2026, 9, 24), 0), (date(2026, 9, 23), 300672)]
|
||||||
|
assert str(res.roas[date(2026, 9, 23)]) == "67.58" and res.roas[date(2026, 9, 30)] == 0
|
||||||
|
m = res.metrics[date(2026, 9, 21)]
|
||||||
|
assert m["노출수"] == 25641 and m["클릭률(%)"] == 1.62 and m["총 전환매출액"] == 19878020
|
||||||
|
assert m["구매완료 광고수익률(%)"] == 501.11 and "광고 계정 이름" not in m and "기간" not in m
|
||||||
|
assert res.columns[0] == "총비용" and res.columns[-1] == "구매완료 광고수익률(%)"
|
||||||
|
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.22.,1,0,0,0,0,0,0,0,1\n0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
|
||||||
|
bad += "0_미라네주방,38461,2026.09.19.,5,0,0,0,0,0,0,0,x\n0_미라네주방,38461,2026.10.20.,5,0,0,0,0,0,0,0,1\n"
|
||||||
|
errs = " / ".join(ads.parse_naver(bad.encode("utf-8"), today=TODAY).errors)
|
||||||
|
assert "겹칩니다" in errs and "총비용이 숫자가 아닙니다" in errs and "ROAS" in errs and "앞으로의 날짜" in errs
|
||||||
|
|
||||||
|
|
||||||
|
def test_naver_roas_from_report_weighted():
|
||||||
|
"""네이버 칸 ROAS = 보고서 값(계산 안 함), 여러 날 = Σ(ROAS×광고비)÷Σ광고비, 광고비 0 인 날은 빼고."""
|
||||||
|
class S(_Store):
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
rows = {(date(2026, 9, 22), "naver"): 299817, (date(2026, 9, 23), "naver"): 300672,
|
||||||
|
(date(2026, 9, 24), "naver"): 0}
|
||||||
|
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
return rows, {k: "upload" for k in rows}
|
||||||
|
|
||||||
|
def ad_roas(self, start, end):
|
||||||
|
rows = {(date(2026, 9, 22), "naver"): Decimal("198.79"), (date(2026, 9, 23), "naver"): Decimal("67.58"),
|
||||||
|
(date(2026, 9, 24), "naver"): Decimal("0")}
|
||||||
|
return {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
return {(date(2026, 9, 22), "naver"): 9_999_999} if "naver" in codes else {}
|
||||||
|
|
||||||
|
ctx = ads.build_ad_dashboard(S(), kind="week", anchor=date(2026, 9, 23), today=TODAY, sales_codes=["naver"])
|
||||||
|
by = {r.get("date"): r for r in ctx["table"]}
|
||||||
|
assert by["2026-09-22"]["roas"]["naver"] == 199 and by["2026-09-23"]["roas"]["naver"] == 68
|
||||||
|
assert by["2026-09-24"]["roas"]["naver"] is None # 광고비 0
|
||||||
|
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||||
|
want = round((Decimal("198.79") * 299817 + Decimal("67.58") * 300672) / (299817 + 300672))
|
||||||
|
assert week["roas"]["naver"] == want == 133 # 매출 실적(9,999,999)으로 계산하지 않음
|
||||||
|
assert ctx["roas_basis"]["naver"] == ""
|
||||||
|
assert {r["code"]: r for r in ctx["month"]["rows"]}["naver"]["roas"] == 133
|
||||||
|
|
||||||
|
|
||||||
|
def test_naver_detail_table_totals():
|
||||||
|
rows = [{"date": "2026-09-22", "amount": 299817, "roas": Decimal("198.79"),
|
||||||
|
"metrics": {"총비용": 299817, "노출수": 31061, "클릭수": 441, "클릭률(%)": 1.42, "구매완료 광고수익률(%)": 198.79}},
|
||||||
|
{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"),
|
||||||
|
"metrics": {"총비용": 300672, "노출수": 30043, "클릭수": 461, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 67.58}},
|
||||||
|
{"date": "2026-09-24", "amount": 0, "roas": Decimal("0"), "metrics": {"총비용": 0, "노출수": 0, "클릭수": 0,
|
||||||
|
"클릭률(%)": 0.0, "구매완료 광고수익률(%)": 0}}]
|
||||||
|
t = ads.detail_table(rows)
|
||||||
|
assert t["columns"] == ["총비용", "노출수", "클릭수", "클릭률(%)", "구매완료 광고수익률(%)"]
|
||||||
|
assert t["total"]["총비용"] == 600489 and t["total"]["노출수"] == 61104 and t["total"]["클릭수"] == 902
|
||||||
|
assert t["total"]["클릭률(%)"] == round(902 * 100 / 61104, 2) # 가중: 클릭수 ÷ 노출수
|
||||||
|
assert t["total"]["구매완료 광고수익률(%)"] == 133.09 # 광고비 가중 평균 (198.79×299,817 + 67.58×300,672) ÷ 600,489
|
||||||
|
assert t["rows"][0]["values"]["노출수"] == 31061 and t["rows"][1]["roas"] == 67.58
|
||||||
|
|
||||||
|
|
||||||
|
def test_naver_upload_and_details_endpoints(monkeypatch):
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self):
|
||||||
|
self.saved, self.kw, self.missing = [], {}, ""
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded(self.missing)
|
||||||
|
self.saved.extend((code, d, a, source) for d, a in entries)
|
||||||
|
self.kw = {"roas": roas, "metrics": metrics}
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
def ad_details(self, code, start, end):
|
||||||
|
if self.missing:
|
||||||
|
raise ads.AdMigrationNeeded(self.missing)
|
||||||
|
return [{"date": "2026-09-23", "amount": 300672, "roas": Decimal("67.58"), "metrics": {"노출수": 30043}}]
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
assert r.json()["saved"] == 5 and r.json()["total"] == 300672 + 299817 + 299199
|
||||||
|
assert store.saved[2] == ("naver", date(2026, 9, 23), 300672, "upload")
|
||||||
|
assert str(store.kw["roas"][date(2026, 9, 23)]) == "67.58" and store.kw["metrics"][date(2026, 9, 21)]["클릭수"] == 416
|
||||||
|
store.saved.clear()
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=coupang_rocket", files={"file": ("r.csv", ROCKET_CSV.encode("utf-8-sig"))})
|
||||||
|
assert r.status_code == 200 and store.kw == {"roas": None, "metrics": None} # 쿠팡은 금액만
|
||||||
|
d = client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()
|
||||||
|
assert d["name"] == "네이버" and d["columns"] == ["노출수"] and d["rows"][0]["roas"] == 67.58
|
||||||
|
assert client.get("/performance/api/ad-spend/coupang_rocket/details?from=2026-09-01&to=2026-09-30").status_code == 400
|
||||||
|
assert client.get("/performance/api/ad-spend/naver/details?from=2026-09-30&to=2026-09-01").status_code == 400
|
||||||
|
store.missing = "006"
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("n.csv", NAVER_CSV.encode("utf-8"))})
|
||||||
|
assert r.status_code == 503 and "006" in r.json()["detail"]
|
||||||
|
assert "006" in client.get("/performance/api/ad-spend/naver/details?from=2026-09-01&to=2026-09-30").json()["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_merge_results_newest_file_wins():
|
||||||
|
"""여러 파일 — 같은 날짜는 파일 날짜(수정 시각)가 최신인 파일 값, 같으면 나중 파일. ROAS·상세도 그 파일 것."""
|
||||||
|
a = ads.ParseResult(entries=[(date(2026, 9, 1), 100), (date(2026, 9, 2), 200)],
|
||||||
|
roas={date(2026, 9, 2): Decimal("10")}, metrics={date(2026, 9, 2): {"노출수": 1}}, columns=["노출수"])
|
||||||
|
b = ads.ParseResult(entries=[(date(2026, 9, 2), 999), (date(2026, 9, 3), 300)],
|
||||||
|
roas={date(2026, 9, 2): Decimal("99")}, metrics={date(2026, 9, 2): {"노출수": 9}}, columns=["노출수", "클릭수"])
|
||||||
|
m, overlap = ads.merge_results([("new.csv", 2000.0, a), ("old.csv", 1000.0, b)]) # a 가 최신
|
||||||
|
assert m.entries == [(date(2026, 9, 1), 100), (date(2026, 9, 2), 200), (date(2026, 9, 3), 300)]
|
||||||
|
assert m.roas[date(2026, 9, 2)] == Decimal("10") and m.metrics[date(2026, 9, 2)] == {"노출수": 1}
|
||||||
|
assert overlap == [date(2026, 9, 2)] and m.columns == ["노출수", "클릭수"]
|
||||||
|
m2, _ = ads.merge_results([("a.csv", 1000.0, a), ("b.csv", 1000.0, b)]) # 같은 시각 → 나중 파일
|
||||||
|
assert dict(m2.entries)[date(2026, 9, 2)] == 999
|
||||||
|
bad = ads.ParseResult(errors=["3행: 오류"])
|
||||||
|
m3, _ = ads.merge_results([("a.csv", 1.0, a), ("bad.csv", 2.0, bad)])
|
||||||
|
assert m3.errors == ["[bad.csv] 3행: 오류"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_multiple_files_endpoint(monkeypatch):
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
saved: list = []
|
||||||
|
|
||||||
|
def set_ad_spend_bulk(self, code, entries, *, source="manual", user="", roas=None, metrics=None):
|
||||||
|
self.saved = list(entries)
|
||||||
|
self.roas = roas
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
old = NAVER_CSV
|
||||||
|
new = NAVER_CSV.replace("2026.09.23.,300672", "2026.09.23.,111111").replace(",67.58", ",12.34")
|
||||||
|
files = [("files", ("new.csv", new.encode("utf-8"))), ("files", ("old.csv", old.encode("utf-8")))]
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["2000", "1000"]})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
body = r.json()
|
||||||
|
assert body["files"] == 2 and body["overlap_days"] == 5 and body["saved"] == 5
|
||||||
|
assert dict(store.saved)[date(2026, 9, 23)] == 111111 and str(store.roas[date(2026, 9, 23)]) == "12.34" # 최신 파일
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver", files=files, data={"modified": ["1000", "2000"]})
|
||||||
|
assert dict(store.saved)[date(2026, 9, 23)] == 300672 # 이번엔 old 가 최신
|
||||||
|
bad = NAVER_CSV + "0_미라네주방,38461,2026.09.20.,abc,0,0,0,0,0,0,0,1\n"
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver",
|
||||||
|
files=[("files", ("ok.csv", old.encode("utf-8"))), ("files", ("bad.csv", bad.encode("utf-8")))])
|
||||||
|
assert r.status_code == 400 and r.json()["errors"][0].startswith("[bad.csv]")
|
||||||
|
r = client.post("/performance/api/ad-spend/upload?channel=naver", files={"file": ("one.csv", old.encode("utf-8"))})
|
||||||
|
assert r.status_code == 200 and r.json()["files"] == 1 # 예전 file 한 개도
|
||||||
|
assert client.post("/performance/api/ad-spend/upload?channel=naver").status_code in (400, 422)
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""매출 자동 업데이트 — 회차 시각 계산·건너뛰기."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from app.modules.performance import auto_sync as au
|
||||||
|
|
||||||
|
KST = timezone(timedelta(hours=9))
|
||||||
|
H = (9, 19)
|
||||||
|
|
||||||
|
|
||||||
|
def _t(h, m, d=13):
|
||||||
|
return datetime(2026, 10, d, h, m, tzinfo=KST)
|
||||||
|
|
||||||
|
|
||||||
|
def test_slots_every_half_hour_9_to_19():
|
||||||
|
slots = [t for t in (_t(0, 0) + timedelta(minutes=30 * i) for i in range(48)) if au.is_slot(t, H)]
|
||||||
|
assert slots[0] == _t(9, 0) and slots[-1] == _t(19, 0) and len(slots) == 21
|
||||||
|
assert not au.is_slot(_t(19, 30), H) and not au.is_slot(_t(8, 30), H) and not au.is_slot(_t(10, 15), H)
|
||||||
|
|
||||||
|
|
||||||
|
def test_next_slot():
|
||||||
|
assert au.next_slot(_t(8, 10), H) == _t(9, 0)
|
||||||
|
assert au.next_slot(_t(9, 0), H) == _t(9, 30) # 지금 회차는 이미 지남 → 다음
|
||||||
|
assert au.next_slot(datetime(2026, 10, 13, 9, 29, 59, tzinfo=KST), H) == _t(9, 30)
|
||||||
|
assert au.next_slot(_t(18, 45), H) == _t(19, 0)
|
||||||
|
assert au.next_slot(_t(19, 0), H) == _t(9, 0, d=14) # 저녁 이후 → 다음 날 9시
|
||||||
|
assert au.next_slot(_t(23, 59), H) == _t(9, 0, d=14)
|
||||||
|
|
||||||
|
|
||||||
|
def test_env_parsing(monkeypatch):
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC", raising=False)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_DAYS", raising=False)
|
||||||
|
monkeypatch.delenv("PERFORMANCE_AUTO_SYNC_HOURS", raising=False)
|
||||||
|
assert au.enabled() and au.sync_days() == 10 and au.hour_window() == (9, 19)
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC", "false")
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_DAYS", "200")
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "20-8") # 잘못된 값 → 기본
|
||||||
|
assert not au.enabled() and au.sync_days() == 90 and au.hour_window() == (9, 19)
|
||||||
|
monkeypatch.setenv("PERFORMANCE_AUTO_SYNC_HOURS", "8-20")
|
||||||
|
assert au.hour_window() == (8, 20)
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_once_uses_job_and_skips_when_busy(monkeypatch):
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
from app.modules.performance.sync import SyncService
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_sync_all(self, *, start, end, codes=None, trigger="manual", user="", job=None):
|
||||||
|
calls.append((start, end, trigger, user, job is not None))
|
||||||
|
return [{"code": "naver", "ok": True}, {"code": "toss", "ok": False, "skipped": False}]
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def last_update_at(self):
|
||||||
|
return "2026-10-13T09:00:05+09:00"
|
||||||
|
|
||||||
|
monkeypatch.setattr(SyncService, "sync_all", fake_sync_all)
|
||||||
|
monkeypatch.setattr(jobs, "running_job", lambda: None)
|
||||||
|
res = au.run_once(Store(), None, today=date(2026, 10, 13), days=10)
|
||||||
|
assert calls == [(date(2026, 10, 4), date(2026, 10, 13), "schedule", au.AUTO_USER, True)]
|
||||||
|
# 광고 API 저장소 메서드가 없는 가짜 저장소 — 광고 가져오기는 조용히 빠지고 매출 결과는 그대로
|
||||||
|
assert res == {"skipped": False, "from": "2026-10-04", "to": "2026-10-13", "ok": 1, "failed": ["toss"], "error": "",
|
||||||
|
"ads": []}
|
||||||
|
|
||||||
|
monkeypatch.setattr(jobs, "running_job", lambda: object())
|
||||||
|
assert au.run_once(Store(), None, today=date(2026, 10, 13), days=10)["skipped"]
|
||||||
|
assert len(calls) == 1
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""쿠팡 발주서 — 504(시간 초과)면 조회 구간을 반으로 줄여 다시 부른다."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||||
|
|
||||||
|
|
||||||
|
class Creds:
|
||||||
|
def get(self, key):
|
||||||
|
return {"vendor_id": "A001", "access_key": "ak", "secret_key": "sk"}[key]
|
||||||
|
|
||||||
|
def has(self, key):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _ctx():
|
||||||
|
return AdapterContext(code="coupang", credentials=Creds())
|
||||||
|
|
||||||
|
|
||||||
|
def _days(params):
|
||||||
|
a = date.fromisoformat(params["createdAtFrom"][:10])
|
||||||
|
b = date.fromisoformat(params["createdAtTo"][:10])
|
||||||
|
return a, b
|
||||||
|
|
||||||
|
|
||||||
|
def test_seller_window_halves_on_timeout_and_remembers(monkeypatch):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
a, b = _days(params)
|
||||||
|
calls.append((params["status"], a, b))
|
||||||
|
if params["status"] == "FINAL_DELIVERY" and (b - a).days + 1 > 7:
|
||||||
|
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||||
|
return [{"orderId": f"{params['status']}-{a}-{b}"}]
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
ad = cp.CoupangAdapter()
|
||||||
|
start, end = date(2026, 1, 1), date(2026, 3, 31) # 주문일 2025-12-31 ~ 3-31 = 91일 → 31일 구간 3개
|
||||||
|
ad._seller_orders(_ctx(), start, end)
|
||||||
|
|
||||||
|
fd = [(a, b) for st, a, b in calls if st == "FINAL_DELIVERY"]
|
||||||
|
ok = [(a, b) for a, b in fd if (b - a).days + 1 <= 7]
|
||||||
|
# 성공한 구간이 빈틈·겹침 없이 전체 주문일을 덮는다
|
||||||
|
d = start - timedelta(days=1)
|
||||||
|
for a, b in ok:
|
||||||
|
assert a == d
|
||||||
|
d = b + timedelta(days=1)
|
||||||
|
assert d == end + timedelta(days=1)
|
||||||
|
# 31 → 15 → 7 로 줄인 뒤엔 다음 31일 구간도 처음부터 7일로(실패는 첫 구간의 두 번뿐)
|
||||||
|
assert len(fd) - len(ok) == 2
|
||||||
|
# 다른 상태는 31일 그대로
|
||||||
|
assert sum(1 for st, a, b in calls if st == "ACCEPT") == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_day_timeout_retries_then_fails(monkeypatch):
|
||||||
|
sleeps = []
|
||||||
|
monkeypatch.setattr(cp.time, "sleep", lambda s: sleeps.append(s))
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
if params["status"] == "FINAL_DELIVERY":
|
||||||
|
raise cp.GatewayTimeout("쿠팡 발주서 API 오류(504): Request timed out")
|
||||||
|
return []
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
with pytest.raises(ApiError) as ei:
|
||||||
|
cp.CoupangAdapter()._seller_orders(_ctx(), date(2026, 1, 5), date(2026, 1, 5))
|
||||||
|
assert "하루도 시간 초과" in ei.value.message and "FINAL_DELIVERY" in ei.value.message
|
||||||
|
assert sleeps == [3.0, 6.0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_rg_window_halves_on_timeout(monkeypatch):
|
||||||
|
got = []
|
||||||
|
|
||||||
|
def fake_pages(self, ctx, path, params, *, rg=False):
|
||||||
|
a = date(int(params["paidDateFrom"][:4]), int(params["paidDateFrom"][4:6]), int(params["paidDateFrom"][6:]))
|
||||||
|
b = date(int(params["paidDateTo"][:4]), int(params["paidDateTo"][4:6]), int(params["paidDateTo"][6:]))
|
||||||
|
if (b - a).days + 1 > 10:
|
||||||
|
raise cp.GatewayTimeout("쿠팡 로켓그로스 주문 API 오류(504)")
|
||||||
|
got.append((a, b))
|
||||||
|
return [{"orderId": str(a)}]
|
||||||
|
|
||||||
|
monkeypatch.setattr(cp.CoupangAdapter, "_pages", fake_pages)
|
||||||
|
cp.CoupangAdapter()._rg_orders(_ctx(), date(2026, 1, 1), date(2026, 1, 30))
|
||||||
|
assert got[0][0] == date(2026, 1, 1) and got[-1][1] == date(2026, 1, 30)
|
||||||
|
assert all((b - a).days + 1 <= 10 for a, b in got)
|
||||||
|
assert all(got[i + 1][0] == got[i][1] + timedelta(days=1) for i in range(len(got) - 1))
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""매출 실적 화면 — 매출 칸 아래 광고비(ROAS%)·매출 단위(원·천원·백만원) (2026-10-19)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from app.modules.performance import dashboard
|
||||||
|
|
||||||
|
TODAY = date(2026, 10, 7)
|
||||||
|
|
||||||
|
|
||||||
|
class _Store:
|
||||||
|
"""build_dashboard 가 읽는 것만 — 카페24·네이버·쿠팡 매출 + 구글·메타·네이버·쿠팡(윙) 광고비."""
|
||||||
|
|
||||||
|
def __init__(self, ads_missing=False):
|
||||||
|
self.ads_missing = ads_missing
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{"code": c, "name": n, "enabled": True, "include_in_sales": True}
|
||||||
|
for c, n in (("cafe24", "카페24"), ("naver", "네이버 스마트스토어"), ("coupang", "쿠팡"))]
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
rows = {(date(2026, 10, 5), "cafe24"): 2_000_000, (date(2026, 10, 5), "coupang"): 600_000,
|
||||||
|
(date(2026, 10, 6), "naver"): 1_234_567}
|
||||||
|
return {k: v for k, v in rows.items() if start <= k[0] <= end and k[1] in codes}
|
||||||
|
|
||||||
|
def rate_table(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def statuses(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def last_update_at(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def running_codes(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
def ad_amounts(self, start, end):
|
||||||
|
if self.ads_missing:
|
||||||
|
raise RuntimeError("perf_ad_spend 없음")
|
||||||
|
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "meta"): 50_000,
|
||||||
|
(date(2026, 10, 5), "coupang_wing"): 200_000, (date(2026, 10, 6), "naver"): 300_000}
|
||||||
|
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
return rows, {k: "manual" for k in rows}
|
||||||
|
|
||||||
|
def ad_roas(self, start, end):
|
||||||
|
rows = {(date(2026, 10, 5), "google"): 412.5, (date(2026, 10, 6), "naver"): 150}
|
||||||
|
return {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||||
|
|
||||||
|
|
||||||
|
def test_sales_ad_channels_mapping():
|
||||||
|
m = dashboard.sales_ad_channels()
|
||||||
|
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"))
|
||||||
|
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
|
||||||
|
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_lines_under_sales_cells():
|
||||||
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
# 카페24 = 구글·메타 두 줄, ROAS 는 광고 보고서 값(구글 412.5 → 413), 메타는 보고서 ROAS 없음
|
||||||
|
assert day5["ads"]["cafe24"] == [{"label": "구글", "amount": 100_000, "roas": 413},
|
||||||
|
{"label": "메타", "amount": 50_000, "roas": None}]
|
||||||
|
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
|
||||||
|
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
|
||||||
|
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
|
||||||
|
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합
|
||||||
|
assert day5["ads_total"] == {"amount": 350_000, "roas": 743} # 2,600,000 ÷ 350,000
|
||||||
|
day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06")
|
||||||
|
assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}]
|
||||||
|
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||||
|
assert [a["amount"] for a in week["ads"]["cafe24"]] == [100_000, 50_000] and week["ads_total"]["amount"] == 650_000
|
||||||
|
day1 = next(r for r in ctx["table"] if r.get("date") == "2026-10-07")
|
||||||
|
assert day1["ads"] == {} and day1["ads_total"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_lines_follow_shop_filter_and_missing_table():
|
||||||
|
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"])
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300}
|
||||||
|
ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY)
|
||||||
|
assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로
|
||||||
|
|
||||||
|
|
||||||
|
def test_amount_text_units():
|
||||||
|
assert dashboard.amount_text(2_475_300) == "2,475,300"
|
||||||
|
assert dashboard.amount_text(2_475_300, "thousand") == "2,475"
|
||||||
|
assert dashboard.amount_text(2_475_500, "thousand") == "2,476"
|
||||||
|
assert dashboard.amount_text(2_475_300, "million") == "2.5"
|
||||||
|
assert dashboard.amount_text(158_000, "million") == "0.2"
|
||||||
|
assert dashboard.amount_text(-158_000, "thousand") == "-158"
|
||||||
|
assert dashboard.amount_text(1_234_567_890, "million") == "1,234.6"
|
||||||
|
assert dashboard.amount_text(5, "nope") == "5" and dashboard.normalize_unit("x") == "won"
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
|
||||||
|
class _Creds:
|
||||||
|
def configured_codes(self, adapters):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
store = _Store()
|
||||||
|
monkeypatch.setattr(common, "guard", lambda request, admin=False: (store, {"email": "king@x", "name": "King", "is_admin": True}))
|
||||||
|
monkeypatch.setattr(common, "services", lambda request, st: (_Creds(), None))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
assert "2,000,000" in html
|
||||||
|
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
|
||||||
|
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
|
||||||
|
|
||||||
|
client.cookies.set("perf_unit", "thousand")
|
||||||
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
assert "단위: 천원" in html and "2,000<" in html and "<i>구글</i>100<em>(413%)</em>" in html
|
||||||
|
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
|
||||||
|
client.cookies.set("perf_unit", "million")
|
||||||
|
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||||
|
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
"""구글 광고 API 연동(2026-10-15) — 입력 검사·토큰·조회·변환·오류 안내·저장 서비스·라우터. 구글 서버는 가짜(httpx MockTransport)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from urllib.parse import parse_qs
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
|
||||||
|
from app.modules.performance import ad_sync
|
||||||
|
from app.modules.performance.ad_sources import google_ads as ga
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured
|
||||||
|
from app.modules.performance.credentials import CredentialService, aad_for
|
||||||
|
from app.modules.performance.security import crypto
|
||||||
|
|
||||||
|
KEY1 = "11" * 32
|
||||||
|
|
||||||
|
|
||||||
|
def _sa_json() -> str:
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||||
|
serialization.NoEncryption()).decode()
|
||||||
|
return json.dumps({"type": "service_account", "client_email": "erp@proj.iam.gserviceaccount.com",
|
||||||
|
"private_key_id": "kid1", "private_key": pem, "token_uri": "https://oauth2.googleapis.com/token"})
|
||||||
|
|
||||||
|
|
||||||
|
SA = _sa_json()
|
||||||
|
|
||||||
|
|
||||||
|
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 set(self, key, value):
|
||||||
|
self.values[key] = value
|
||||||
|
|
||||||
|
def known_secrets(self):
|
||||||
|
return [v for v in self.values.values() if v]
|
||||||
|
|
||||||
|
|
||||||
|
def _ctx(**over):
|
||||||
|
values = {"customer_id": "123-456-7890", "service_account_json": SA}
|
||||||
|
values.update(over)
|
||||||
|
return AdapterContext(code="google", credentials=Creds(values))
|
||||||
|
|
||||||
|
|
||||||
|
def _install(monkeypatch, handler):
|
||||||
|
"""구글(토큰·광고 API) 가짜 서버 — handler(request) 가 searchStream 응답을 만든다. 보낸 요청을 돌려준다."""
|
||||||
|
ga._token_cache.clear()
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def route(request: httpx.Request) -> httpx.Response:
|
||||||
|
seen.append(request)
|
||||||
|
if request.url.host == "oauth2.googleapis.com":
|
||||||
|
form = parse_qs(request.content.decode())
|
||||||
|
assert form["grant_type"] == ["urn:ietf:params:oauth:grant-type:jwt-bearer"] and form["assertion"][0].count(".") == 2
|
||||||
|
return httpx.Response(200, json={"access_token": "ya29.TOKEN", "expires_in": 3600})
|
||||||
|
return handler(request)
|
||||||
|
|
||||||
|
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
ROWS = [{"results": [
|
||||||
|
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-01"},
|
||||||
|
"metrics": {"costMicros": "123456500000", "impressions": "20000", "clicks": "400", "conversions": 12.5,
|
||||||
|
"conversionsValue": 617282.5}},
|
||||||
|
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-02"},
|
||||||
|
"metrics": {"impressions": "50"}}, # 비용 0(값이 빠진 칸)
|
||||||
|
]}, {"results": [
|
||||||
|
{"customer": {"currencyCode": "KRW"}, "segments": {"date": "2026-10-03"},
|
||||||
|
"metrics": {"costMicros": "1000000", "clicks": "1", "impressions": "10", "conversionsValue": 3000}},
|
||||||
|
]}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_credentials():
|
||||||
|
src = ga.GoogleAdsSource()
|
||||||
|
ok = {"customer_id": "123-456-7890", "service_account_json": SA}
|
||||||
|
assert src.validate_credentials(ok) == []
|
||||||
|
assert src.validate_credentials({**ok, "service_account_json": "__stored__"}) == []
|
||||||
|
assert "developer_token" not in {f.key for f in src.visible_fields()} # 개발자 토큰 폐지(2026-09-09) — 입력칸 없음
|
||||||
|
errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26",
|
||||||
|
"service_account_json": '{"type": "authorized_user"}'})
|
||||||
|
assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음
|
||||||
|
assert "입력하세요" in " ".join(src.validate_credentials({}))
|
||||||
|
assert "JSON" in " ".join(src.validate_credentials({**ok, "service_account_json": "not json"}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_days_converts_and_sends_headers(monkeypatch):
|
||||||
|
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=ROWS))
|
||||||
|
days = ga.GoogleAdsSource().fetch_days(_ctx(login_customer_id="999-888-7777", api_version="v27"),
|
||||||
|
date(2026, 10, 1), date(2026, 10, 3))
|
||||||
|
api = seen[-1]
|
||||||
|
assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream"
|
||||||
|
assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and "developer-token" not in api.headers # 폐지된 머리글은 보내지 않음
|
||||||
|
assert api.headers["login-customer-id"] == "9998887777"
|
||||||
|
q = json.loads(api.content)["query"]
|
||||||
|
assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q
|
||||||
|
d1, d2, d3 = days
|
||||||
|
# 광고비 = 부가세 포함(2026-10-15): 123,456.5원 × 1.1 = 135,802.15 → 135,802. ROAS 는 구글 값 그대로(617,282.5 ÷ 123,456.5)
|
||||||
|
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 135802, Decimal("500.00"))
|
||||||
|
assert d1.metrics == {"광고비(부가세 포함)": 135802, "비용(부가세 별도)": 123457, "노출수": 20000, "클릭수": 400,
|
||||||
|
"클릭률(%)": 2.0, "전환수": 12.5, "전환 가치": 617283, "ROAS(%)": 500.0}
|
||||||
|
assert list(d1.metrics)[:2] == ["광고비(부가세 포함)", "비용(부가세 별도)"] # 일자별 표 열 순서
|
||||||
|
assert (d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (0, None, 0.0) # 비용 0 → ROAS 없음
|
||||||
|
assert (d3.amount, d3.roas) == (1, Decimal("300000.00"))
|
||||||
|
# 토큰은 한 번만 받아 두고 다시 쓴다
|
||||||
|
ga.GoogleAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert sum(1 for r in seen if r.url.host == "oauth2.googleapis.com") == 1
|
||||||
|
assert "login-customer-id" not in seen[-1].headers and "/v26/" in str(seen[-1].url) # 비우면 MCC 없음·기본 버전
|
||||||
|
|
||||||
|
|
||||||
|
def test_errors_are_explained(monkeypatch):
|
||||||
|
src = ga.GoogleAdsSource()
|
||||||
|
denied = [{"error": {"code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED",
|
||||||
|
"details": [{"errors": [{"errorCode": {"authorizationError": "USER_PERMISSION_DENIED"},
|
||||||
|
"message": "User doesn't have permission to access customer."}]}]}}]
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(403, json=denied))
|
||||||
|
with pytest.raises(AuthFailed) as e:
|
||||||
|
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert "USER_PERMISSION_DENIED" in e.value.message and "액세스 및 보안" in e.value.message
|
||||||
|
|
||||||
|
# 사용자 화면 오류(2026-10-15): 로그인 고객 ID(MCC) 칸에 권한 없는 번호 → 칸을 비우라는 안내
|
||||||
|
bad_login = [{"error": {"code": 403, "message": "PERMISSION_DENIED", "details": [{"errors": [
|
||||||
|
{"errorCode": {"authorizationError": "INVALID_LOGIN_CUSTOMER_ID"},
|
||||||
|
"message": "The login customer id header 'Optional[9998887777]' could not be validated."}]}]}}]
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(403, json=bad_login))
|
||||||
|
with pytest.raises(AuthFailed) as e:
|
||||||
|
src.fetch_days(_ctx(login_customer_id="999-888-7777"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert "INVALID_LOGIN_CUSTOMER_ID" in e.value.message and "칸을 지우고" in e.value.message
|
||||||
|
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(404, text="Not Found"))
|
||||||
|
with pytest.raises(ApiError) as e:
|
||||||
|
src.fetch_days(_ctx(api_version="v19"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert "v19" in e.value.message and "API 버전" in e.value.message
|
||||||
|
|
||||||
|
usd = [{"results": [{"customer": {"currencyCode": "USD"}, "segments": {"date": "2026-10-01"}, "metrics": {}}]}]
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(200, json=usd))
|
||||||
|
with pytest.raises(ApiError, match="USD"):
|
||||||
|
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
|
||||||
|
with pytest.raises(NotConfigured):
|
||||||
|
src.fetch_days(_ctx(customer_id=""), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
|
||||||
|
ga._token_cache.clear()
|
||||||
|
|
||||||
|
def bad_token(request):
|
||||||
|
return httpx.Response(400, json={"error": "invalid_grant", "error_description": "Invalid JWT Signature."})
|
||||||
|
|
||||||
|
monkeypatch.setattr(ga, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(bad_token)))
|
||||||
|
with pytest.raises(AuthFailed, match="invalid_grant"):
|
||||||
|
src.fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_message(monkeypatch):
|
||||||
|
body = [{"results": [{"customer": {"id": "1234567890", "descriptiveName": "미라네주방", "currencyCode": "KRW",
|
||||||
|
"timeZone": "Asia/Seoul"}}]}]
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(200, json=body))
|
||||||
|
assert ga.GoogleAdsSource().test_connection(_ctx()) == "연결됨 — 미라네주방 · 통화 KRW · 시간대 Asia/Seoul"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ad_credentials_use_own_namespace():
|
||||||
|
"""광고 인증정보 암호문은 "perf:ad:{채널}:{항목}" 에 묶인다 — 쇼핑몰 암호문과 바꿔 넣으면 복호화되지 않는다."""
|
||||||
|
ring = crypto.KeyRing.from_env({"APP_ENCRYPTION_KEY": KEY1})
|
||||||
|
|
||||||
|
class Table:
|
||||||
|
def __init__(self):
|
||||||
|
self.rows = {}
|
||||||
|
|
||||||
|
def credential_rows(self, code):
|
||||||
|
return {k: {"encrypted_value": v, "key_version": 1} for (c, k), v in self.rows.items() if c == code}
|
||||||
|
|
||||||
|
def upsert_credential(self, code, key, *, encrypted_value, key_version, user=""):
|
||||||
|
self.rows[(code, key)] = encrypted_value
|
||||||
|
|
||||||
|
t = Table()
|
||||||
|
svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS)
|
||||||
|
svc.save(ga.GoogleAdsSource(), {"service_account_json": SA, "customer_id": "1234567890"}, user="king")
|
||||||
|
assert svc.accessor("google").get("service_account_json") == SA
|
||||||
|
assert aad_for("google", "service_account_json", "ad:") == "perf:ad:google:service_account_json"
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
crypto.decrypt(t.rows[("google", "service_account_json")], aad=aad_for("google", "service_account_json"), ring=ring)
|
||||||
|
# 저장된 일반 항목을 화면에서 비우고 [연결 테스트] → 그 항목은 빈 값으로(저장값 무시), 새 입력값이 있으면 그 값
|
||||||
|
svc.save(ga.GoogleAdsSource(), {"login_customer_id": "999-888-7777"}, user="king")
|
||||||
|
acc = svc.accessor("google", cleared={"login_customer_id"})
|
||||||
|
assert acc.get("login_customer_id") == "" and not acc.has("login_customer_id") and acc.get("customer_id") == "1234567890"
|
||||||
|
assert svc.accessor("google").get("login_customer_id") == "999-888-7777"
|
||||||
|
acc = svc.accessor("google", overrides={"login_customer_id": "111-222-3333"}, cleared={"login_customer_id"})
|
||||||
|
assert acc.get("login_customer_id") == "111-222-3333"
|
||||||
|
# [저장] 때 clear 로 보내면 지워진다(빈 칸 = 유지가 아니라 지움)
|
||||||
|
t.delete_credential = lambda code, key: t.rows.pop((code, key))
|
||||||
|
svc.save(ga.GoogleAdsSource(), {}, clear=["login_customer_id"], user="king")
|
||||||
|
assert ("google", "login_customer_id") not in t.rows
|
||||||
|
|
||||||
|
|
||||||
|
class FakeStore:
|
||||||
|
def __init__(self):
|
||||||
|
self.replaced, self.status = [], []
|
||||||
|
|
||||||
|
def ad_credential_keys_by_code(self):
|
||||||
|
return {"google": {"customer_id", "service_account_json"}}
|
||||||
|
|
||||||
|
def ad_credential_rows(self, code):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def replace_ad_api_range(self, code, start, end, days, *, user=""):
|
||||||
|
self.replaced.append((code, start, end, days, user))
|
||||||
|
return len(days)
|
||||||
|
|
||||||
|
def record_ad_status(self, code, *, status, ok, error="", kind="test"):
|
||||||
|
self.status.append((code, status, ok, error, kind))
|
||||||
|
|
||||||
|
|
||||||
|
def _service(store, source):
|
||||||
|
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||||||
|
svc.configured = lambda: {"google": True}
|
||||||
|
svc._ctx = lambda code, values=None, user="": _ctx()
|
||||||
|
return svc
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_service_saves_and_records(monkeypatch):
|
||||||
|
store = FakeStore()
|
||||||
|
from app.modules.performance.ad_sources.base import AdDay
|
||||||
|
|
||||||
|
src = ga.GoogleAdsSource()
|
||||||
|
monkeypatch.setattr(src, "fetch_days", lambda ctx, s, e: [AdDay(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})])
|
||||||
|
monkeypatch.setattr(ad_sync, "get_source", lambda code: src)
|
||||||
|
svc = _service(store, src)
|
||||||
|
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 3), user="king@x")
|
||||||
|
assert res["ok"] and res["days"] == 1 and res["total"] == 1000
|
||||||
|
assert store.replaced == [("google", date(2026, 10, 1), date(2026, 10, 3),
|
||||||
|
[(date(2026, 10, 1), 1000, Decimal("250.00"), {"비용": 1000})], "king@x")]
|
||||||
|
assert store.status[-1] == ("google", "ok", True, "", "sync")
|
||||||
|
|
||||||
|
# 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림)
|
||||||
|
def boom(ctx, s, e):
|
||||||
|
raise AuthFailed("거부된 값 123-456-7890")
|
||||||
|
|
||||||
|
monkeypatch.setattr(src, "fetch_days", boom)
|
||||||
|
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert not res["ok"] and res["status"] == "auth_failed" and "123-456-7890" not in res["message"] # 꺼낸 인증정보 값은 가림
|
||||||
|
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False)
|
||||||
|
|
||||||
|
# 같은 채널 동시 실행 막기
|
||||||
|
lock = ad_sync._lock("google")
|
||||||
|
lock.acquire()
|
||||||
|
try:
|
||||||
|
with pytest.raises(ad_sync.AdSyncBusy):
|
||||||
|
svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert svc.sync_all(date(2026, 10, 1), date(2026, 10, 1))[0]["skipped"]
|
||||||
|
finally:
|
||||||
|
lock.release()
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_endpoint(monkeypatch):
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router")
|
||||||
|
calls, admin = [], {"v": False}
|
||||||
|
|
||||||
|
class Svc:
|
||||||
|
def __init__(self):
|
||||||
|
self.result = {"ok": True, "code": "google", "name": "구글 광고", "days": 3, "total": 9000}
|
||||||
|
self.conf = {"google": True}
|
||||||
|
|
||||||
|
def configured(self):
|
||||||
|
return self.conf
|
||||||
|
|
||||||
|
def sync(self, code, start, end, *, user=""):
|
||||||
|
calls.append((code, start, end, user))
|
||||||
|
return {**self.result, "from": start.isoformat(), "to": end.isoformat()}
|
||||||
|
|
||||||
|
svc = Svc()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: date(2026, 10, 15))
|
||||||
|
monkeypatch.setattr(perf_router, "_ad_services", lambda store: (None, svc))
|
||||||
|
import app.store as app_store
|
||||||
|
|
||||||
|
monkeypatch.setattr(app_store, "is_admin", lambda user: admin["v"])
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-10-01", "to": "2026-10-31"})
|
||||||
|
assert r.status_code == 200 and r.json()["to"] == "2026-10-15" # 오늘 뒤는 잘라냄
|
||||||
|
assert calls[-1] == ("google", date(2026, 10, 1), date(2026, 10, 15), "king@x")
|
||||||
|
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||||
|
assert r.status_code == 200 and calls[-1][1] == date(2026, 10, 6) # 기본 = 최근 10일
|
||||||
|
r = client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"})
|
||||||
|
assert r.status_code == 403 # 92일 넘으면 관리자만
|
||||||
|
admin["v"] = True
|
||||||
|
assert client.post("/performance/api/ad-sources/google/sync", json={"from": "2026-01-01", "to": "2026-10-15"}).status_code == 200
|
||||||
|
assert client.post("/performance/api/ad-sources/kakao/sync", json={}).status_code == 404 # 광고 API 연동이 없는 채널
|
||||||
|
r = client.post("/performance/api/ad-sources/meta/sync", json={}) # 메타(2026-10-16) — 연동은 있으나 미설정
|
||||||
|
assert r.status_code == 400 and "설정되지 않았습니다" in r.json()["detail"]
|
||||||
|
svc.result = {"ok": False, "code": "google", "name": "구글 광고", "status": "auth_failed", "message": "권한 없음"}
|
||||||
|
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||||
|
assert r.status_code == 502 and "권한 없음" in r.json()["detail"]
|
||||||
|
svc.conf = {"google": False}
|
||||||
|
r = client.post("/performance/api/ad-sources/google/sync", json={})
|
||||||
|
assert r.status_code == 400 and "설정" in r.json()["detail"]
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
"""수동 입력 엑셀 업로드 — 머리글 매칭·값 있는 칸만·오류 시 전부 거절."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
from datetime import date, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import manual_upload as mu
|
||||||
|
|
||||||
|
TODAY = date(2026, 10, 13)
|
||||||
|
MARKETS = [
|
||||||
|
{"code": "naver", "name": "네이버", "manual_input": False},
|
||||||
|
{"code": "coupang_rocket", "name": "쿠팡(로켓)", "manual_input": True},
|
||||||
|
{"code": "ohouse", "name": "오늘의집", "manual_input": True},
|
||||||
|
{"code": "toss", "name": "토스쇼핑", "manual_input": True},
|
||||||
|
{"code": "atomy", "name": "애터미아자몰", "manual_input": True},
|
||||||
|
]
|
||||||
|
EXTRA = {"toss": ("토스쇼핑", "토스")}
|
||||||
|
|
||||||
|
|
||||||
|
def _xlsx(rows):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
for r in rows:
|
||||||
|
ws.append(list(r))
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(rows):
|
||||||
|
return mu.parse_workbook(_xlsx(rows), markets=MARKETS, today=TODAY, extra_names=EXTRA)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_filled_cells_of_manual_shops():
|
||||||
|
res = _parse([
|
||||||
|
("날짜", "쿠팡(로켓)", " 오늘의 집 ", "네이버", "모르는몰", "토스", "애터미아자몰"),
|
||||||
|
(datetime(2026, 10, 12), 1_000, None, 999, 5, "12,300원", ""),
|
||||||
|
("2026.10.13(화)", None, 0, None, None, None, 4500.4),
|
||||||
|
(None, None, None, None, None, None, None), # 빈 줄
|
||||||
|
])
|
||||||
|
assert not res.errors
|
||||||
|
assert res.columns == ["coupang_rocket", "ohouse", "toss", "atomy"]
|
||||||
|
assert sorted(res.entries) == sorted([
|
||||||
|
("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 12), 12300),
|
||||||
|
("ohouse", date(2026, 10, 13), 0), ("atomy", date(2026, 10, 13), 4500)])
|
||||||
|
assert res.ignored == ["네이버(수동 입력 꺼짐)", "모르는몰(알 수 없는 쇼핑몰)"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("raw, expect", [
|
||||||
|
("2026-10-01", date(2026, 10, 1)), ("2026/10/1", date(2026, 10, 1)), ("20261001", date(2026, 10, 1)),
|
||||||
|
(20261001, date(2026, 10, 1)), (46296, date(2026, 10, 1)), ("2026년 10월 1일", date(2026, 10, 1)), (None, None),
|
||||||
|
])
|
||||||
|
def test_parse_date(raw, expect):
|
||||||
|
assert mu.parse_date(raw) == expect
|
||||||
|
|
||||||
|
|
||||||
|
def test_errors_reject_everything_with_cell_refs():
|
||||||
|
res = _parse([
|
||||||
|
("날짜", "쿠팡(로켓)", "오늘의집"),
|
||||||
|
("2026-10-10", "abc", 100),
|
||||||
|
("엉터리", 1, None),
|
||||||
|
("2026-10-14", 1, None), # 앞으로의 날짜
|
||||||
|
(None, 5, None), # 날짜 없음
|
||||||
|
("2026-10-11", 7, None),
|
||||||
|
("2026-10-11", 8, None), # 같은 날 두 번
|
||||||
|
])
|
||||||
|
joined = "\n".join(res.errors)
|
||||||
|
assert "B2" in joined and "A3" in joined and "A4" in joined and "5행" in joined and "B7" in joined
|
||||||
|
assert len(res.errors) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_header_problems():
|
||||||
|
with pytest.raises(mu.UploadError):
|
||||||
|
_parse([("날짜", "네이버", "모르는몰"), ("2026-10-10", 1, 2)]) # 반영할 열 없음
|
||||||
|
with pytest.raises(mu.UploadError):
|
||||||
|
mu.parse_workbook(b"not an xlsx", markets=MARKETS, today=TODAY)
|
||||||
|
res = _parse([("날짜", "쿠팡(로켓)", "coupang_rocket"), ("2026-10-10", 1, 2)])
|
||||||
|
assert any("두 번" in e for e in res.errors)
|
||||||
|
|
||||||
|
|
||||||
|
def test_sample_file_headers_match_marketplaces():
|
||||||
|
"""모듈 폴더 샘플 파일 머리글 = 수동 입력 쇼핑몰 이름(시드 기준) — 업로드하면 전부 반영 대상이어야 한다."""
|
||||||
|
sample = Path(mu.__file__).resolve().parent / "upload_sample.xlsx"
|
||||||
|
seed = [{"code": c, "name": n, "manual_input": True} for c, n in (
|
||||||
|
("coupang_rocket", "쿠팡(로켓)"), ("ohouse", "오늘의집"), ("gmarket", "G마켓"), ("kakao", "카카오"),
|
||||||
|
("gsshop", "GS샵"), ("lotteon", "롯데ON"), ("atomy", "애터미아자몰"))]
|
||||||
|
wb = openpyxl.load_workbook(sample)
|
||||||
|
ws = wb.active
|
||||||
|
ws.append([date(2026, 10, 1)] + [1] * 7)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
res = mu.parse_workbook(buf.getvalue(), markets=seed, today=TODAY)
|
||||||
|
assert not res.errors and not res.ignored and len(res.entries) == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_upload_endpoint_saves_or_rejects(monkeypatch):
|
||||||
|
"""라우터: 정상 파일은 한 번에 저장, 잘못된 칸이 있으면 400 + 칸 목록, 아무것도 저장 안 함. 샘플 받기."""
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
|
||||||
|
perf_router = importlib.import_module("app.modules.performance.router") # 패키지 속성 router 는 APIRouter
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
saved: list = []
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{**m, "enabled": True} for m in MARKETS]
|
||||||
|
|
||||||
|
def set_manual_sales_bulk(self, entries, *, user=""):
|
||||||
|
self.saved.extend(entries)
|
||||||
|
return len(entries)
|
||||||
|
|
||||||
|
store = Store()
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(perf_router, "today_kst", lambda: TODAY)
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
client = TestClient(app)
|
||||||
|
|
||||||
|
ok = _xlsx([("날짜", "쿠팡(로켓)", "토스"), ("2026-10-12", 1000, None), ("2026-10-13", None, 2000)])
|
||||||
|
r = client.post("/performance/api/manual-sales/upload", files={"file": ("a.xlsx", ok)})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
body = r.json()
|
||||||
|
assert body["saved"] == 2 and body["from"] == "2026-10-12" and body["to"] == "2026-10-13"
|
||||||
|
assert [s["code"] for s in body["by_shop"]] == ["coupang_rocket", "toss"]
|
||||||
|
assert sorted(store.saved) == [("coupang_rocket", date(2026, 10, 12), 1000), ("toss", date(2026, 10, 13), 2000)]
|
||||||
|
|
||||||
|
store.saved.clear()
|
||||||
|
bad = _xlsx([("날짜", "쿠팡(로켓)"), ("2026-10-12", 1000), ("2026-10-13", "x")])
|
||||||
|
r = client.post("/performance/api/manual-sales/upload", files={"file": ("b.xlsx", bad)})
|
||||||
|
assert r.status_code == 400 and r.json()["errors"] and store.saved == []
|
||||||
|
|
||||||
|
r = client.get("/performance/api/manual-sales/sample.xlsx")
|
||||||
|
assert r.status_code == 200 and r.content[:2] == b"PK"
|
||||||
@@ -0,0 +1,501 @@
|
|||||||
|
"""메타 광고 API 연동(2026-10-16) — 입력 검사·요청 매개변수·여러 계정 합산·쪽 넘김·구매 값·부가세·ROAS·오류 안내·저장 서비스.
|
||||||
|
메타 서버는 가짜(httpx MockTransport)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance import ad_spend, ad_sync
|
||||||
|
from app.modules.performance.ad_sources import meta_ads as ma
|
||||||
|
from app.modules.performance.ad_sources.registry import get_source
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError, AuthFailed, NotConfigured, TokenExpired
|
||||||
|
from app.modules.performance.credentials import CredentialService
|
||||||
|
|
||||||
|
TOKEN = "EAAGtesttoken0123456789abcdefSECRET"
|
||||||
|
|
||||||
|
|
||||||
|
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 set(self, key, value):
|
||||||
|
self.values[key] = value
|
||||||
|
|
||||||
|
def known_secrets(self):
|
||||||
|
return [v for k, v in self.values.items() if v and k in ("access_token", "app_secret")]
|
||||||
|
|
||||||
|
|
||||||
|
def _ctx(**over):
|
||||||
|
values = {"account_ids": "act_1111111111\n2222222222", "access_token": TOKEN}
|
||||||
|
values.update(over)
|
||||||
|
return AdapterContext(code="meta", credentials=Creds(values))
|
||||||
|
|
||||||
|
|
||||||
|
def _install(monkeypatch, handler):
|
||||||
|
"""가짜 메타 서버 — handler(request) 가 응답을 만든다. 보낸 요청을 돌려준다."""
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def route(request: httpx.Request) -> httpx.Response:
|
||||||
|
seen.append(request)
|
||||||
|
return handler(request)
|
||||||
|
|
||||||
|
monkeypatch.setattr(ma, "_http", lambda ctx: httpx.Client(transport=httpx.MockTransport(route)))
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
def _row(day, spend, **extra):
|
||||||
|
r = {"date_start": day, "date_stop": day, "account_currency": "KRW", "spend": spend}
|
||||||
|
r.update(extra)
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
# 계정 1: 두 쪽(paging.next), 계정 2: 한 쪽. 10-01 은 두 계정 모두 있음 → 날짜별 합산.
|
||||||
|
PAGE1 = {"data": [_row("2026-10-01", "100000", account_name="본계정", impressions="20000", clicks="400", inline_link_clicks="300",
|
||||||
|
actions=[{"action_type": "omni_purchase", "value": "10"}, {"action_type": "purchase", "value": "10"},
|
||||||
|
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "10"},
|
||||||
|
{"action_type": "link_click", "value": "300"}],
|
||||||
|
action_values=[{"action_type": "omni_purchase", "value": "450000"},
|
||||||
|
{"action_type": "purchase", "value": "450000"},
|
||||||
|
{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "450000"}])],
|
||||||
|
"paging": {"next": "https://graph.facebook.com/v26.0/act_1111111111/insights?after=CUR&access_token=" + TOKEN}}
|
||||||
|
PAGE2 = {"data": [_row("2026-10-02", "0", impressions="10")], "paging": {}}
|
||||||
|
ACC2 = {"data": [_row("2026-10-01", "50000.5", account_name="서브계정", impressions="5000", clicks="100", inline_link_clicks="80",
|
||||||
|
actions=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "2"}],
|
||||||
|
action_values=[{"action_type": "offsite_conversion.fb_pixel_purchase", "value": "150000"}])]}
|
||||||
|
|
||||||
|
|
||||||
|
def _insights_server(request: httpx.Request) -> httpx.Response:
|
||||||
|
path, q = request.url.path, request.url.params
|
||||||
|
if path == "/v26.0/act_1111111111/insights":
|
||||||
|
return httpx.Response(200, json=PAGE2 if q.get("after") == "CUR" else PAGE1)
|
||||||
|
if path == "/v26.0/act_2222222222/insights":
|
||||||
|
return httpx.Response(200, json=ACC2)
|
||||||
|
return httpx.Response(404, json={"error": {"message": "unknown path", "code": 100}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_registered_and_detail_channel():
|
||||||
|
assert get_source("meta").name == "메타 광고"
|
||||||
|
assert "meta" in ad_spend.DETAIL_CHANNELS and "meta" in ad_spend.FILE_ROAS # 머리글 → 일자별 표, ROAS 는 광고 쪽 값
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_account_ids():
|
||||||
|
assert ma.parse_account_ids("act_123456, 654321\n\nACT_123456;777777") == ["123456", "654321", "777777"]
|
||||||
|
assert ma.parse_account_ids("") == []
|
||||||
|
for bad in ("act_abc", "12-34", "act_"):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ma.parse_account_ids(bad)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
ma.parse_account_ids(",".join(str(100000 + i) for i in range(ma.MAX_ACCOUNTS + 1)))
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_credentials():
|
||||||
|
src = ma.MetaAdsSource()
|
||||||
|
ok = {"account_ids": "act_1111111111", "access_token": TOKEN}
|
||||||
|
assert src.validate_credentials(ok) == []
|
||||||
|
assert src.validate_credentials({**ok, "access_token": "__stored__"}) == []
|
||||||
|
assert {f.key for f in src.visible_fields()} == {"account_ids", "access_token", "app_secret", "api_version"}
|
||||||
|
assert {f.key for f in src.visible_fields() if f.secret} == {"access_token", "app_secret"}
|
||||||
|
errs = src.validate_credentials({"account_ids": "act_x", "access_token": "short token", "api_version": "26"})
|
||||||
|
assert len(errs) == 3 and not any("short token" in e for e in errs) # 토큰 값은 문구에 없음
|
||||||
|
assert "입력하세요" in " ".join(src.validate_credentials({}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_days_sums_accounts_pages_and_converts(monkeypatch):
|
||||||
|
seen = _install(monkeypatch, _insights_server)
|
||||||
|
days = ma.MetaAdsSource().fetch_days(_ctx(), date(2026, 10, 1), date(2026, 10, 2))
|
||||||
|
first = seen[0]
|
||||||
|
assert first.url.path == "/v26.0/act_1111111111/insights"
|
||||||
|
q = first.url.params
|
||||||
|
assert q["access_token"] == TOKEN and "appsecret_proof" not in q
|
||||||
|
assert (q["level"], q["time_increment"]) == ("account", "1")
|
||||||
|
assert json.loads(q["time_range"]) == {"since": "2026-10-01", "until": "2026-10-02"}
|
||||||
|
assert {"spend", "action_values", "actions", "account_currency", "date_start"} <= set(q["fields"].split(","))
|
||||||
|
assert [r.url.params.get("after") for r in seen] == [None, "CUR", None] # 계정 1 두 쪽 → 계정 2
|
||||||
|
d1, d2 = days
|
||||||
|
# 10-01: 지출 100,000 + 50,000.5 = 150,000.5 → 광고비 = 지출 그대로(메타는 부가세 포함, 2026-10-16) → 150,001
|
||||||
|
# 구매 전환값 = 계정1 omni_purchase 450,000(겹친 purchase·픽셀 값은 더하지 않음) + 계정2 픽셀 150,000 = 600,000
|
||||||
|
# ROAS = 600,000 ÷ 150,000.5 × 100 = 399.998... → 400.00
|
||||||
|
assert (d1.day, d1.amount, d1.roas) == (date(2026, 10, 1), 150001, Decimal("400.00"))
|
||||||
|
total_metrics = {k: v for k, v in d1.metrics.items() if k != "_accounts"}
|
||||||
|
assert total_metrics == {"지출 금액(부가세 포함)": 150001, "노출수": 25000, "클릭수": 500,
|
||||||
|
"클릭률(%)": 2.0, "링크 클릭": 380, "구매수": 12, "구매 전환값": 600000, "ROAS(%)": 400.0}
|
||||||
|
assert list(d1.metrics)[0] == "지출 금액(부가세 포함)" # 일자별 표 첫 열(× 1.1 없음 — 부가세 별도 열도 없음)
|
||||||
|
assert (d2.day, d2.amount, d2.roas, d2.metrics["클릭률(%)"]) == (date(2026, 10, 2), 0, None, 0.0) # 지출 0 → ROAS 없음
|
||||||
|
# 계정별(상세보기 탭, 2026-10-16) — 계정마다 따로 변환. 이름은 insights 의 account_name(없는 쪽은 같은 계정 앞 줄 이름)
|
||||||
|
a1, a2 = d1.metrics["_accounts"]["1111111111"], d1.metrics["_accounts"]["2222222222"]
|
||||||
|
assert (a1["name"], a1["amount"], a1["roas"]) == ("본계정", 100000, 450.0) # 지출 그대로, 450,000 ÷ 100,000
|
||||||
|
assert (a2["name"], a2["amount"], a2["roas"]) == ("서브계정", 50001, 300.0) # 50,000.5 → 50,001, 150,000 ÷ 50,000.5 = 299.997 → 300.00
|
||||||
|
assert a1["metrics"]["구매수"] == 10 and a2["metrics"]["구매 전환값"] == 150000 and a2["metrics"]["링크 클릭"] == 80
|
||||||
|
assert list(d2.metrics["_accounts"]) == ["1111111111"] and d2.metrics["_accounts"]["1111111111"]["name"] == "본계정"
|
||||||
|
assert "account_name" in seen[0].url.params["fields"].split(",")
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_secret_proof_and_version(monkeypatch):
|
||||||
|
seen = _install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
|
||||||
|
out = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333", app_secret="appsecret", api_version="v27.0"),
|
||||||
|
date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert out == []
|
||||||
|
assert seen[0].url.path == "/v27.0/act_333333/insights"
|
||||||
|
expected = hmac.new(b"appsecret", TOKEN.encode(), hashlib.sha256).hexdigest()
|
||||||
|
assert seen[0].url.params["appsecret_proof"] == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_limits(monkeypatch):
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": []}))
|
||||||
|
with pytest.raises(ApiError, match="366"):
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(), date(2025, 1, 1), date(2026, 10, 1))
|
||||||
|
with pytest.raises(NotConfigured):
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(access_token=""), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
# 다음 쪽 주소가 메타가 아니면 따라가지 않는다(토큰을 다른 곳에 보내지 않게)
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(200, json={"data": [], "paging": {"next": "https://evil.example/x"}}))
|
||||||
|
with pytest.raises(ApiError, match="다음 쪽"):
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("code,status,exc,hint", [
|
||||||
|
(190, 400, TokenExpired, "시스템 사용자"),
|
||||||
|
(200, 403, AuthFailed, "ads_read"),
|
||||||
|
(100, 400, ApiError, "광고 계정 ID"),
|
||||||
|
(17, 400, ApiError, "호출 한도"),
|
||||||
|
(80004, 403, ApiError, "호출 한도"), # 403 이어도 호출 한도는 인증 실패가 아님
|
||||||
|
])
|
||||||
|
def test_errors_are_explained(monkeypatch, code, status, exc, hint):
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(status, json={"error": {"message": "meta says no", "code": code}}))
|
||||||
|
with pytest.raises(exc) as info:
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert hint in str(info.value) and f"({code})" in str(info.value) and TOKEN not in str(info.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_network_error_has_no_token(monkeypatch):
|
||||||
|
def boom(req):
|
||||||
|
raise httpx.ConnectError("connect failed for " + str(req.url))
|
||||||
|
|
||||||
|
_install(monkeypatch, boom)
|
||||||
|
with pytest.raises(ApiError) as info:
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert "ConnectError" in str(info.value) and TOKEN not in str(info.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_message(monkeypatch):
|
||||||
|
accounts = {"/v26.0/act_1111111111": {"name": "본계정", "currency": "KRW", "timezone_name": "Asia/Seoul", "account_status": 1},
|
||||||
|
"/v26.0/act_2222222222": {"name": "해외", "currency": "USD", "timezone_name": "America/Los_Angeles", "account_status": 2}}
|
||||||
|
seen = _install(monkeypatch, lambda req: httpx.Response(200, json=accounts[req.url.path]))
|
||||||
|
msg = ma.MetaAdsSource().test_connection(_ctx())
|
||||||
|
assert "광고 계정 2개" in msg and "본계정(KRW·Asia/Seoul·운영 중)" in msg and "해외(USD" in msg and "사용 중지" in msg
|
||||||
|
assert "원화가 아닌 계정" in msg
|
||||||
|
assert seen[0].url.params["fields"] == "name,currency,timezone_name,account_status"
|
||||||
|
|
||||||
|
|
||||||
|
class FakeStore:
|
||||||
|
def __init__(self):
|
||||||
|
self.replaced, self.status = [], []
|
||||||
|
|
||||||
|
def replace_ad_api_range(self, code, start, end, days, *, user=""):
|
||||||
|
self.replaced.append((code, start, end, days, user))
|
||||||
|
return len(days)
|
||||||
|
|
||||||
|
def record_ad_status(self, code, *, status, ok, error="", kind="test"):
|
||||||
|
self.status.append((code, status, ok, error, kind))
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_service_end_to_end(monkeypatch):
|
||||||
|
"""실제 MetaAdsSource.fetch_days → AdSyncService 저장·상태. 실패 문구에서 토큰은 가린다."""
|
||||||
|
_install(monkeypatch, _insights_server)
|
||||||
|
store = FakeStore()
|
||||||
|
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||||||
|
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx()
|
||||||
|
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 2), user="king@x")
|
||||||
|
assert res["ok"] and res["days"] == 2 and res["total"] == 150001 and res["name"] == "메타 광고"
|
||||||
|
code, start, end, days, user = store.replaced[0]
|
||||||
|
assert (code, start, end, user) == ("meta", date(2026, 10, 1), date(2026, 10, 2), "king@x")
|
||||||
|
assert [(d, amt, roas) for d, amt, roas, _m in days] == [(date(2026, 10, 1), 150001, Decimal("400.00")),
|
||||||
|
(date(2026, 10, 2), 0, None)]
|
||||||
|
assert store.status[-1] == ("meta", "ok", True, "", "sync")
|
||||||
|
|
||||||
|
# 메타가 오류 문구에 토큰을 되돌려 줘도 저장·화면 문구에서는 가린다
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(400, json={"error": {"message": "bad token " + TOKEN, "code": 190}}))
|
||||||
|
res = svc.sync("meta", date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert not res["ok"] and res["status"] == "token_expired" and TOKEN not in res["message"]
|
||||||
|
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("token_expired", False) and TOKEN not in store.status[-1][3]
|
||||||
|
|
||||||
|
|
||||||
|
# ── 권한 오류(#200) 진단 — 연결 테스트가 메타에 토큰 정보를 물어 원인 하나를 짚는다(2026-10-16) ──
|
||||||
|
DENIED = {"error": {"message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission", "code": 200}}
|
||||||
|
|
||||||
|
|
||||||
|
def _diag_server(debug=None, perms=None, adaccounts=None):
|
||||||
|
"""debug/perms/adaccounts = 응답 dict, None 이면 그 조회도 실패(권한 오류)."""
|
||||||
|
def handler(req: httpx.Request) -> httpx.Response:
|
||||||
|
path = req.url.path
|
||||||
|
if path.endswith("/debug_token"):
|
||||||
|
assert req.url.params["input_token"] == TOKEN
|
||||||
|
return httpx.Response(200, json=debug) if debug is not None else httpx.Response(400, json=DENIED)
|
||||||
|
if path.endswith("/me/permissions"):
|
||||||
|
return httpx.Response(200, json=perms) if perms is not None else httpx.Response(400, json=DENIED)
|
||||||
|
if path.endswith("/me/adaccounts"):
|
||||||
|
return httpx.Response(200, json=adaccounts) if adaccounts is not None else httpx.Response(400, json=DENIED)
|
||||||
|
return httpx.Response(400, json=DENIED) # 광고 계정 조회 = 권한 오류
|
||||||
|
return handler
|
||||||
|
|
||||||
|
|
||||||
|
def _diag(monkeypatch, **server):
|
||||||
|
_install(monkeypatch, _diag_server(**server))
|
||||||
|
with pytest.raises(AuthFailed) as info:
|
||||||
|
ma.MetaAdsSource().test_connection(_ctx(account_ids="1111111111,2222222222"))
|
||||||
|
msg = str(info.value)
|
||||||
|
assert "(#200)" in msg and "[진단]" in msg and TOKEN not in msg
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def _debug(scopes, granular=None, exp=0):
|
||||||
|
return {"data": {"app_id": "777", "application": "DBX ERP", "is_valid": True, "expires_at": exp,
|
||||||
|
"scopes": scopes, "granular_scopes": granular or []}}
|
||||||
|
|
||||||
|
|
||||||
|
ALL_VISIBLE = {"data": [{"account_id": "1111111111"}, {"account_id": "2222222222"}]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_missing_ads_read(monkeypatch):
|
||||||
|
msg = _diag(monkeypatch, debug=_debug(["public_profile", "business_management"]), adaccounts=ALL_VISIBLE)
|
||||||
|
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg and "DBX ERP(777)" in msg and "만료 없음" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_account_not_assigned(monkeypatch):
|
||||||
|
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts={"data": [{"account_id": "1111111111"}]})
|
||||||
|
assert "광고 권한: ads_read" in msg and "보이는 광고 계정 1개" in msg
|
||||||
|
assert "배정되지 않은 계정: act_2222222222" in msg and "act_1111111111" not in msg.split("배정되지 않은 계정")[1].split("→")[0]
|
||||||
|
assert "자산 할당" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_scope_targets_other_accounts(monkeypatch):
|
||||||
|
granular = [{"scope": "ads_read", "target_ids": ["1111111111"]}]
|
||||||
|
msg = _diag(monkeypatch, debug=_debug(["ads_read"], granular), adaccounts=ALL_VISIBLE)
|
||||||
|
assert "다른 계정에만" in msg and "act_2222222222" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_points_to_app_when_token_and_accounts_ok(monkeypatch):
|
||||||
|
msg = _diag(monkeypatch, debug=_debug(["ads_read", "ads_management"]), adaccounts=ALL_VISIBLE)
|
||||||
|
assert "광고 권한: ads_management, ads_read" in msg and "앱 쪽 문제" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_falls_back_to_permissions(monkeypatch):
|
||||||
|
perms = {"data": [{"permission": "ads_read", "status": "declined"}, {"permission": "public_profile", "status": "granted"}]}
|
||||||
|
msg = _diag(monkeypatch, debug=None, perms=perms, adaccounts=None)
|
||||||
|
assert "광고 권한: 없음" in msg and "ads_read 권한이 없습니다" in msg # 거절(declined)은 받은 권한이 아님
|
||||||
|
|
||||||
|
|
||||||
|
def test_diagnose_unknown_when_meta_says_nothing(monkeypatch):
|
||||||
|
msg = _diag(monkeypatch, debug=None, perms=None, adaccounts=None)
|
||||||
|
assert "원인을 좁히지 못했습니다" in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_diag_hint_only_outside_connection_test(monkeypatch):
|
||||||
|
"""불러오기(fetch_days) 권한 오류엔 '연결 테스트가 진단' 안내, 연결 테스트 자체엔 그 안내 대신 진단 결과."""
|
||||||
|
_install(monkeypatch, _diag_server(debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE))
|
||||||
|
with pytest.raises(AuthFailed) as info:
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(account_ids="1111111111"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert ma._DIAG_HINT in str(info.value) and "[진단]" not in str(info.value)
|
||||||
|
msg = _diag(monkeypatch, debug=_debug(["ads_read"]), adaccounts=ALL_VISIBLE)
|
||||||
|
assert ma._DIAG_HINT not in msg
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_test_shows_full_diagnosis_first(monkeypatch):
|
||||||
|
"""설정 [연결 테스트](AdSyncService) 문구 — 진단이 맨 앞, 잘리지 않음, 메타 원문의 긴 주소는 뺌(2026-10-16 "[진…" 잘림)."""
|
||||||
|
long_denied = {"error": {"code": 200, "message": "(#200) Ad account owner has NOT grant ads_management or ads_read permission, "
|
||||||
|
"refer to https://developers.facebook.com/docs/marketing-api/get-started/authorization/"
|
||||||
|
"#permissions-and-features for details"}}
|
||||||
|
|
||||||
|
def handler(req):
|
||||||
|
if req.url.path.endswith("/debug_token"):
|
||||||
|
return httpx.Response(200, json=_debug(["ads_read"]))
|
||||||
|
if req.url.path.endswith("/me/adaccounts"):
|
||||||
|
return httpx.Response(200, json={"data": []})
|
||||||
|
return httpx.Response(400, json=long_denied)
|
||||||
|
|
||||||
|
_install(monkeypatch, handler)
|
||||||
|
store = FakeStore()
|
||||||
|
svc = ad_sync.AdSyncService(store, CredentialService(None, lambda: None))
|
||||||
|
svc._ctx = lambda code, values=None, user="", cleared=None: _ctx(account_ids="1111111111,2222222222")
|
||||||
|
res = svc.test_connection("meta")
|
||||||
|
msg = res["message"]
|
||||||
|
assert not res["ok"] and res["status"] == "auth_failed"
|
||||||
|
assert msg.startswith("[진단]") and not msg.endswith("…") and len(msg) > 300 # 예전 300자 한도면 잘렸을 길이
|
||||||
|
assert "배정되지 않은 계정: act_1111111111, act_2222222222" in msg and "자산 할당" in msg
|
||||||
|
assert "(메타 원문: 메타 API 오류(200): (#200) Ad account owner has NOT grant" in msg
|
||||||
|
assert "https://" not in msg and ma._DIAG_HINT not in msg and TOKEN not in msg
|
||||||
|
|
||||||
|
|
||||||
|
# ── 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
|
||||||
|
def _stored(day, amount, roas, metrics):
|
||||||
|
"""저장소 ad_details 행 모양."""
|
||||||
|
return {"date": day, "amount": amount, "roas": roas, "metrics": metrics, "source": "api"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_tabs_total_and_accounts():
|
||||||
|
def acc(name, amount, roas, spend_metric):
|
||||||
|
return {"name": name, "amount": amount, "roas": roas,
|
||||||
|
"metrics": {"지출 금액(부가세 포함)": amount, "노출수": spend_metric, "클릭수": spend_metric // 100, "클릭률(%)": 1.0,
|
||||||
|
"ROAS(%)": roas}}
|
||||||
|
rows = [
|
||||||
|
_stored("2026-10-01", 300, 200.0, {"지출 금액(부가세 포함)": 300, "노출수": 3000, "클릭수": 30, "클릭률(%)": 1.0, "ROAS(%)": 200.0,
|
||||||
|
"_accounts": {"1": acc("작은계정", 100, 100.0, 1000), "2": acc("큰계정", 200, 250.0, 2000)}}),
|
||||||
|
_stored("2026-10-02", 500, 300.0, {"지출 금액(부가세 포함)": 500, "노출수": 5000, "클릭수": 50, "클릭률(%)": 1.0, "ROAS(%)": 300.0,
|
||||||
|
"_accounts": {"2": acc("큰계정(새 이름)", 500, 300.0, 5000)}}),
|
||||||
|
_stored("2026-10-03", 70, None, {"지출 금액(부가세 포함)": 70}), # 계정별 저장 전에 가져온 날
|
||||||
|
]
|
||||||
|
t = ad_spend.detail_table(rows)
|
||||||
|
assert "_accounts" not in t["columns"] and "_accounts" not in t["total"] # "_" 키는 표 열·합계에 없음
|
||||||
|
assert all("_accounts" not in r["values"] for r in t["rows"]) # 화면으로도 보내지 않음
|
||||||
|
out = ad_spend.detail_tabs(rows)
|
||||||
|
tabs = out["tabs"]
|
||||||
|
assert [x["key"] for x in tabs] == ["total", "2", "1"] # 합계 → 광고비 큰 계정부터
|
||||||
|
assert [x["label"] for x in tabs] == ["합계", "큰계정(새 이름)", "작은계정"] # 이름 = 최근 날 이름
|
||||||
|
assert tabs[0]["total"] == t["total"] and len(tabs[0]["rows"]) == 3
|
||||||
|
big = tabs[1]
|
||||||
|
assert big["account_id"] == "2" and [r["date"] for r in big["rows"]] == ["2026-10-01", "2026-10-02"]
|
||||||
|
assert big["total"]["지출 금액(부가세 포함)"] == 700 and big["total"]["노출수"] == 7000
|
||||||
|
assert big["total"]["ROAS(%)"] == round((200 * 250 + 500 * 300) / 700, 2) # 광고비 가중 평균
|
||||||
|
assert [r["date"] for r in tabs[2]["rows"]] == ["2026-10-01"] # 광고를 낸 날만
|
||||||
|
assert out["accounts_missing"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_tabs_absent_without_accounts():
|
||||||
|
rows = [_stored("2026-10-01", 100, 150.0, {"지출 금액(부가세 포함)": 100, "ROAS(%)": 150.0})]
|
||||||
|
assert ad_spend.detail_tabs(rows) == {"tabs": [], "accounts_missing": 0} # 네이버·구글·옛 메타 자료 = 탭 없음
|
||||||
|
|
||||||
|
|
||||||
|
def test_details_endpoint_returns_tabs(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")
|
||||||
|
rows = [_stored("2026-10-01", 110, 450.0, {"지출 금액(부가세 포함)": 110, "_accounts": {
|
||||||
|
"1": {"name": "본계정", "amount": 110, "roas": 450.0, "metrics": {"지출 금액(부가세 포함)": 110}}}})]
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def ad_details(self, code, start, end):
|
||||||
|
assert code == "meta"
|
||||||
|
return rows
|
||||||
|
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request: (Store(), {"email": "a@x"}))
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
d = TestClient(app).get("/performance/api/ad-spend/meta/details?from=2026-10-01&to=2026-10-31").json()
|
||||||
|
assert d["columns"] == ["지출 금액(부가세 포함)"] and [t["label"] for t in d["tabs"]] == ["합계", "본계정"]
|
||||||
|
assert d["accounts_missing"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
# ── 외화(USD) 광고 계정 — 그날 환율로 원화 환산(2026-10-16) ──
|
||||||
|
from app.modules.performance import fx # noqa: E402
|
||||||
|
|
||||||
|
FX_ROWS = [{"date": "2026-10-01", "base": "USD", "quote": "KRW", "rate": 1350.0},
|
||||||
|
{"date": "2026-10-02", "base": "USD", "quote": "KRW", "rate": 1360.5}] # 10-03 은 없음 → 10-02 값
|
||||||
|
|
||||||
|
|
||||||
|
def _fx_and_meta(insights_by_account, fx_rows=FX_ROWS, fx_status=200):
|
||||||
|
calls = {"fx": []}
|
||||||
|
|
||||||
|
def handler(req: httpx.Request) -> httpx.Response:
|
||||||
|
if req.url.host == "api.frankfurter.dev":
|
||||||
|
calls["fx"].append(req)
|
||||||
|
return httpx.Response(fx_status, json=fx_rows if fx_status == 200 else {"status": fx_status, "message": "down"})
|
||||||
|
acc = req.url.path.split("/act_")[1].split("/")[0]
|
||||||
|
return httpx.Response(200, json={"data": insights_by_account.get(acc, [])})
|
||||||
|
return handler, calls
|
||||||
|
|
||||||
|
|
||||||
|
def _usd(day, spend, value, **extra):
|
||||||
|
return {**_row(day, spend, account_currency="USD", account_name="US 계정",
|
||||||
|
action_values=[{"action_type": "omni_purchase", "value": value}]), **extra}
|
||||||
|
|
||||||
|
|
||||||
|
def test_usd_account_converted_with_daily_rate(monkeypatch):
|
||||||
|
fx.clear_cache()
|
||||||
|
handler, calls = _fx_and_meta({
|
||||||
|
"333333": [_usd("2026-10-01", "100", "400"), _usd("2026-10-03", "10.5", "0")],
|
||||||
|
"444444": [_row("2026-10-01", "50000", account_name="원화 계정")],
|
||||||
|
})
|
||||||
|
_install(monkeypatch, handler)
|
||||||
|
d1, d3 = ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333,444444"), date(2026, 10, 1), date(2026, 10, 3))
|
||||||
|
q = calls["fx"][0].url.params
|
||||||
|
assert (q["base"], q["quotes"], q["to"]) == ("USD", "KRW", "2026-10-03") and q["from"] <= "2026-10-01"
|
||||||
|
assert len(calls["fx"]) == 1 # 통화마다 기간 한 번
|
||||||
|
# 10-01: USD 100 × 1,350 = 135,000원 + 원화 50,000 = 185,000 = 광고비(메타 지출은 부가세 포함 — × 1.1 없음)
|
||||||
|
# 구매 전환값 USD 400 × 1,350 = 540,000 → ROAS = 540,000 ÷ 185,000 = 291.89%
|
||||||
|
assert (d1.amount, d1.roas) == (185000, Decimal("291.89"))
|
||||||
|
assert d1.metrics["지출 금액(부가세 포함)"] == 185000 and d1.metrics["구매 전환값"] == 540000
|
||||||
|
us = d1.metrics["_accounts"]["333333"]
|
||||||
|
assert (us["amount"], us["roas"]) == (135000, 400.0) # 100 × 1,350, ROAS 는 환율과 무관(400 ÷ 100)
|
||||||
|
assert us["metrics"]["지출 금액(USD)"] == 100.0 and us["metrics"]["적용 환율(원)"] == 1350.0
|
||||||
|
assert "적용 환율(원)" not in d1.metrics["_accounts"]["444444"]["metrics"] # 원화 계정엔 없음
|
||||||
|
assert "적용 환율(원)" not in d1.metrics # 합계 표에도 없음
|
||||||
|
# 10-03: 그날 환율 없음 → 10-02 값(1,360.5). 10.5 × 1,360.5 = 14,285.25 → 14,285
|
||||||
|
assert d3.day == date(2026, 10, 3) and d3.amount == 14285
|
||||||
|
assert d3.metrics["_accounts"]["333333"]["metrics"]["적용 환율(원)"] == 1360.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_usd_rate_unavailable_saves_nothing(monkeypatch):
|
||||||
|
fx.clear_cache()
|
||||||
|
handler, _calls = _fx_and_meta({"333333": [_usd("2026-10-01", "100", "0")]}, fx_status=503)
|
||||||
|
_install(monkeypatch, handler)
|
||||||
|
with pytest.raises(ApiError) as info:
|
||||||
|
ma.MetaAdsSource().fetch_days(_ctx(account_ids="333333"), date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
assert "USD 광고 계정을 원화로 바꿀 환율" in str(info.value) and "503" in str(info.value) and TOKEN not in str(info.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_krw_rates_fill_cache_and_errors():
|
||||||
|
fx.clear_cache()
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
def route(req):
|
||||||
|
seen.append(req)
|
||||||
|
return httpx.Response(200, json=FX_ROWS + [{"date": "x", "quote": "KRW", "rate": 1}, {"date": "2026-10-02", "quote": "JPY", "rate": 9}])
|
||||||
|
|
||||||
|
client = httpx.Client(transport=httpx.MockTransport(route))
|
||||||
|
rates = fx.krw_rates(client, "usd", date(2026, 10, 1), date(2026, 10, 4), today=date(2026, 10, 10))
|
||||||
|
assert rates == {date(2026, 10, 1): Decimal("1350.0"), date(2026, 10, 2): Decimal("1360.5"),
|
||||||
|
date(2026, 10, 3): Decimal("1360.5"), date(2026, 10, 4): Decimal("1360.5")} # 빈 날 = 앞 날 값
|
||||||
|
# 실제로 고시된 지난 날(10-01·10-02)만 기억 — 그 두 날만 다시 물으면 서버에 묻지 않는다
|
||||||
|
assert fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 2), today=date(2026, 10, 10))[date(2026, 10, 2)] == Decimal("1360.5")
|
||||||
|
assert len(seen) == 1
|
||||||
|
fx.krw_rates(client, "USD", date(2026, 10, 1), date(2026, 10, 3), today=date(2026, 10, 10)) # 10-03 은 앞 날 값이라 기억 안 함
|
||||||
|
assert len(seen) == 2
|
||||||
|
assert fx.krw_rates(client, "KRW", date(2026, 10, 1), date(2026, 10, 2)) == {date(2026, 10, 1): 1, date(2026, 10, 2): 1}
|
||||||
|
with pytest.raises(fx.FxError, match="찾지 못했습니다"): # 앞 열흘에도 없음
|
||||||
|
fx.krw_rates(client, "USD", date(2026, 11, 1), date(2026, 11, 1), today=date(2026, 11, 5))
|
||||||
|
|
||||||
|
def down(req):
|
||||||
|
raise httpx.ConnectError("boom")
|
||||||
|
with pytest.raises(fx.FxError, match="ConnectError"):
|
||||||
|
fx.krw_rates(httpx.Client(transport=httpx.MockTransport(down)), "EUR", date(2026, 10, 1), date(2026, 10, 1))
|
||||||
|
|
||||||
|
|
||||||
|
def test_detail_table_rate_total_is_weighted_average():
|
||||||
|
rows = [_stored("2026-10-01", 1000, None, {"적용 환율(원)": 1300.0}),
|
||||||
|
_stored("2026-10-02", 3000, None, {"적용 환율(원)": 1400.0}),
|
||||||
|
_stored("2026-10-03", 0, None, {"적용 환율(원)": 9999.0})] # 광고비 0 인 날은 빼고
|
||||||
|
assert ad_spend.detail_table(rows)["total"]["적용 환율(원)"] == 1375.0 # (1300×1000 + 1400×3000) ÷ 4000
|
||||||
|
|
||||||
|
|
||||||
|
def test_connection_mentions_conversion(monkeypatch):
|
||||||
|
_install(monkeypatch, lambda req: httpx.Response(200, json={"name": "US", "currency": "USD", "timezone_name": "America/Los_Angeles",
|
||||||
|
"account_status": 1}))
|
||||||
|
msg = ma.MetaAdsSource().test_connection(_ctx(account_ids="333333"))
|
||||||
|
assert "그날 환율로 원화로 바꿔 넣습니다" in msg and "가져올 수 없습니다" not in msg
|
||||||
@@ -596,6 +596,8 @@ def test_toss_reconcile_hides_personal():
|
|||||||
|
|
||||||
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
|
||||||
access_token_expires_at=str(int(_t.time()) + 99999)))
|
access_token_expires_at=str(int(_t.time()) + 99999)))
|
||||||
|
from app.modules.performance.adapters import toss as _toss # 지금 인증정보로 받은 토큰(검토 F04 — 지문이 같아야 재사용)
|
||||||
|
ctx.credentials.set("access_token_for", _toss.credential_fingerprint(ctx.credentials, _toss.TOKEN_KEYS))
|
||||||
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
|
||||||
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
|
||||||
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
steps = [_toss_step("REFUND", 2, 21, "2026-09-10T11:00:00", -9900), _toss_step("REFUND", 2, None, "2026-09-10T11:00:00", -3000)]
|
||||||
@@ -1064,15 +1066,18 @@ def test_coupang_hmac_and_connection_errors():
|
|||||||
seen = {}
|
seen = {}
|
||||||
|
|
||||||
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
def fake_get(url, headers=None, timeout=None, status=200, body=None):
|
||||||
|
seen.setdefault("urls", []).append(url)
|
||||||
seen["url"], seen["auth"] = url, headers["Authorization"]
|
seen["url"], seen["auth"] = url, headers["Authorization"]
|
||||||
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []})
|
||||||
|
|
||||||
orig = httpx.get
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
try:
|
try:
|
||||||
httpx.get = fake_get
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = fake_get, 0, 0
|
||||||
msg = cp.CoupangAdapter().test_connection(ctx)
|
msg = cp.CoupangAdapter().test_connection(ctx)
|
||||||
assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"]
|
first, rg = seen["urls"]
|
||||||
assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"]
|
assert "연결 정상" in msg and "로켓그로스" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in first
|
||||||
|
assert "%2B09:00" in first and "SK-SECRET" not in seen["auth"]
|
||||||
|
assert "/rg_open_api/apis/api/v1/vendors/A00012345/rg/orders?paidDateFrom=" in rg
|
||||||
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"})
|
||||||
try:
|
try:
|
||||||
cp.CoupangAdapter().test_connection(ctx)
|
cp.CoupangAdapter().test_connection(ctx)
|
||||||
@@ -1081,7 +1086,158 @@ def test_coupang_hmac_and_connection_errors():
|
|||||||
else:
|
else:
|
||||||
raise AssertionError("403 이면 인증 실패여야 합니다")
|
raise AssertionError("403 이면 인증 실패여야 합니다")
|
||||||
finally:
|
finally:
|
||||||
httpx.get = orig
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_sheet(order_id, box, paid, items, *, status="INSTRUCT", ship=3000):
|
||||||
|
def money(n):
|
||||||
|
return {"currencyCode": "KRW", "units": n, "nanos": 0}
|
||||||
|
|
||||||
|
return {"shipmentBoxId": box, "orderId": order_id, "orderedAt": paid, "paidAt": paid, "status": status,
|
||||||
|
"orderer": {"name": "홍길동", "safeNumber": "0502-1111-2222"},
|
||||||
|
"receiver": {"name": "홍길동", "addr1": "서울 비밀구 1", "receiverNumber": "+82-10-1234-5678"},
|
||||||
|
"parcelPrintMessage": "문 앞", "shippingPrice": money(ship), "remotePrice": money(0),
|
||||||
|
"orderItems": [{"sequenceNo": f"{i + 1:03d}", "vendorItemId": 100 + i, "vendorItemName": n,
|
||||||
|
"sellerProductName": n, "sellerProductItemName": "1개", "shippingCount": q,
|
||||||
|
"salesPrice": money(p), "orderPrice": money(p * q), "discountPrice": money(dc),
|
||||||
|
"cancelCount": cc, "holdCountForCancel": 0, "canceled": cc >= q,
|
||||||
|
"etcInfoValues": ["개인 메모"]}
|
||||||
|
for i, (n, p, q, dc, cc) in enumerate(items)]}
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_rg(order_id, paid_ms, items):
|
||||||
|
return {"vendorId": "A00012345", "orderId": order_id, "paidAt": paid_ms,
|
||||||
|
"orderItems": [{"vendorItemId": 900 + i, "productName": n, "salesQuantity": q, "unitSalesPrice": str(p),
|
||||||
|
"currency": "KRW"} for i, (n, p, q) in enumerate(items)]}
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_server(sheets_by_status, rg_pages):
|
||||||
|
"""가짜 쿠팡 — 발주서는 상태별 목록(2쪽까지), 로켓그로스는 nextToken 쪽 넘김. 호출 기록을 남긴다."""
|
||||||
|
import httpx
|
||||||
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, headers=None, timeout=None):
|
||||||
|
u = urlparse(url)
|
||||||
|
q = {k: v[0] for k, v in parse_qs(u.query).items()}
|
||||||
|
calls.append((u.path, q))
|
||||||
|
if u.path.endswith("/rg/orders"):
|
||||||
|
i = int(q.get("nextToken") or 0)
|
||||||
|
nxt = str(i + 1) if i + 1 < len(rg_pages) else ""
|
||||||
|
return httpx.Response(200, json={"code": 200, "message": "SUCCESS", "data": rg_pages[i], "nextToken": nxt})
|
||||||
|
rows = sheets_by_status.get(q["status"], [])
|
||||||
|
if q.get("nextToken") == "p2":
|
||||||
|
return httpx.Response(200, json={"code": 200, "data": rows[1:], "nextToken": ""})
|
||||||
|
return httpx.Response(200, json={"code": 200, "data": rows[:1], "nextToken": "p2" if len(rows) > 1 else ""})
|
||||||
|
|
||||||
|
return get, calls
|
||||||
|
|
||||||
|
|
||||||
|
KST_1012_0030_MS = 1791732600000 # 2026-10-12 00:30 KST = 10-11 15:30 UTC
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_collect_sales():
|
||||||
|
"""쿠팡 매출 = 판매자배송 발주서 orderPrice(쿠폰 할인 전) + 로켓그로스 단가 × 수량, 결제일(한국 시간) 기준.
|
||||||
|
상태 6개 모두 조회·쪽 넘김, 결제일이 기간 밖이면 뺌, 결제 뒤 취소된 줄도 결제일 매출, 같은 발주서 두 번 와도 한 번.
|
||||||
|
구매자·수령자 정보는 저장하지 않는다."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
|
||||||
|
sheets = {
|
||||||
|
"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0), ("뚜껑", 3000, 1, 0, 0)]),
|
||||||
|
_cp_sheet(2, 21, "2026-10-12T23:59:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])], # 결제 뒤 취소
|
||||||
|
"FINAL_DELIVERY": [_cp_sheet(3, 31, "2026-10-11T23:50:00+09:00", [("밀폐용기", 12000, 1, 0, 0)]), # 전날 결제 — 뺌
|
||||||
|
_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)])], # 같은 발주서 다시
|
||||||
|
}
|
||||||
|
rg_pages = [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])], [_cp_rg(71, KST_1012_0030_MS + 3600_000, [("컵", 5000, 1)])]]
|
||||||
|
get, calls = _cp_server(sheets, rg_pages)
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "coupang"),
|
||||||
|
{"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-SECRET"})
|
||||||
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||||
|
finally:
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
assert r["ok"], r
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "coupang"}
|
||||||
|
assert set(ev_) == {"coupang:1", "coupang:2", "coupang:rg:70", "coupang:rg:71"}, set(ev_)
|
||||||
|
assert ev_["coupang:1"]["amount"] == 24000 + 3000 and ev_["coupang:1"]["quantity"] == 3 # 배송비 제외, 중복 없음
|
||||||
|
assert ev_["coupang:1"]["discount_amount"] == 1000 and ev_["coupang:1"]["product_name"] == "밀폐용기 외 1건"
|
||||||
|
assert ev_["coupang:2"]["amount"] == 12000 and "취소" in ev_["coupang:2"]["order_status"]
|
||||||
|
assert ev_["coupang:rg:70"]["amount"] == 29700 and ev_["coupang:rg:70"]["sales_date"] == date(2026, 10, 12)
|
||||||
|
assert ev_["coupang:rg:71"]["amount"] == 5000 # 다음 쪽(nextToken)
|
||||||
|
assert {q["status"] for p, q in calls if p.endswith("/ordersheets")} == set(cp.STATUSES)
|
||||||
|
sheet_q = next(q for p, q in calls if p.endswith("/ordersheets"))
|
||||||
|
assert sheet_q["createdAtFrom"] == "2026-10-11+09:00" and sheet_q["createdAtTo"] == "2026-10-12+09:00" # 주문일 하루 앞부터
|
||||||
|
assert any(q.get("nextToken") == "p2" and q["status"] == "INSTRUCT" for p, q in calls if p.endswith("/ordersheets"))
|
||||||
|
rg_q = next(q for p, q in calls if p.endswith("/rg/orders"))
|
||||||
|
assert rg_q["paidDateFrom"] == "20261012" and rg_q["paidDateTo"] == "20261012"
|
||||||
|
assert "홍길동" not in repr(st.events) and "비밀구" not in repr(st.events) and "1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_spans_and_money():
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
|
||||||
|
assert cp.spans(date(2026, 1, 1), date(2026, 3, 5), 31) == [
|
||||||
|
(date(2026, 1, 1), date(2026, 1, 31)), (date(2026, 2, 1), date(2026, 3, 3)), (date(2026, 3, 4), date(2026, 3, 5))]
|
||||||
|
assert cp._won({"units": 15000, "nanos": 0}) == 15000 and cp._won("27,800") == 27800 and cp._won(None) == 0
|
||||||
|
assert cp._kst_day("2026-10-12T00:10:00+09:00") == date(2026, 10, 12)
|
||||||
|
assert cp._kst_day("2026-10-11T15:10:00Z") == date(2026, 10, 12) # UTC → 한국 날짜
|
||||||
|
assert cp._kst_day(KST_1012_0030_MS) == date(2026, 10, 12)
|
||||||
|
assert cp._kst_day("2026-10-12") == date(2026, 10, 12) and cp._kst_day("") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_coupang_reconcile_candidates_hide_personal():
|
||||||
|
"""원본 데이터 확인 — 날짜별 후보 금액(할인 전·후, 취소분 뺀 값, 로켓그로스)·판매량, 개인정보 항목은 아예 없음.
|
||||||
|
로켓그로스만 실패해도 판매자배송 결과는 보여 준다."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
class Creds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||||
|
sheets = {"INSTRUCT": [_cp_sheet(1, 11, "2026-10-12T09:10:00+09:00", [("밀폐용기", 12000, 2, 1000, 0)]),
|
||||||
|
_cp_sheet(2, 21, "2026-10-13T10:00:00+09:00", [("밀폐용기", 12000, 1, 0, 1)])]}
|
||||||
|
get, _calls = _cp_server(sheets, [[_cp_rg(70, KST_1012_0030_MS, [("물병", 9900, 3)])]])
|
||||||
|
orig = (httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC)
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = get, 0, 0
|
||||||
|
try:
|
||||||
|
rec = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12), to=date(2026, 10, 13))
|
||||||
|
cands = {c["label"][:1]: c for c in rec["refund_candidates"]}
|
||||||
|
assert cands["①"]["days"] == {"2026-10-12": 24000 + 29700, "2026-10-13": 12000}
|
||||||
|
assert cands["②"]["days"]["2026-10-12"] == 24000 and cands["③"]["days"]["2026-10-12"] == 23000
|
||||||
|
assert cands["④"]["days"]["2026-10-13"] == 0 and cands["⑤"]["days"]["2026-10-12"] == 29700
|
||||||
|
assert next(c for c in rec["refund_candidates"] if c["label"].startswith("판매량"))["days"]["2026-10-12"] == 5
|
||||||
|
assert rec["days"][0] == {"date": "2026-10-12", "orders": 2, "amount": 53700, "claimed": 0, "ship": 3000}
|
||||||
|
assert rec["days"][1]["claimed"] == 12000 and rec["candidates_title"]
|
||||||
|
names = {f["name"] for p in rec["probes"] if p["ok"] for f in p["fields"]}
|
||||||
|
assert "orderItems.orderPrice.units" in names and not any(n.startswith(("orderer", "receiver")) for n in names)
|
||||||
|
assert "홍길동" not in repr(rec) and "비밀구" not in repr(rec) and "개인 메모" not in repr(rec) and "문 앞" not in repr(rec)
|
||||||
|
|
||||||
|
def deny_rg(url, headers=None, timeout=None): # 로켓그로스만 거부(403)
|
||||||
|
if "/rg/orders" in url:
|
||||||
|
return httpx.Response(403, json={"message": "Access Denied"})
|
||||||
|
return get(url, headers, timeout)
|
||||||
|
|
||||||
|
httpx.get = deny_rg
|
||||||
|
rec2 = cp.CoupangAdapter().reconcile(ctx, date(2026, 10, 12))
|
||||||
|
p = {x["key"]: x for x in rec2["probes"]}
|
||||||
|
assert p["seller"]["ok"] and not p["rg"]["ok"] and "403" in p["rg"]["error"]
|
||||||
|
assert rec2["refund_candidates"][0]["error"] and rec2["refund_candidates"][1]["days"]["2026-10-12"] == 24000
|
||||||
|
finally:
|
||||||
|
httpx.get, cp.CALL_INTERVAL_SEC, cp.RG_CALL_INTERVAL_SEC = orig
|
||||||
|
|
||||||
|
|
||||||
def test_elevenst_connection():
|
def test_elevenst_connection():
|
||||||
@@ -1224,10 +1380,15 @@ def test_elevenst_collect_sales():
|
|||||||
|
|
||||||
def test_registry_and_event_validation():
|
def test_registry_and_event_validation():
|
||||||
codes = [a.code for a in all_adapters()]
|
codes = [a.code for a in all_adapters()]
|
||||||
assert len(codes) == len(set(codes)) == 10
|
assert len(codes) == len(set(codes)) == 12
|
||||||
|
assert codes == ["cafe24", "naver", "coupang", "coupang_rocket", "ohouse", "gmarket", "kakao",
|
||||||
|
"gsshop", "elevenst", "lotteon", "toss", "atomy"]
|
||||||
for a in all_adapters():
|
for a in all_adapters():
|
||||||
keys = [f.key for f in a.credential_fields()]
|
keys = [f.key for f in a.credential_fields()]
|
||||||
assert len(keys) == len(set(keys)), a.code
|
assert len(keys) == len(set(keys)), a.code
|
||||||
|
if a.manual_only: # 수동 입력 전용 — 인증 항목 없음
|
||||||
|
assert not keys and not a.implemented, a.code
|
||||||
|
continue
|
||||||
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
assert a.uses_shared_integration or any(f.secret for f in a.visible_fields()), a.code
|
||||||
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
for bad in (SaleEvent("SALE", "x", "o", date.today(), -1), SaleEvent("CANCEL", "x", "o", date.today(), 5),
|
||||||
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
SaleEvent("SALE", "x", "o", date.today(), 1.5), SaleEvent("BOGUS", "x", "o", date.today(), 1)):
|
||||||
@@ -1399,6 +1560,8 @@ def test_naver_reconcile_hides_personal():
|
|||||||
import time as _t
|
import time as _t
|
||||||
ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T",
|
ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T",
|
||||||
access_token_expires_at=str(int(_t.time()) + 9999)))
|
access_token_expires_at=str(int(_t.time()) + 9999)))
|
||||||
|
# 저장된 토큰은 발급한 인증정보 지문과 같을 때만 다시 쓴다(검토 F04) — 지금 인증정보로 받은 토큰으로
|
||||||
|
ctx.credentials.set("access_token_for", nv.credential_fingerprint(ctx.credentials, nv.TOKEN_KEYS))
|
||||||
rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")]
|
rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")]
|
||||||
orig = (httpx.get, nv.CALL_INTERVAL_SEC)
|
orig = (httpx.get, nv.CALL_INTERVAL_SEC)
|
||||||
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
|
||||||
@@ -1613,6 +1776,158 @@ def test_gsshop_collect_sales():
|
|||||||
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
|
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
|
||||||
|
|
||||||
|
|
||||||
|
def _kakao_detail(oid, pid, paid, price, qty=1, opt=0, sdc=0, cdc=0, adc=0, ship=3000, status="ShippingProgress"):
|
||||||
|
return {"id": oid,
|
||||||
|
"orderBase": {"id": oid, "paymentId": pid, "status": status, "createdAt": paid, "paidAt": paid,
|
||||||
|
"modifiedAt": paid},
|
||||||
|
"orderer": {"phoneNumber": "010-1234-5678"},
|
||||||
|
"orderProduct": {"id": oid, "name": "미라클통", "optionContent": "3200ml", "quantity": qty,
|
||||||
|
"productPrice": price, "optionPrice": opt, "sellerDiscountPrice": sdc,
|
||||||
|
"sellerCouponDiscountPrice": cdc, "adminDiscountPrice": adc, "deliveryAmount": ship,
|
||||||
|
"areaAdditionalDeliveryAmount": 0},
|
||||||
|
"orderDeliveryRequest": {"receiverName": "홍길동", "receiverAddress1": "서울 반품동", "requirement": "문 앞"},
|
||||||
|
"orderClaimReturn": {"claimItemStatus": "RETURN_COMPLETE", "pickupName": "홍길동", "reasonComment": "변심"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_kakao_connection_headers_and_errors():
|
||||||
|
"""카카오: kapi.kakao.com + Authorization(앱 어드민 키)·Target-Authorization(판매자 인증키)·channel-ids 헤더.
|
||||||
|
-2(두 키가 같은 앱)·-401(판매자 키 무효)·403 은 인증 실패, 키 값은 메시지에 없음."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import kakao as kk
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, NotConfigured
|
||||||
|
|
||||||
|
class Creds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
ctx = AdapterContext(code="kakao", credentials=Creds(admin_key="ADMIN-SECRET", api_key="SELLER-SECRET"))
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def ok(url, params=None, headers=None, timeout=None):
|
||||||
|
seen.update(url=url, params=params, headers=headers)
|
||||||
|
return httpx.Response(200, json={"contents": [{"orderId": 1, "paymentId": 9, "orderStatus": "PayComplete"}]})
|
||||||
|
|
||||||
|
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||||
|
kk.CALL_INTERVAL_SEC = 0
|
||||||
|
try:
|
||||||
|
httpx.get = ok
|
||||||
|
msg = kk.KakaoAdapter().test_connection(ctx)
|
||||||
|
assert "연결 정상" in msg and "1건" in msg
|
||||||
|
assert seen["url"] == "https://kapi.kakao.com/v2/shopping/orders/paidAt"
|
||||||
|
assert seen["headers"]["Authorization"] == "KakaoAK ADMIN-SECRET"
|
||||||
|
assert seen["headers"]["Target-Authorization"] == "KakaoAK SELLER-SECRET"
|
||||||
|
assert seen["headers"]["channel-ids"] == "101" # 기본 톡스토어
|
||||||
|
assert seen["params"]["from"].endswith(" 00:00:00") and seen["params"]["to"].endswith(" 23:59:59")
|
||||||
|
ctx2 = AdapterContext(code="kakao", credentials=Creds(admin_key="A", api_key="S", channel_ids=" 1, 101 "))
|
||||||
|
kk.KakaoAdapter().test_connection(ctx2)
|
||||||
|
assert seen["headers"]["channel-ids"] == "1,101"
|
||||||
|
for status, body, kind, word in (
|
||||||
|
(401, {"msg": "invalid authorization or target-authorization header.", "code": -2}, AuthFailed, "서로 다른 앱"),
|
||||||
|
(401, {"msg": "appKey(판매자인증키) is already deactivated", "code": -401}, AuthFailed, "판매자 API 인증키"),
|
||||||
|
(400, {"code": -800, "msg": "대행사 매핑/권한 확인이 필요합니다."}, AuthFailed, "연결되지 않았습니다"),
|
||||||
|
(403, {"code": -3, "msg": "forbidden"}, AuthFailed, "403"),
|
||||||
|
(500, {"code": -500, "msg": "internal"}, ApiError, "500")):
|
||||||
|
httpx.get = (lambda s, b: lambda url, params=None, headers=None, timeout=None: httpx.Response(s, json=b))(status, body)
|
||||||
|
try:
|
||||||
|
kk.KakaoAdapter().test_connection(ctx)
|
||||||
|
except kind as exc:
|
||||||
|
assert word in exc.message and "ADMIN-SECRET" not in exc.message and "SELLER-SECRET" not in exc.message
|
||||||
|
else:
|
||||||
|
raise AssertionError("오류여야 합니다")
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
try:
|
||||||
|
kk.KakaoAdapter().test_connection(AdapterContext(code="kakao", credentials=Creds(api_key="S")))
|
||||||
|
except NotConfigured:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("어드민 키 없으면 미설정")
|
||||||
|
|
||||||
|
|
||||||
|
def test_kakao_collect_sales():
|
||||||
|
"""카카오 매출 = 결제(paymentId) 하나, 결제일 기준, (상품가+옵션가)×수량 − 할인들, 배송비 제외.
|
||||||
|
목록(paidAt, token 으로 다음 쪽) → 주문정보(order_id). 미결제는 빼고 결제 뒤 취소는 포함. 개인정보 미저장."""
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import kakao as kk
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext
|
||||||
|
|
||||||
|
details = {
|
||||||
|
11: _kakao_detail(11, 900, "20261001101500", 10000, qty=2, opt=1000, sdc=500, cdc=1000, adc=500), # 22000-2000
|
||||||
|
12: _kakao_detail(12, 900, "20261001101500", 5000), # 같은 결제
|
||||||
|
13: _kakao_detail(13, 901, "20261001200000", 7000, status="PayCancelComplete"), # 결제 뒤 취소
|
||||||
|
15: _kakao_detail(15, 903, "20261002090000", 3000),
|
||||||
|
}
|
||||||
|
rows = {
|
||||||
|
"2026-10-01": [[{"orderId": 11, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||||
|
"modifiedAt": "20261001110000"},
|
||||||
|
{"orderId": 12, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
|
||||||
|
"modifiedAt": "20261001110000"}],
|
||||||
|
[{"orderId": 13, "paymentId": 901, "orderStatus": "PayCancelComplete", "paidAt": "20261001200000",
|
||||||
|
"modifiedAt": "20261001210000"},
|
||||||
|
{"orderId": 14, "paymentId": 902, "orderStatus": "PayWaiting", "paidAt": "",
|
||||||
|
"modifiedAt": "20261001210000"}]],
|
||||||
|
"2026-10-02": [[{"orderId": 15, "paymentId": 903, "orderStatus": "BuyDecision", "paidAt": "20261002090000",
|
||||||
|
"modifiedAt": "20261002090000"}]],
|
||||||
|
}
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, params=None, headers=None, timeout=None):
|
||||||
|
calls.append((url.rsplit("/", 1)[-1], dict(params)))
|
||||||
|
if url.endswith("/v1/shopping/order"):
|
||||||
|
return httpx.Response(200, json=details[int(params["order_id"])])
|
||||||
|
pages = rows.get(params["from"][:10], [[]])
|
||||||
|
i = int(params.get("token") or 0)
|
||||||
|
body = {"contents": pages[i]}
|
||||||
|
if i + 1 < len(pages):
|
||||||
|
body["token"] = str(i + 1)
|
||||||
|
return httpx.Response(200, json=body)
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(next(a for a in all_adapters() if a.code == "kakao"), {"admin_key": "ADMIN", "api_key": "SELLER"})
|
||||||
|
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
r = SyncService(st, creds).sync_marketplace("kakao", date(2026, 10, 1), date(2026, 10, 2))
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
assert r["ok"], r
|
||||||
|
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "kakao"}
|
||||||
|
assert set(ev_) == {"kakao:900", "kakao:901", "kakao:903"} # 미결제 902 제외
|
||||||
|
a = ev_["kakao:900"]
|
||||||
|
assert a["amount"] == (10000 + 1000) * 2 - 2000 + 5000 and a["sales_date"] == date(2026, 10, 1)
|
||||||
|
assert a["discount_amount"] == 2000 and a["quantity"] == 3 and a["product_name"] == "미라클통"
|
||||||
|
assert ev_["kakao:901"]["amount"] == 7000 # 결제 뒤 취소도 결제일 매출(네이버와 같은 기준)
|
||||||
|
assert ev_["kakao:903"]["sales_date"] == date(2026, 10, 2)
|
||||||
|
assert not any(c[0] == "order" and c[1]["order_id"] == "14" for c in calls) # 미결제는 주문정보도 안 부름
|
||||||
|
assert [c[1].get("token") for c in calls if c[0] == "paidAt"] == [None, "1", None] # 다음 쪽 token
|
||||||
|
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
|
||||||
|
|
||||||
|
# 원본 데이터 확인 — 개인정보는 값 없이 이름만, 날짜별 현재 규칙 매출
|
||||||
|
ad = kk.KakaoAdapter()
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
|
||||||
|
try:
|
||||||
|
rec = ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1),
|
||||||
|
to=date(2026, 10, 2))
|
||||||
|
n = len(calls)
|
||||||
|
ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1))
|
||||||
|
assert not [c for c in calls[n:] if c[0] == "order"] # 수정일이 같으면 주문정보 캐시
|
||||||
|
finally:
|
||||||
|
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
|
||||||
|
assert rec["days"][0] == {"date": "2026-10-01", "orders": 2, "amount": 25000 + 7000, "claimed": 7000, "ship": 9000}
|
||||||
|
assert rec["days"][1]["amount"] == 3000
|
||||||
|
f = {x["name"]: x for x in rec["probes"][0]["fields"]}
|
||||||
|
assert f["orderProduct.productPrice"]["sum"] == 10000 + 5000 + 7000 + 3000
|
||||||
|
assert f["orderDeliveryRequest.receiverName"]["sample"] == "" and f["orderer.phoneNumber"]["sample"] == ""
|
||||||
|
assert "홍길동" not in repr(rec) and "반품동" not in repr(rec) and "010-1234-5678" not in repr(rec)
|
||||||
|
assert "변심" not in repr(rec) and "문 앞" not in repr(rec)
|
||||||
|
|
||||||
|
|
||||||
def test_sync_job_cancel():
|
def test_sync_job_cancel():
|
||||||
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
|
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
|
||||||
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
|
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
|
||||||
@@ -1720,6 +2035,21 @@ def test_sync_job_stop_shop():
|
|||||||
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
assert not job.stop_shop("toss") and not job.stop_shop("nope") # 끝난 작업·없는 쇼핑몰
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_only_marketplaces_skip_sync_and_show_manual_status():
|
||||||
|
"""쿠팡(로켓)·애터미아자몰 = 수동 입력 전용 — 매출 업데이트 대상이 아니고 연결 상태는 "수동 입력"."""
|
||||||
|
from app.modules.performance.dashboard import display_status
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
res = SyncService(st, creds).sync_all(start=date(2026, 10, 1), end=date(2026, 10, 2),
|
||||||
|
codes=["coupang_rocket", "atomy"], user="king@x")
|
||||||
|
assert res == [] and not st.events and not st.status
|
||||||
|
for code in ("coupang_rocket", "atomy"):
|
||||||
|
assert display_status({"code": code, "enabled": True}, None, False) == "manual"
|
||||||
|
assert display_status({"code": "coupang_rocket", "enabled": False}, None, False) == "disabled"
|
||||||
|
assert display_status({"code": "ohouse", "enabled": True}, None, False) == "not_configured"
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
os.environ.pop("APP_ENCRYPTION_KEY", None)
|
||||||
n = 0
|
n = 0
|
||||||
@@ -1729,3 +2059,112 @@ if __name__ == "__main__":
|
|||||||
n += 1
|
n += 1
|
||||||
print("ok", name)
|
print("ok", name)
|
||||||
print(f"{n} tests passed")
|
print(f"{n} tests passed")
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_sale_api_rules():
|
||||||
|
"""수동 입력 API — 그 쇼핑몰 수동 입력이 켜져 있을 때만, 오늘까지, 숫자(쉼표 허용), 비우면 지움, 002 미적용이면 503.
|
||||||
|
켜고 끄기(PUT marketplaces)는 관리자 전용 그대로, manual_input 도 받는다."""
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
from app.modules.performance import common
|
||||||
|
from app.modules.performance.db import ManualMigrationNeeded
|
||||||
|
|
||||||
|
router = importlib.import_module("app.modules.performance.router") # 패키지의 router 는 APIRouter 객체
|
||||||
|
|
||||||
|
class St:
|
||||||
|
def __init__(self):
|
||||||
|
self.saved, self.updated, self.missing = [], [], False
|
||||||
|
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{"code": "coupang", "manual_input": True}, {"code": "naver", "manual_input": False}]
|
||||||
|
|
||||||
|
def set_manual_sale(self, code, day, amount, *, user=""):
|
||||||
|
if self.missing:
|
||||||
|
raise ManualMigrationNeeded()
|
||||||
|
self.saved.append((code, day, amount, user))
|
||||||
|
|
||||||
|
def api_amount(self, code, day):
|
||||||
|
return 50000
|
||||||
|
|
||||||
|
def update_marketplace(self, code, **kw):
|
||||||
|
if self.missing and kw.get("manual_input") is not None:
|
||||||
|
raise ManualMigrationNeeded()
|
||||||
|
self.updated.append((code, kw))
|
||||||
|
return {"code": code}
|
||||||
|
|
||||||
|
st = St()
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
def fake_require(request, *, admin=False):
|
||||||
|
seen["admin"] = admin
|
||||||
|
return st, {"email": "me@test.local"}
|
||||||
|
|
||||||
|
def status_of(fn):
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except HTTPException as exc:
|
||||||
|
return exc.status_code, exc.detail
|
||||||
|
return 200, ""
|
||||||
|
|
||||||
|
orig = (common.require_store, router.today_kst)
|
||||||
|
common.require_store, router.today_kst = fake_require, (lambda: date(2026, 10, 12))
|
||||||
|
try:
|
||||||
|
r = router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "87,000"})
|
||||||
|
body = __import__("json").loads(r.body)
|
||||||
|
assert st.saved[-1] == ("coupang", date(2026, 10, 12), 87000, "me@test.local") and seen["admin"] is False
|
||||||
|
assert body["manual"] == 87000 and body["amount"] == 87000 and body["api_amount"] == 50000
|
||||||
|
body = __import__("json").loads(router.api_manual_sale(None, "coupang", "2026-10-11", {"amount": ""}).body)
|
||||||
|
assert st.saved[-1][2] is None and body["manual"] is None and body["amount"] == 50000 # 지움 → API 값
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-13", {"amount": 1}))[0] == 400 # 앞날
|
||||||
|
code, msg = status_of(lambda: router.api_manual_sale(None, "naver", "2026-10-12", {"amount": 1}))
|
||||||
|
assert code == 400 and "수동 입력" in msg # 꺼진 쇼핑몰
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": "abc"}))[0] == 400
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 10 ** 13}))[0] == 400
|
||||||
|
assert status_of(lambda: router.api_manual_sale(None, "nope", "2026-10-12", {"amount": 1}))[0] == 404
|
||||||
|
router.api_update_marketplace(None, "coupang", {"manual_input": True})
|
||||||
|
assert seen["admin"] is True and st.updated[-1] == ("coupang", {"enabled": None, "include_in_sales": None, "manual_input": True})
|
||||||
|
st.missing = True
|
||||||
|
code, msg = status_of(lambda: router.api_manual_sale(None, "coupang", "2026-10-12", {"amount": 1}))
|
||||||
|
assert code == 503 and "002" in msg
|
||||||
|
assert status_of(lambda: router.api_update_marketplace(None, "coupang", {"manual_input": False}))[0] == 503
|
||||||
|
finally:
|
||||||
|
common.require_store, router.today_kst = orig
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_manual_cells_and_order():
|
||||||
|
"""대시보드 — 수동 입력 켠 쇼핑몰만 manual_codes, 값이 있는 칸만 manual_cells, 수동 값이 그날 금액(수수료도 그 값으로)."""
|
||||||
|
from decimal import Decimal
|
||||||
|
|
||||||
|
from app.modules.performance.dashboard import build_dashboard
|
||||||
|
|
||||||
|
class St:
|
||||||
|
def list_marketplaces(self):
|
||||||
|
return [{"code": c, "name": c, "enabled": True, "include_in_sales": True, "manual_input": c == "coupang"}
|
||||||
|
for c in ("cafe24", "naver", "coupang", "toss")]
|
||||||
|
|
||||||
|
def daily_amounts(self, start, end, codes):
|
||||||
|
return {(date(2026, 10, 5), "coupang"): 87000} # 저장소가 이미 수동 값으로 바꿔 돌려준다
|
||||||
|
|
||||||
|
def manual_amounts(self, start, end, codes, *, active_only=True):
|
||||||
|
assert codes == ["coupang"]
|
||||||
|
return {(date(2026, 10, 5), "coupang"): 87000} if start <= date(2026, 10, 5) <= end else {}
|
||||||
|
|
||||||
|
def rate_table(self):
|
||||||
|
return {"coupang": [(date(2026, 1, 1), Decimal("10"))]}
|
||||||
|
|
||||||
|
def statuses(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def last_update_at(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def running_codes(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
ctx = build_dashboard(St(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||||
|
assert ctx["codes"] == ["cafe24", "naver", "coupang", "toss"]
|
||||||
|
assert ctx["manual_codes"] == ["coupang"] and ctx["manual_cells"] == ["2026-10-05|coupang"]
|
||||||
|
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||||
|
assert day5["cells"]["coupang"]["gross"] == 87000 and day5["cells"]["coupang"]["commission"] == 8700
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
"""2026-10-15 코드 검토(docs/CODE_REVIEW_2026-10-15.md) 실적 항목 회귀 테스트 — DB·네트워크 없이(가짜 저장소·가짜 HTTP).
|
||||||
|
|
||||||
|
F01 쿠팡 잘못된 응답(HTTP 200 + JSON 아님·data 없음)은 수집 실패 — 기존 매출 유지(replace_events 안 부름)
|
||||||
|
F04 인증정보가 바뀌면 이전 계정 토큰을 쓰지 않음(저장 때 내부 토큰 삭제 + 토큰-인증정보 지문), 같은 값 재저장은 유지
|
||||||
|
F05 쪽 수 상한·커서 반복이면 부분 수집을 성공으로 내지 않음(쿠팡은 기간을 나눠 다시), 다른 어댑터도 실패로
|
||||||
|
F06 collect() 끝 무렵 받아들인 [중지]는 저장 전에 반영, 저장을 시작했으면 [중지] 불가
|
||||||
|
F09 쇼핑몰 연결 테스트도 clear(비운 칸)를 빈 값으로 시험하고, 저장하지 않은 시험은 연결 상태를 바꾸지 않음
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.modules.performance.adapters import coupang as cp
|
||||||
|
from app.modules.performance.adapters import gsshop as gs
|
||||||
|
from app.modules.performance.adapters import kakao as kk
|
||||||
|
from app.modules.performance.adapters import naver as nv
|
||||||
|
from app.modules.performance.adapters import toss as ts
|
||||||
|
from app.modules.performance.adapters.base import AdapterContext, ApiError
|
||||||
|
from app.modules.performance.adapters.registry import get_adapter
|
||||||
|
from app.modules.performance.credentials import CredentialService
|
||||||
|
from app.modules.performance.sync import SyncService
|
||||||
|
from app.modules.performance.tests.test_performance import FakeStore, _naver_item, ring
|
||||||
|
|
||||||
|
|
||||||
|
class Creds(dict):
|
||||||
|
def get(self, k, default=""):
|
||||||
|
return dict.get(self, k, default)
|
||||||
|
|
||||||
|
def has(self, k):
|
||||||
|
return bool(dict.get(self, k))
|
||||||
|
|
||||||
|
def set(self, k, v):
|
||||||
|
self[k] = v
|
||||||
|
|
||||||
|
def known_secrets(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def _cp_ctx():
|
||||||
|
return AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK", secret_key="SK"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def no_wait(monkeypatch):
|
||||||
|
monkeypatch.setattr(cp, "CALL_INTERVAL_SEC", 0)
|
||||||
|
monkeypatch.setattr(cp, "RG_CALL_INTERVAL_SEC", 0)
|
||||||
|
monkeypatch.setattr(cp.time, "sleep", lambda *_a, **_k: None)
|
||||||
|
|
||||||
|
|
||||||
|
def _coupang_store_with_sales():
|
||||||
|
"""기존 쿠팡 매출 한 줄(10/12)이 있는 가짜 저장소 + 쿠팡 인증정보. replace_events 호출을 기록한다."""
|
||||||
|
st = FakeStore()
|
||||||
|
st.events[("coupang", "SALE", "coupang:9")] = {"sales_date": date(2026, 10, 12), "amount": 15000,
|
||||||
|
"event_type": "SALE", "is_sample": False}
|
||||||
|
st.replaced = []
|
||||||
|
orig = st.replace_events
|
||||||
|
|
||||||
|
def replace(code, start, end, events, *, id_prefix=""):
|
||||||
|
st.replaced.append((code, start, end, list(events)))
|
||||||
|
return orig(code, start, end, events, id_prefix=id_prefix)
|
||||||
|
|
||||||
|
st.replace_events = replace
|
||||||
|
creds = CredentialService(st, lambda: ring())
|
||||||
|
creds.save(get_adapter("coupang"), {"vendor_id": "A00012345", "access_key": "AK-1", "secret_key": "SK-1"})
|
||||||
|
return st, creds
|
||||||
|
|
||||||
|
|
||||||
|
# ── F01 ─────────────────────────────────────────────────────
|
||||||
|
@pytest.mark.parametrize("response", [
|
||||||
|
httpx.Response(200, text="<html>maintenance</html>"), # JSON 아님
|
||||||
|
httpx.Response(200, json={"message": "점검 중입니다"}), # 주문 목록(data) 없음
|
||||||
|
httpx.Response(200, json={"code": 200, "data": {"unexpected": True}}), # data 가 목록 아님
|
||||||
|
])
|
||||||
|
def test_f01_bad_200_response_fails_and_keeps_existing_sales(monkeypatch, no_wait, response):
|
||||||
|
st, creds = _coupang_store_with_sales()
|
||||||
|
monkeypatch.setattr(httpx, "get", lambda *a, **k: response)
|
||||||
|
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||||
|
assert not r["ok"] and r["status"] == "api_error", r
|
||||||
|
assert st.replaced == [] # 기간 교체(삭제)를 아예 하지 않음
|
||||||
|
assert ("coupang", "SALE", "coupang:9") in st.events # 기존 매출 그대로
|
||||||
|
assert st.status["coupang"]["ok"] is False and "저장하지 않았습니다" in r["message"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_f01_empty_list_is_still_a_normal_empty_period(monkeypatch, no_wait):
|
||||||
|
"""정상 빈 목록(data: [])은 주문 0건 — 기간 교체가 정상적으로 일어난다(실패와 구분)."""
|
||||||
|
st, creds = _coupang_store_with_sales()
|
||||||
|
monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [], "nextToken": ""}))
|
||||||
|
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12))
|
||||||
|
assert r["ok"], r
|
||||||
|
assert len(st.replaced) == 1 and st.replaced[0][3] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_f01_page_rows_contract():
|
||||||
|
assert cp.CoupangAdapter._page_rows({"code": 200, "data": []}, "발주서") == []
|
||||||
|
assert cp.CoupangAdapter._page_rows({"code": 200, "message": "OK", "data": None}, "발주서") == [] # 성공 표시 + null
|
||||||
|
assert cp.CoupangAdapter._page_rows({"data": [{"a": 1}, "x"]}, "발주서") == [{"a": 1}]
|
||||||
|
for body in ({}, {"data": None}, {"message": "maintenance"}, {"data": "x"}):
|
||||||
|
with pytest.raises(ApiError):
|
||||||
|
cp.CoupangAdapter._page_rows(body, "발주서")
|
||||||
|
|
||||||
|
|
||||||
|
# ── F05 ─────────────────────────────────────────────────────
|
||||||
|
def test_f05_coupang_page_limit_and_repeated_cursor_raise(monkeypatch, no_wait):
|
||||||
|
ad = cp.CoupangAdapter()
|
||||||
|
monkeypatch.setattr(cp, "MAX_PAGES", 2)
|
||||||
|
n = {"i": 0}
|
||||||
|
|
||||||
|
def endless(*a, **k):
|
||||||
|
n["i"] += 1
|
||||||
|
return httpx.Response(200, json={"code": 200, "data": [{"orderId": n["i"]}], "nextToken": f"t{n['i']}"})
|
||||||
|
|
||||||
|
monkeypatch.setattr(httpx, "get", endless)
|
||||||
|
with pytest.raises(cp.TooManyPages):
|
||||||
|
ad._pages(_cp_ctx(), "/x", {})
|
||||||
|
monkeypatch.setattr(httpx, "get", lambda *a, **k: httpx.Response(200, json={"code": 200, "data": [{"a": 1}], "nextToken": "same"}))
|
||||||
|
with pytest.raises(cp.TooManyPages, match="반복"):
|
||||||
|
ad._pages(_cp_ctx(), "/x", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_f05_coupang_splits_period_until_complete_or_fails(monkeypatch, no_wait):
|
||||||
|
"""2일 조회가 쪽 수 상한을 넘으면 하루씩 나눠 끝까지 받는다. 하루도 넘치면 명확한 실패."""
|
||||||
|
ad = cp.CoupangAdapter()
|
||||||
|
monkeypatch.setattr(cp, "MAX_PAGES", 3)
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, headers=None, timeout=None):
|
||||||
|
q = dict(p.split("=", 1) for p in url.split("?", 1)[1].split("&"))
|
||||||
|
calls.append((q["paidDateFrom"], q["paidDateTo"]))
|
||||||
|
if q["paidDateFrom"] != q["paidDateTo"]: # 여러 날 — 끝이 안 보임
|
||||||
|
i = int(q.get("nextToken", "0")) + 1
|
||||||
|
return httpx.Response(200, json={"data": [{"orderId": i}], "nextToken": str(i)})
|
||||||
|
return httpx.Response(200, json={"data": [{"orderId": q["paidDateFrom"]}], "nextToken": ""})
|
||||||
|
|
||||||
|
monkeypatch.setattr(httpx, "get", get)
|
||||||
|
rows = ad._rg_orders(_cp_ctx(), date(2026, 10, 11), date(2026, 10, 12))
|
||||||
|
assert sorted(r["orderId"] for r in rows) == ["20261011", "20261012"] # 부분 목록이 아니라 하루씩 전부
|
||||||
|
assert ("20261011", "20261011") in calls and ("20261012", "20261012") in calls
|
||||||
|
|
||||||
|
monkeypatch.setattr(httpx, "get", lambda url, headers=None, timeout=None: httpx.Response(
|
||||||
|
200, json={"data": [{"orderId": 1}], "nextToken": str(time.perf_counter_ns())}))
|
||||||
|
with pytest.raises(ApiError, match="하루"):
|
||||||
|
ad._rg_orders(_cp_ctx(), date(2026, 10, 12), date(2026, 10, 12))
|
||||||
|
|
||||||
|
|
||||||
|
def test_f05_other_adapters_fail_instead_of_partial(monkeypatch):
|
||||||
|
"""네이버·카카오·토스·GS샵 — 상한 소진·커서 반복은 실패(일부만 받은 목록을 돌려주지 않음)."""
|
||||||
|
ctx = AdapterContext(code="x", credentials=Creds())
|
||||||
|
d = date(2026, 10, 12)
|
||||||
|
|
||||||
|
monkeypatch.setattr(nv, "MAX_PAGES", 2)
|
||||||
|
a = nv.NaverAdapter()
|
||||||
|
a._get = lambda ctx, path, params: {"data": {"contents": [_naver_item(f"O{params['page']}", f"P{params['page']}",
|
||||||
|
"2026-10-12", 1000)],
|
||||||
|
"pagination": {"page": params["page"], "hasNext": True}}}
|
||||||
|
with pytest.raises(ApiError, match="끝까지"):
|
||||||
|
a._day_items(ctx, d)
|
||||||
|
|
||||||
|
k = kk.KakaoAdapter()
|
||||||
|
k._get = lambda ctx, path, params: {"contents": [{"orderId": "1"}], "token": "same"}
|
||||||
|
with pytest.raises(ApiError, match="반복"):
|
||||||
|
k._day_rows(ctx, d)
|
||||||
|
|
||||||
|
t = ts.TossAdapter()
|
||||||
|
t._get = lambda ctx, path, params: {"results": [{"id": 1}], "nextCursor": "c"}
|
||||||
|
with pytest.raises(ApiError, match="반복"):
|
||||||
|
t._window_items(ctx, d, d)
|
||||||
|
t._get = lambda ctx, path, params: {"items": [{"id": 1}], "nextToken": "n"}
|
||||||
|
with pytest.raises(ApiError, match="반복"):
|
||||||
|
t._settlement_items(ctx, d, d)
|
||||||
|
with pytest.raises(ApiError, match="반복"):
|
||||||
|
t._claims(ctx)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gs, "MAX_PAGES", 2)
|
||||||
|
g = gs.GsshopAdapter()
|
||||||
|
g._get = lambda ctx, path, params: {"data": [{"ordNo": params["pageIdx"]}], "hasMorePage": True}
|
||||||
|
with pytest.raises(ApiError, match="끝까지"):
|
||||||
|
g._pages(ctx, gs.SALES_PATH, d, d)
|
||||||
|
|
||||||
|
|
||||||
|
# ── F06 ─────────────────────────────────────────────────────
|
||||||
|
def test_f06_stop_accepted_at_end_of_collect_is_not_saved(monkeypatch, no_wait):
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
|
||||||
|
st, creds = _coupang_store_with_sales()
|
||||||
|
job = jobs.SyncJob(user="t", start=None, end=None)
|
||||||
|
shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"]
|
||||||
|
ad = get_adapter("coupang")
|
||||||
|
|
||||||
|
def collect(ctx, start, end): # 마지막 API 호출·정리 중에 [중지]가 들어온 상황
|
||||||
|
assert job.stop_shop("coupang") is True
|
||||||
|
return 1, []
|
||||||
|
|
||||||
|
monkeypatch.setattr(ad, "collect", collect)
|
||||||
|
r = SyncService(st, creds).sync_marketplace("coupang", date(2026, 10, 12), date(2026, 10, 12), progress=shop)
|
||||||
|
assert r.get("cancelled") and r["status"] == "cancelled", r
|
||||||
|
assert st.replaced == [] and ("coupang", "SALE", "coupang:9") in st.events # 저장 안 함
|
||||||
|
assert shop.state == "cancelled" and shop.message == "중지됨"
|
||||||
|
|
||||||
|
|
||||||
|
def test_f06_stop_after_saving_started_is_refused():
|
||||||
|
from app.modules.performance import jobs
|
||||||
|
|
||||||
|
job = jobs.SyncJob(user="t", start=None, end=None)
|
||||||
|
shop = job.set_targets([("coupang", "쿠팡", True)], date(2026, 10, 12), date(2026, 10, 12))["coupang"]
|
||||||
|
shop.start()
|
||||||
|
shop.begin_saving()
|
||||||
|
assert shop.state == "saving"
|
||||||
|
assert job.stop_shop("coupang") is False and shop.stop_requested is False # 저장 중이면 중지 불가를 알림
|
||||||
|
|
||||||
|
|
||||||
|
# ── F04 ─────────────────────────────────────────────────────
|
||||||
|
def _toss_svc():
|
||||||
|
st = FakeStore()
|
||||||
|
svc = CredentialService(st, lambda: ring())
|
||||||
|
ad = get_adapter("toss")
|
||||||
|
svc.save(ad, {"api_key": "k1", "api_secret": "s1"})
|
||||||
|
acc = svc.accessor("toss")
|
||||||
|
acc.set("access_token", "OLD_ACCOUNT_TOKEN")
|
||||||
|
acc.set("access_token_expires_at", str(int(time.time()) + 86400))
|
||||||
|
acc.set("access_token_for", ts.credential_fingerprint(acc, ts.TOKEN_KEYS))
|
||||||
|
return st, svc, ad
|
||||||
|
|
||||||
|
|
||||||
|
def test_f04_same_values_keep_token_changed_values_drop_it(monkeypatch):
|
||||||
|
st, svc, ad = _toss_svc()
|
||||||
|
issued = []
|
||||||
|
monkeypatch.setattr(httpx, "post", lambda *a, **k: issued.append(1) or httpx.Response(
|
||||||
|
200, json={"access_token": "NEW_ACCOUNT_TOKEN", "expires_in": 3600}))
|
||||||
|
|
||||||
|
svc.save(ad, {"api_key": "k1", "api_secret": "s1"}) # 같은 값 다시 저장
|
||||||
|
assert ("toss", "access_token") in st.creds
|
||||||
|
ctx = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||||
|
assert ad._token(ctx) == "OLD_ACCOUNT_TOKEN" and issued == [] # 불필요한 재발급 없음
|
||||||
|
|
||||||
|
svc.save(ad, {"api_key": "k2"}) # 계정(키) 변경
|
||||||
|
assert ("toss", "access_token") not in st.creds and ("toss", "access_token_expires_at") not in st.creds
|
||||||
|
ctx = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||||
|
assert ad._token(ctx) == "NEW_ACCOUNT_TOKEN" and issued == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_f04_token_bound_to_credentials_even_without_save(monkeypatch):
|
||||||
|
"""연결 테스트(저장 안 한 새 입력값)·예전 토큰(지문 없음)도 이전 계정 토큰을 쓰지 않는다 — 실제 수집과 같은 기준."""
|
||||||
|
st, svc, ad = _toss_svc()
|
||||||
|
monkeypatch.setattr(httpx, "post", lambda *a, **k: httpx.Response(200, json={"access_token": "NEW", "expires_in": 3600}))
|
||||||
|
trial = AdapterContext(code="toss", credentials=svc.accessor("toss", overrides={"api_key": "k2"}, persist=False))
|
||||||
|
assert ad._token(trial) == "NEW"
|
||||||
|
assert svc.accessor("toss").get("access_token") == "OLD_ACCOUNT_TOKEN" # 시험은 저장된 토큰을 건드리지 않음
|
||||||
|
# 지문이 없는 예전 토큰(배포 전에 저장된 것)은 한 번 새로 받는다
|
||||||
|
svc.accessor("toss").set("access_token_for", "")
|
||||||
|
real = AdapterContext(code="toss", credentials=svc.accessor("toss"))
|
||||||
|
assert ad._token(real) == "NEW" and svc.accessor("toss").get("access_token") == "NEW"
|
||||||
|
|
||||||
|
|
||||||
|
def test_f04_fingerprint_hides_values_and_gs_mode_cache_follows_key():
|
||||||
|
fp = ts.credential_fingerprint(Creds(api_key="secret-key-1", api_secret="s"), ts.TOKEN_KEYS)
|
||||||
|
assert len(fp) == 64 and "secret" not in fp
|
||||||
|
a = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K1" * 16))
|
||||||
|
b = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="K2" * 16))
|
||||||
|
assert gs.GsshopAdapter._mode_key(a) != gs.GsshopAdapter._mode_key(b)
|
||||||
|
|
||||||
|
|
||||||
|
# ── F09 ─────────────────────────────────────────────────────
|
||||||
|
def test_f09_shop_test_uses_empty_value_for_cleared_and_keeps_status(monkeypatch):
|
||||||
|
st = FakeStore()
|
||||||
|
svc = CredentialService(st, lambda: ring())
|
||||||
|
ad = get_adapter("naver")
|
||||||
|
svc.save(ad, {"client_id": "cid", "client_secret": "$2a$04$abcdefghijklmnopqrstuu", "account_id": "OLD-SELLER"})
|
||||||
|
st.status["naver"] = {"status": "ok", "ok": True, "error": ""}
|
||||||
|
seen = []
|
||||||
|
monkeypatch.setattr(ad, "test_connection", lambda ctx: seen.append(ctx.credentials.get("account_id")) or "연결됨")
|
||||||
|
r = SyncService(st, svc).test_connection("naver", cleared={"account_id"})
|
||||||
|
assert seen == [""] and r["ok"] and r["unsaved"] is True # 비운 칸은 빈 값, 저장 안 한 시험
|
||||||
|
assert st.status["naver"] == {"status": "ok", "ok": True, "error": ""} # 연결 상태 그대로
|
||||||
|
assert svc.accessor("naver").get("account_id") == "OLD-SELLER" # 저장값도 그대로
|
||||||
|
r = SyncService(st, svc).test_connection("naver") # 저장값 그대로 시험은 상태 기록
|
||||||
|
assert seen[-1] == "OLD-SELLER" and r["unsaved"] is False and st.status["naver"].get("test")
|
||||||
|
|
||||||
|
|
||||||
|
def test_f09_router_passes_clear_like_ad_test(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")
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Sync:
|
||||||
|
def test_connection(self, code, *, values=None, user="", cleared=None):
|
||||||
|
calls.append((code, values, cleared))
|
||||||
|
return {"ok": True, "status": "ok", "label": "정상 연결", "message": "연결됨", "unsaved": bool(values or cleared)}
|
||||||
|
|
||||||
|
st = FakeStore()
|
||||||
|
st.list_marketplaces = lambda: [{"code": "naver", "name": "네이버"}]
|
||||||
|
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (st, {"email": "king@x"}))
|
||||||
|
monkeypatch.setattr(common, "services", lambda request, store: (None, Sync()))
|
||||||
|
app = FastAPI()
|
||||||
|
app.include_router(perf_router.router)
|
||||||
|
c = TestClient(app)
|
||||||
|
r = c.post("/performance/api/marketplaces/naver/test",
|
||||||
|
json={"values": {"client_id": "new"}, "clear": ["account_id", "client_id", "nope"]})
|
||||||
|
assert r.status_code == 200 and r.json()["unsaved"] is True
|
||||||
|
assert calls[-1] == ("naver", {"client_id": "new"}, {"account_id"}) # 새 값이 있는 칸·모르는 칸은 빼고
|
||||||
Binary file not shown.
@@ -0,0 +1,127 @@
|
|||||||
|
# [프로젝트] 프로젝트 관리 모듈(아사나식) — `app/modules/project/`, `project_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 상세는 `docs/PROJECT_MODULE.md` — **178KB 큰 문서, 통째로 읽지 말 것.**
|
||||||
|
> `grep -n '^#' docs/PROJECT_MODULE.md` 로 목차를 보고 해당 절(아래 괄호의 6-x 번호)만 offset/limit 으로 읽는다.
|
||||||
|
> 정적 파일: `app/static/project*.js|css`(`project.js`·`project.css`·`project-goal-*`·`project-meeting-*`·`project-options.js`·`project-help.*`·`project-fonts.css`), `erp-overdue.js|css`.
|
||||||
|
> 템플릿: `templates/project/`. PC 알림 프로그램: `desktop/notifier/`.
|
||||||
|
> 다른 모듈과 연결: 긴급 공지(`notice`)가 `ProjectStore.pool` 공유 · 회의록 머리 카드가 실적 `performance_store` 매출 읽기 · 회의록 보드는 `app/integrations/google_slides.py`.
|
||||||
|
|
||||||
|
## 꼭 지킬 코드 규칙
|
||||||
|
|
||||||
|
- 라우터 핸들러는 동기 DB 라 `def` 로 둔다(`async def` 금지).
|
||||||
|
- 말풍선은 전부 아사나식 공용 말풍선(`.pj-hovertip`) — 새 기능도 `title=`/`data-tip=` 만 달고 별도 툴팁 구현 금지. 모달 대화창 안 말풍선은 popover(top layer).
|
||||||
|
- 담당자 배정 UI = 아이콘+이름(`assigneeMenuItems` / `enhanceAssigneeSelect`), 글자만 메뉴·기본 select 금지.
|
||||||
|
- 상단 바 화면 배율 토글(`html.pj-ui-scale` → `.erp-app` zoom .75, 2880×1620·200%용) — **팝업은 반드시 `document.body` 에 붙인다**(배율 안의 fixed 좌표는 어긋남).
|
||||||
|
- 권한 판단은 **지금 기준 공통 모듈 `access.py`** 하나로(목록·배지·알림·멘션·메일 수신자·삭제·댓글 수정까지 — 멤버에서 빠지면 기록이 있어도 안 보이고 알림도 없음).
|
||||||
|
- URL 의 섹션·부모 작업이 그 프로젝트 것인지 서버가 검증.
|
||||||
|
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
|
||||||
|
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
|
||||||
|
- UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것.
|
||||||
|
|
||||||
|
## 권한 — 관리자 등급 4단계 (2026-10-12, 6-14)
|
||||||
|
|
||||||
|
- **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**.
|
||||||
|
- 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다.
|
||||||
|
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버·소유자 변경.
|
||||||
|
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
|
||||||
|
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
|
||||||
|
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
|
||||||
|
- 연결(멀티호밍)된 작업은 연결된 프로젝트 멤버에게 읽기 전용(6-10).
|
||||||
|
- 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`).
|
||||||
|
|
||||||
|
## 구조 / 데이터
|
||||||
|
|
||||||
|
- 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE) → 진행단계(`project_stages`, 칸반 섹션) → 작업(`tasks`: 담당자·우선순위·시작/마감).
|
||||||
|
- 멤버 배정(`project_members`)·활동이력(`project_activity`).
|
||||||
|
- 프로젝트 색상 32색(아사나 16색 + 진한 16색, 수정 창 12열).
|
||||||
|
- 아이콘(`projects.icon`, Material Symbols 42종, 마이그레이션 011 + [아사나 아이콘] 탭 33종 `"asana:"+이름`, 채워진 모양 전용 부분 글꼴 `material-symbols-asana.woff2`).
|
||||||
|
- 섹션: 새 프로젝트는 섹션 없이 시작 — `create_project(seed_stages=True)` 일 때만 기본 4단계. 섹션 머리는 모두 `#f3f3f3`(섹션별 색 지정 없음), 섹션 이름 굵게.
|
||||||
|
- 섹션 기본 담당자 `default_assignee_email`(마이그레이션 009) — 담당자 빈 작업을 그 섹션에 만들거나 옮기면 자동 배정. 섹션 제목 오른쪽 담당자 아이콘 = 그 자리에서 지정(6-16).
|
||||||
|
- 실시간 반영은 `project_live_version` 카운터(마이그레이션 007, 미적용 시 MAX 폴백).
|
||||||
|
|
||||||
|
## 화면
|
||||||
|
|
||||||
|
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
|
||||||
|
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
|
||||||
|
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
|
||||||
|
- 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
|
||||||
|
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
||||||
|
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(기본 정렬·필터 없음일 때만, 전체 보기는 섹션 맨 끝). 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||||
|
- 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터).
|
||||||
|
- 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19).
|
||||||
|
- 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20).
|
||||||
|
- 패널(`/project/p/{pid}?task=&embed=1`, `html.pj-embed`).
|
||||||
|
- **업무를 다른 프로젝트로 이동** — 보드 카드를 왼쪽 프로젝트 목록에 끌어 놓으면 섹션 선택 창 → `POST /project/api/tasks/{id}/move-project`(세부 업무 함께, 원 소속 권한 + 대상 프로젝트 멤버)(6-18).
|
||||||
|
|
||||||
|
## 업무 창 / 댓글 / 협업자
|
||||||
|
|
||||||
|
- 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성).
|
||||||
|
- **파일 끌어 놓기 = 첨부**(2026-10-19): 업무 창 아무 곳(`.pj-task-modal-card`, 설명칸 포함)·보드 메인 업무 카드에 파일을 놓으면 `POST /project/api/tasks/{id}/attachments`(여러 개 차례로, `uploadTaskFiles`). 종류 "Files" 로 카드·세부 업무 끌기와 구분, 받는 곳 밖에 놓친 파일은 document 가 막아 화면이 파일로 넘어가지 않음.
|
||||||
|
- 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 주소 붙여넣기 시 자동 링크. 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동).
|
||||||
|
- 설명란·댓글에서 @로 멤버 태그(`task_mentions`, 마이그레이션 006) → 수신함에 그 작업이 쌓임. 댓글 `@아이디` 는 아이콘+이름 칩.
|
||||||
|
- 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea).
|
||||||
|
- 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503). 반응 = 댓글 쓴 사람에게 알림(`type=reaction`).
|
||||||
|
- 완료 이력 줄은 `project_activity` completed 를 댓글 사이에 표시(댓글 수 제외).
|
||||||
|
- 협업자(`task_followers`, 자동 팔로우: 만든 사람·담당자·댓글·@태그) — 완료·댓글 알림은 담당자+협업자에게만.
|
||||||
|
- **담당자는 협업자가 아니다**(협업자 = 담당자 외의 멤버, `db.add_followers` 가 거르고 담당자 지정 시 협업자에서 뺌, 기존 겹친 행은 마이그레이션 028).
|
||||||
|
- 세부 업무: 업무 창 세부 업무 줄 담당자 오른쪽 = 협업자 지정. 만들 때(업무 창 추가 칸·보드 카드 새 줄) 협업자도 같이(`POST …/tasks` 의 `followers`, 비멤버 400). 만든 사람을 자동 협업자로 넣지 않음(고른 사람만). 보드 카드 세부 업무 줄에도 협업자 아이콘. 추가 칸은 동그라미 아이콘 버튼. 빈 마감일 아이콘 늘 옅게(6-17·6-19·6-20).
|
||||||
|
- 작업 삭제는 휴지통(`project_trash`, 마이그레이션 010) — 삭제 직전 스냅샷 3개월 보관, Pro user 이상만 보기·복구(`/project/trash`).
|
||||||
|
|
||||||
|
## 알림
|
||||||
|
|
||||||
|
- 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
|
||||||
|
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
|
||||||
|
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
|
||||||
|
- 마감 알림(`reminders.py` 데몬 스레드, 영업일 09시, D-1/당일/지연, `task_reminders` 로 중복 방지, `PROJECT_REMINDER_*` env) — 마이그레이션 008.
|
||||||
|
- 작업 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*` + `PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기).
|
||||||
|
- **PC 알림 프로그램**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms exe 하나·트레이 상주, 마이그레이션 023 `notifier_links`·`notifier_tokens`, 6-11)
|
||||||
|
- 브라우저가 뒤에 있어도 태그·배정 알림을 웹 팝업과 같은 모양으로 화면 위에.
|
||||||
|
- 브라우저 `/project/notifier?code=` 승인으로 PC별 토큰(서버는 SHA-256 만, PC 는 DPAPI). `GET /project/api/notifier/alerts`(Bearer)는 웹 알림과 같은 `_alerts_payload`, 토큰마다 지금 사용자·권한 재확인.
|
||||||
|
- 프로그램이 돌고 있으면(최근 3분 확인, `notifier_active`) 웹 큰 팝업은 쉰다(`desktop: true`).
|
||||||
|
- 압축·난독화 금지(백신 오탐), 빌드 `desktop/notifier/build.ps1`.
|
||||||
|
|
||||||
|
## Project 옵션 (상단 톱니, 2026-10-16)
|
||||||
|
|
||||||
|
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
|
||||||
|
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
|
||||||
|
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`).
|
||||||
|
- 긴급 공지 = 수퍼관리자만.
|
||||||
|
|
||||||
|
## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9)
|
||||||
|
|
||||||
|
- 사이드바 "목표" → 연도 펼침 → `/project/goals/{연도}`. 매출(목표·실적·달성)·로아스 월별 숫자 + 업무 영역(상품·마케팅·컨텐츠·유통 등)별 연간·월별 글.
|
||||||
|
- 조회는 전원·입력(주차별 목표·연도 추가/삭제 포함)은 Pro user 이상.
|
||||||
|
- 3·6·9·12월 오른쪽 1~4분기 칸(글 칸 13=1분기·15=2분기·14=3분기·16=4분기 — 예전 반기 칸 번호 재사용, 15·16 은 마이그레이션 017) + 분기 월 칸 접기 애니메이션(localStorage `pj_goal_fold_q`, 표는 `width:1px` + `table-layout:fixed`)(6-9-0).
|
||||||
|
- 영역·줄 이름 클릭 바로 수정. 로아스는 % 표기.
|
||||||
|
- **엑셀식 칸 병합** — 마우스로 끌어 사각형 선택 → 우클릭 셀 병합/병합 해제, 같은 영역 안 세로 `row_span` + 같은 분기 월 칸 가로, 글은 왼쪽 위 칸(`goal_cell_merges`, 마이그레이션 014·015·017).
|
||||||
|
- 3열 줄 추가는 같은 항목 칸(2열) 안에(`goal_rows.label_cont`, 마이그레이션 016).
|
||||||
|
- 구조 변경은 새로고침 없이 제자리 다시 그리기(`refreshTable`) + 애니메이션.
|
||||||
|
- 모든 열 너비 끌어서 조절(localStorage `pj_goal_col_w`), 세로 스크롤 틀 고정은 머리 줄 + 매출·로아스 줄까지, 항목 칸 +·우클릭으로 줄 위/아래 추가·삭제.
|
||||||
|
- 목표 표 매출 목표 월 칸을 누르면 **주차별 매출 목표**(`goal_week_targets`) 입력 창 — 월 전체 목표는 직접 입력(주차 합계와 별개), 맨 아래 차이 = 월 목표 − 주차 합계.
|
||||||
|
- 목표 표·회의록 칸 저장은 공용 `createFieldSaver`(같은 칸 요청 직렬화·보낸 값만 저장됨·실패 시 초안 유지·localStorage 초안 백업, 저장 실패면 구조 변경 중단 — 6-9-3).
|
||||||
|
- 구역·항목 메뉴는 우클릭 + ⋮ 버튼(키보드·터치).
|
||||||
|
|
||||||
|
## 주간 회의록 (`/project/goals/{연도}/meetings/{월}`, 6-9-2·6-9-3·6-9-4·6-22)
|
||||||
|
|
||||||
|
- 진입: 목표 표 월 머리. `goal_meetings`·`goal_meeting_items` 마이그레이션 015.
|
||||||
|
- 수정: 프로젝트 권한자 **누구나**. Pro user 이상 [회의 완료](`completed_at`, 마이그레이션 022)면 잠금(지난주 결과는 다음 주 회의록이 열려 있는 동안 허용). 삭제·완료·완료 해제는 Pro user 이상.
|
||||||
|
- 표 첫 열 머리 글자 "구분".
|
||||||
|
- 주차 탭 — **주차는 그 달 안**(`store.month_weeks`): 1일이 월~금이면 1일~일요일이 1주차, 토·일이면 1일~다음 주 일요일, 그 뒤 월~일, 말일이 월·화면 앞 주차에 붙음. 회의록 `week_start` = 주차 시작일(마이그레이션 020).
|
||||||
|
- 지난주 = **바로 앞 주차**(`store.prev_week_period`) 회의록의 같은 연결키 줄(`line_key`, 마이그레이션 018 — 생성 순서·이름 변경과 무관, **이름 추정 연결 금지**)로 리뷰.
|
||||||
|
- 열: 주요 업무·정량 목표 ‖ 전주 업무·결과(글, `result_note` 020)·전주 목표·결과. 정량 목표·결과는 숫자면 원 정수 칸, 아니면 글 칸 `target_text`·`result_text`(예: 20개, 021).
|
||||||
|
- 실적 조회 장애는 0원이 아니라 "미확인".
|
||||||
|
- 위에 목표 표 그 달 열 글을 영역별 "N월 계획" 카드로.
|
||||||
|
- 참석자 옆 [회의록 보드] = 그 주차의 빈 Google 슬라이드를 독립 창으로(오른쪽 🔗 아이콘 = 그 보드 링크 복사). 공유 드라이브 `MEETING_BOARD_FOLDER_ID`(없으면 만듦), `app/integrations/google_slides.py`, Drive appProperties 로 주차 연결 — Drive·Slides 권한 토큰 필요.
|
||||||
|
- 표를 스크롤해도 보이는 머리 영역 3칸:
|
||||||
|
1. 월 계획 + 머리 줄에 숫자 4개 작게 1행 — 월 목표 매출·월 누적 목표 매출(`goal_week_targets` 1주차~이 주차 합)·월 누적 실적(1일~오늘)·누적 목표 대비 차액·%.
|
||||||
|
2. 결정 사항·메모.
|
||||||
|
3. "N주차 작업 등록" 표(제목·담당자·프로젝트·섹션 → [적용] = 서버가 그 프로젝트에 작업 생성, `initMeetQuickTasks`).
|
||||||
|
주차별 서버 표 `goal_meeting_tasks`(마이그레이션 025)라 모두가 같이 보고, 남의 프로젝트 이름은 가림, 완료 프로젝트·섹션은 목록에서 뺌.
|
||||||
|
작업 칸(마이그레이션 026 `parent_task_id`) = 이미 있는 작업을 고르면 그 작업의 세부 작업으로 등록.
|
||||||
|
등록된 줄 제목 = 오른쪽 작업 창(편집, 저장 대기), [크게 열기] = 같은 표를 넓은 창으로.
|
||||||
|
- 실적 모듈 `performance_store` 매출은 머리 카드에만 읽기 전용 — 줄(쇼핑몰)별 자동 결과·이번주 실적·연결 배지·쇼핑몰 연결 메뉴는 폐지, 지난주 결과는 늘 직접 입력.
|
||||||
|
- "주요 업무" 칸 우클릭 위/아래 줄 추가 = 항목 칸은 그대로 그 항목 안에(마이그레이션 027 `label_cont`, 항목 칸 나누기).
|
||||||
|
- 회의록 줄 작업은 새로고침 없이 제자리 다시 그리기(`refreshMeeting`) + 애니메이션.
|
||||||
|
- 구분(구역) 칸 우클릭·⋯ = 구역 통째로 위/아래(`move-section`).
|
||||||
|
- 항목 칸 끌어 옮기기(2026-10-19) — 마우스로 항목 칸을 5px 이상 끌면 묶음(label_cont 줄 + 걸친 세로 병합)이 같은 구역 안에서 실시간 이동(칸 단위 FLIP, 구분 칸은 늘 첫 줄), 놓으면 `POST meeting-items/{id}/move-to {before_item_id|null}`(`db.move_meeting_group`, 묶음 사이·다른 구역은 거절) → `refreshMeeting`. Esc 취소, 짧게 누르기는 이름 수정.
|
||||||
|
- 회의록 표(`.pj-meet-table`) 테두리는 검정 `#000`, 구역(구분) 처음·끝 가로선은 굵게 2px, 항목과 항목 사이 가로선은 검정(`.is-item-end`), 같은 항목 안 하위 줄 사이만 회색 `#bfc3c9`(2026-10-19). 구역 끝에 닿는 칸(병합 포함)은 `.is-sec-end`(아래선 없음 — 다음 구역 굵은 선이 대신). 둘 다 JS `markMeetSecEnds` 가 달고 표 다시 그리기·끌기 뒤에도 다시 계산.
|
||||||
+627
-86
@@ -49,6 +49,11 @@ class ProjectStore:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self._pool.close()
|
self._pool.close()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pool(self) -> Any:
|
||||||
|
"""같은 project_db 를 쓰는 다른 저장소(긴급 공지 — app/modules/notice)가 연결 풀을 같이 쓴다."""
|
||||||
|
return self._pool
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 프로젝트 / 서브프로젝트
|
# 프로젝트 / 서브프로젝트
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -675,6 +680,28 @@ class ProjectStore:
|
|||||||
assignee_allowed: Any = None,
|
assignee_allowed: Any = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김)."""
|
"""assignee_allowed — update_task 와 같이 섹션 기본 담당자 자동 배정 전 지금 권한 확인(라우터가 넘김)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row, done_at = self._insert_task(
|
||||||
|
conn, project_id=project_id, title=title, stage_id=stage_id, description=description,
|
||||||
|
assignee_email=assignee_email, assignee_name=assignee_name, priority=priority,
|
||||||
|
start_date=start_date, due_date=due_date, start_time=start_time, due_time=due_time,
|
||||||
|
created_by=created_by, parent_task_id=parent_task_id, assignee_allowed=assignee_allowed,
|
||||||
|
)
|
||||||
|
out = self.get_task(task_id=row["id"])
|
||||||
|
out["_newly_completed"] = done_at is not None
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _insert_task(
|
||||||
|
self, conn: Any, *, project_id: int, title: str, stage_id: int | None = None, description: str = "",
|
||||||
|
assignee_email: str = "", assignee_name: str = "", priority: str = "normal",
|
||||||
|
start_date: str | None = None, due_date: str | None = None, start_time: str | None = None,
|
||||||
|
due_time: str | None = None, created_by: str = "", parent_task_id: int | None = None,
|
||||||
|
assignee_allowed: Any = None,
|
||||||
|
) -> tuple[dict[str, Any], Any]:
|
||||||
|
"""업무 한 건 INSERT(+배정·완료 이력) — **부르는 쪽의 연결·트랜잭션 안에서**(커밋하지 않음). (행, 완료 시각|None).
|
||||||
|
create_task 와 회의록 [적용](apply_meeting_task — 줄 잠금과 같은 트랜잭션)이 같이 쓴다. 다른 풀 연결을 빌리지
|
||||||
|
않는다(assignee_allowed 는 사용자 목록만 보는 함수)."""
|
||||||
ttl = store.validate_task_title(title)
|
ttl = store.validate_task_title(title)
|
||||||
pr = store.validate_priority(priority)
|
pr = store.validate_priority(priority)
|
||||||
sd = store.validate_date(start_date)
|
sd = store.validate_date(start_date)
|
||||||
@@ -684,74 +711,70 @@ class ProjectStore:
|
|||||||
store.validate_date_range(sd, dd, sti, dti)
|
store.validate_date_range(sd, dd, sti, dti)
|
||||||
assignee = store.norm_str(assignee_email, lower=True)
|
assignee = store.norm_str(assignee_email, lower=True)
|
||||||
done_at = None
|
done_at = None
|
||||||
with self._pool.connection() as conn:
|
if parent_task_id is not None:
|
||||||
with conn.transaction():
|
# 세부 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이
|
||||||
if parent_task_id is not None:
|
# 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다.
|
||||||
# 세부 업무는 부모와 같은 프로젝트에 속하고(담당자 선택지 등이
|
parent = conn.execute(
|
||||||
# 맞아떨어지게), 보드에는 안 보이므로 세션을 갖지 않는다.
|
"SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,)
|
||||||
parent = conn.execute(
|
).fetchone()
|
||||||
"SELECT project_id FROM tasks WHERE id = %s", (parent_task_id,)
|
if not parent:
|
||||||
).fetchone()
|
raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}")
|
||||||
if not parent:
|
# 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트
|
||||||
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
|
# 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는
|
||||||
# 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트
|
# 프로젝트에 세부 업무를 만들 수 있었다).
|
||||||
# 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는
|
if int(parent["project_id"]) != int(project_id):
|
||||||
# 프로젝트에 세부 업무를 만들 수 있었다).
|
raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.")
|
||||||
if int(parent["project_id"]) != int(project_id):
|
stage_id = None
|
||||||
raise ValueError("상위 작업이 이 프로젝트에 속하지 않습니다.")
|
elif stage_id not in (None, ""):
|
||||||
stage_id = None
|
stage_id = self._check_stage_in_project(conn, stage_id, project_id)
|
||||||
elif stage_id not in (None, ""):
|
else:
|
||||||
stage_id = self._check_stage_in_project(conn, stage_id, project_id)
|
# stage 미지정 시 프로젝트의 첫 세션으로
|
||||||
else:
|
st = conn.execute(
|
||||||
# stage 미지정 시 프로젝트의 첫 세션으로
|
"SELECT id FROM project_stages WHERE project_id = %s "
|
||||||
st = conn.execute(
|
"ORDER BY sort_order ASC, id ASC LIMIT 1",
|
||||||
"SELECT id FROM project_stages WHERE project_id = %s "
|
(project_id,),
|
||||||
"ORDER BY sort_order ASC, id ASC LIMIT 1",
|
).fetchone()
|
||||||
(project_id,),
|
stage_id = st["id"] if st else None
|
||||||
).fetchone()
|
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는
|
||||||
stage_id = st["id"] if st else None
|
# 세션이 없어 해당 없음).
|
||||||
# 담당자 없이 만들면 그 세션의 기본 담당자를 배정(세부 업무는
|
if not assignee and stage_id is not None:
|
||||||
# 세션이 없어 해당 없음).
|
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id,
|
||||||
if not assignee and stage_id is not None:
|
allowed=assignee_allowed)
|
||||||
assignee, assignee_name = self._stage_default_assignee(conn, stage_id, project_id,
|
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
|
||||||
allowed=assignee_allowed)
|
if stage_id is not None:
|
||||||
# 완료 섹션에 바로 만든 작업은 완료 섹션으로 옮긴 것과 같이 완료 처리(완료 시각·이력).
|
done_row = conn.execute(
|
||||||
if stage_id is not None:
|
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
|
||||||
done_row = conn.execute(
|
).fetchone()
|
||||||
"SELECT is_done_stage FROM project_stages WHERE id = %s", (stage_id,)
|
if done_row and done_row["is_done_stage"]:
|
||||||
).fetchone()
|
done_at = now_kst()
|
||||||
if done_row and done_row["is_done_stage"]:
|
nxt = conn.execute(
|
||||||
done_at = now_kst()
|
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
||||||
nxt = conn.execute(
|
"WHERE project_id = %s",
|
||||||
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
(project_id,),
|
||||||
"WHERE project_id = %s",
|
).fetchone()
|
||||||
(project_id,),
|
row = conn.execute(
|
||||||
).fetchone()
|
"""
|
||||||
row = conn.execute(
|
INSERT INTO tasks
|
||||||
"""
|
(project_id, stage_id, parent_task_id, title, description,
|
||||||
INSERT INTO tasks
|
assignee_email, assignee_name, priority, start_date, due_date,
|
||||||
(project_id, stage_id, parent_task_id, title, description,
|
start_time, due_time, sort_order, created_by, completed_at)
|
||||||
assignee_email, assignee_name, priority, start_date, due_date,
|
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||||
start_time, due_time, sort_order, created_by, completed_at)
|
RETURNING *
|
||||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
""",
|
||||||
RETURNING *
|
(
|
||||||
""",
|
project_id, stage_id, parent_task_id, ttl, store.norm_str(description),
|
||||||
(
|
assignee, store.norm_str(assignee_name), pr, sd, dd,
|
||||||
project_id, stage_id, parent_task_id, ttl, store.norm_str(description),
|
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at,
|
||||||
assignee, store.norm_str(assignee_name), pr, sd, dd,
|
),
|
||||||
sti, dti, int(nxt["n"]), store.norm_str(created_by, lower=True), done_at,
|
).fetchone()
|
||||||
),
|
if assignee:
|
||||||
).fetchone()
|
self._log(conn, project_id=project_id, task_id=row["id"],
|
||||||
if assignee:
|
actor=created_by, action=store.ACTION_ASSIGNED,
|
||||||
self._log(conn, project_id=project_id, task_id=row["id"],
|
detail=f"{ttl} → {assignee}")
|
||||||
actor=created_by, action=store.ACTION_ASSIGNED,
|
if done_at is not None:
|
||||||
detail=f"{ttl} → {assignee}")
|
self._log(conn, project_id=project_id, task_id=row["id"],
|
||||||
if done_at is not None:
|
actor=created_by, action=store.ACTION_COMPLETED, detail=ttl)
|
||||||
self._log(conn, project_id=project_id, task_id=row["id"],
|
return row, done_at
|
||||||
actor=created_by, action=store.ACTION_COMPLETED, detail=ttl)
|
|
||||||
out = self.get_task(task_id=row["id"])
|
|
||||||
out["_newly_completed"] = done_at is not None
|
|
||||||
return out
|
|
||||||
|
|
||||||
def move_subtask(
|
def move_subtask(
|
||||||
self, *, task_id: int, parent_task_id: int, actor: str = ""
|
self, *, task_id: int, parent_task_id: int, actor: str = ""
|
||||||
@@ -771,19 +794,19 @@ class ProjectStore:
|
|||||||
(task_id,),
|
(task_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if not sub:
|
if not sub:
|
||||||
raise KeyError(f"작업을 찾을 수 없습니다: {task_id}")
|
raise KeyError(f"업무를 찾을 수 없습니다: {task_id}")
|
||||||
if sub["parent_task_id"] is None:
|
if sub["parent_task_id"] is None:
|
||||||
raise ValueError("세부 작업만 다른 작업으로 옮길 수 있습니다.")
|
raise ValueError("세부 업무만 다른 업무로 옮길 수 있습니다.")
|
||||||
parent = conn.execute(
|
parent = conn.execute(
|
||||||
"SELECT id, project_id, parent_task_id, title FROM tasks WHERE id = %s",
|
"SELECT id, project_id, parent_task_id, title FROM tasks WHERE id = %s",
|
||||||
(parent_task_id,),
|
(parent_task_id,),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if not parent:
|
if not parent:
|
||||||
raise KeyError(f"상위 작업을 찾을 수 없습니다: {parent_task_id}")
|
raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}")
|
||||||
if parent["parent_task_id"] is not None:
|
if parent["parent_task_id"] is not None:
|
||||||
raise ValueError("세부 작업 안으로는 옮길 수 없습니다.")
|
raise ValueError("세부 업무 안으로는 옮길 수 없습니다.")
|
||||||
if int(parent["project_id"]) != int(sub["project_id"]):
|
if int(parent["project_id"]) != int(sub["project_id"]):
|
||||||
raise ValueError("다른 프로젝트의 작업으로는 옮길 수 없습니다.")
|
raise ValueError("다른 프로젝트의 업무로는 옮길 수 없습니다.")
|
||||||
if int(parent["id"]) != int(sub["parent_task_id"]):
|
if int(parent["id"]) != int(sub["parent_task_id"]):
|
||||||
nxt = conn.execute(
|
nxt = conn.execute(
|
||||||
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks "
|
||||||
@@ -913,6 +936,8 @@ class ProjectStore:
|
|||||||
store.validate_date_range(final("start_date"), final("due_date"),
|
store.validate_date_range(final("start_date"), final("due_date"),
|
||||||
final("start_time"), final("due_time"))
|
final("start_time"), final("due_time"))
|
||||||
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
||||||
|
if "assignee_email" in assignee_fields:
|
||||||
|
self._drop_assignee_follower(conn, task_id, assignee_fields["assignee_email"])
|
||||||
if newly_assigned:
|
if newly_assigned:
|
||||||
self._log(conn, project_id=prev["project_id"], task_id=task_id,
|
self._log(conn, project_id=prev["project_id"], task_id=task_id,
|
||||||
actor=actor, action=store.ACTION_ASSIGNED,
|
actor=actor, action=store.ACTION_ASSIGNED,
|
||||||
@@ -928,6 +953,88 @@ class ProjectStore:
|
|||||||
out["_newly_completed"] = newly_completed if changed else False
|
out["_newly_completed"] = newly_completed if changed else False
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
def move_task_to_project(
|
||||||
|
self, *, task_id: int, project_id: int, stage_id: Any = None, actor: str = "",
|
||||||
|
assignee_allowed: Any = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""메인 업무를 다른 프로젝트(의 섹션)로 옮긴다 — 세부 업무(모든 단계)도 함께. 한 트랜잭션.
|
||||||
|
|
||||||
|
· 메인 업무만(세부 업무는 상위 업무와 함께 움직인다). 같은 프로젝트면 ValueError.
|
||||||
|
· 섹션은 대상 프로젝트 것만(None = 섹션 없음). 목록 끝(sort_order 최대+1)으로.
|
||||||
|
· 섹션을 옮길 때와 같은 규칙 — 담당자가 비었으면 그 섹션 기본 담당자, 완료 섹션이면 완료 처리.
|
||||||
|
· 대상 프로젝트로 걸려 있던 연결(멀티호밍)은 이제 원 소속이라 지운다(다른 연결은 그대로).
|
||||||
|
· 활동 이력·알림·회의록 업무 등록 줄의 프로젝트도 따라 바꾼다(이력이 새 프로젝트 화면에 보이게).
|
||||||
|
반환: 옮긴 업무(get_task) + `_moved_ids`·`_newly_assigned`·`_newly_completed`.
|
||||||
|
"""
|
||||||
|
newly_assigned: str | None = None
|
||||||
|
newly_completed = False
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute("SELECT * FROM tasks WHERE id = %s FOR UPDATE", (task_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(f"업무를 찾을 수 없습니다: {task_id}")
|
||||||
|
prev = self._serialize(row)
|
||||||
|
if prev.get("parent_task_id") is not None:
|
||||||
|
raise ValueError("세부 업무는 상위 업무와 함께 옮겨집니다. 상위 업무를 옮기세요.")
|
||||||
|
target = int(project_id)
|
||||||
|
if int(prev["project_id"]) == target:
|
||||||
|
raise ValueError("이미 이 프로젝트의 업무입니다.")
|
||||||
|
if not conn.execute("SELECT 1 FROM projects WHERE id = %s", (target,)).fetchone():
|
||||||
|
raise KeyError(f"프로젝트를 찾을 수 없습니다: {target}")
|
||||||
|
new_stage = self._check_stage_in_project(conn, stage_id, target)
|
||||||
|
ids = [int(r["id"]) for r in conn.execute(
|
||||||
|
"WITH RECURSIVE tree AS (SELECT id FROM tasks WHERE id = %s "
|
||||||
|
"UNION ALL SELECT t.id FROM tasks t JOIN tree ON t.parent_task_id = tree.id) "
|
||||||
|
"SELECT id FROM tree",
|
||||||
|
(task_id,),
|
||||||
|
).fetchall()]
|
||||||
|
nxt = conn.execute(
|
||||||
|
"SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM tasks WHERE project_id = %s",
|
||||||
|
(target,),
|
||||||
|
).fetchone()
|
||||||
|
conn.execute("UPDATE tasks SET project_id = %s WHERE id = ANY(%s)", (target, ids))
|
||||||
|
sets = ["stage_id = %s", "sort_order = %s"]
|
||||||
|
params: list[Any] = [new_stage, int(nxt["n"])]
|
||||||
|
if new_stage is not None and not (prev.get("assignee_email") or ""):
|
||||||
|
dae, dan = self._stage_default_assignee(conn, new_stage, target, allowed=assignee_allowed)
|
||||||
|
if dae:
|
||||||
|
sets += ["assignee_email = %s", "assignee_name = %s"]
|
||||||
|
params += [dae, dan]
|
||||||
|
newly_assigned = dae
|
||||||
|
if self._stage_is_done_conn(conn, new_stage) and not prev.get("completed_at"):
|
||||||
|
sets.append("completed_at = %s")
|
||||||
|
params.append(now_kst())
|
||||||
|
newly_completed = True
|
||||||
|
conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = %s", (*params, task_id))
|
||||||
|
if newly_assigned:
|
||||||
|
self._drop_assignee_follower(conn, task_id, newly_assigned)
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM task_project_links WHERE task_id = ANY(%s) AND project_id = %s", (ids, target))
|
||||||
|
conn.execute("UPDATE project_activity SET project_id = %s WHERE task_id = ANY(%s)", (target, ids))
|
||||||
|
conn.execute("UPDATE project_notifications SET project_id = %s WHERE task_id = ANY(%s)", (target, ids))
|
||||||
|
if self._table_exists(conn, "goal_meeting_tasks"):
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_meeting_tasks SET project_id = %s, stage_id = %s WHERE task_id = %s",
|
||||||
|
(target, new_stage, task_id))
|
||||||
|
old_name = conn.execute("SELECT name FROM projects WHERE id = %s", (prev["project_id"],)).fetchone()
|
||||||
|
new_name = conn.execute("SELECT name FROM projects WHERE id = %s", (target,)).fetchone()
|
||||||
|
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||||
|
action=store.ACTION_PROJECT_MOVED,
|
||||||
|
detail=f"{prev['title']}: {(old_name or {}).get('name', '')} → {(new_name or {}).get('name', '')}")
|
||||||
|
if newly_assigned:
|
||||||
|
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||||
|
action=store.ACTION_ASSIGNED, detail=f"{prev['title']} → {newly_assigned}")
|
||||||
|
if newly_completed:
|
||||||
|
self._log(conn, project_id=target, task_id=task_id, actor=actor,
|
||||||
|
action=store.ACTION_COMPLETED, detail=prev["title"])
|
||||||
|
out = self.get_task(task_id=task_id)
|
||||||
|
if out is None:
|
||||||
|
raise KeyError(task_id)
|
||||||
|
out["_moved_ids"] = ids
|
||||||
|
out["_newly_assigned"] = newly_assigned
|
||||||
|
out["_newly_completed"] = newly_completed
|
||||||
|
return out
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관
|
# 휴지통 (마이그레이션 010) — 지우기 직전 스냅샷, 관리자 복구, 3개월 보관
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -1068,23 +1175,23 @@ class ProjectStore:
|
|||||||
payload = tr["payload"] or {}
|
payload = tr["payload"] or {}
|
||||||
tasks = list(payload.get("tasks") or [])
|
tasks = list(payload.get("tasks") or [])
|
||||||
if not tasks:
|
if not tasks:
|
||||||
raise ValueError("복구할 작업 데이터가 없습니다.")
|
raise ValueError("복구할 업무 데이터가 없습니다.")
|
||||||
ids = [int(t["id"]) for t in tasks]
|
ids = [int(t["id"]) for t in tasks]
|
||||||
clash = conn.execute(
|
clash = conn.execute(
|
||||||
"SELECT id FROM tasks WHERE id = ANY(%s) LIMIT 1", (ids,)
|
"SELECT id FROM tasks WHERE id = ANY(%s) LIMIT 1", (ids,)
|
||||||
).fetchone()
|
).fetchone()
|
||||||
if clash:
|
if clash:
|
||||||
raise ValueError(f"이미 같은 작업(id {clash['id']})이 있어 복구할 수 없습니다.")
|
raise ValueError(f"이미 같은 업무(id {clash['id']})이 있어 복구할 수 없습니다.")
|
||||||
project_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM projects").fetchall()}
|
project_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM projects").fetchall()}
|
||||||
stage_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM project_stages").fetchall()}
|
stage_ids = {int(r["id"]) for r in conn.execute("SELECT id FROM project_stages").fetchall()}
|
||||||
root = next((t for t in tasks if int(t["id"]) == int(tr["task_id"])), tasks[0])
|
root = next((t for t in tasks if int(t["id"]) == int(tr["task_id"])), tasks[0])
|
||||||
if int(root["project_id"]) not in project_ids:
|
if int(root["project_id"]) not in project_ids:
|
||||||
raise ValueError("작업이 속했던 프로젝트가 삭제되어 복구할 수 없습니다.")
|
raise ValueError("업무가 속했던 프로젝트가 삭제되어 복구할 수 없습니다.")
|
||||||
parent = root.get("parent_task_id")
|
parent = root.get("parent_task_id")
|
||||||
if parent and int(parent) not in ids:
|
if parent and int(parent) not in ids:
|
||||||
ok = conn.execute("SELECT 1 FROM tasks WHERE id = %s", (int(parent),)).fetchone()
|
ok = conn.execute("SELECT 1 FROM tasks WHERE id = %s", (int(parent),)).fetchone()
|
||||||
if not ok:
|
if not ok:
|
||||||
raise ValueError("상위 작업이 없어 복구할 수 없습니다 — 상위 작업을 먼저 복구하세요.")
|
raise ValueError("상위 업무가 없어 복구할 수 없습니다 — 상위 업무를 먼저 복구하세요.")
|
||||||
for t in tasks:
|
for t in tasks:
|
||||||
if t.get("stage_id") is not None and int(t["stage_id"]) not in stage_ids:
|
if t.get("stage_id") is not None and int(t["stage_id"]) not in stage_ids:
|
||||||
t["stage_id"] = None
|
t["stage_id"] = None
|
||||||
@@ -1735,6 +1842,30 @@ class ProjectStore:
|
|||||||
return False
|
return False
|
||||||
return row is not None
|
return row is not None
|
||||||
|
|
||||||
|
# ── Project 옵션(시스템 전체, 마이그레이션 029) — 키 하나 = 행 하나, 값 검사는 store 한 곳 ──
|
||||||
|
def get_project_options(self) -> dict[str, Any]:
|
||||||
|
"""저장된 시스템 옵션 원본 {key: value}. 029 미적용이면 {}(화면은 기본값)."""
|
||||||
|
try:
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute("SELECT key, value FROM project_options").fetchall()
|
||||||
|
except psycopg_errors.UndefinedTable:
|
||||||
|
return {}
|
||||||
|
return {r["key"]: r["value"] for r in rows}
|
||||||
|
|
||||||
|
def set_project_options(self, *, values: dict[str, Any], updated_by: str) -> None:
|
||||||
|
"""검사를 마친 값만 넣는다(store.validate_project_options). 한 트랜잭션 — 전부 아니면 전무.
|
||||||
|
029 미적용이면 psycopg_errors.UndefinedTable(라우터가 503)."""
|
||||||
|
by = store.norm_str(updated_by, lower=True)
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
for key, value in values.items():
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO project_options (key, value, updated_by, updated_at) VALUES (%s, %s, %s, now()) "
|
||||||
|
"ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_by = EXCLUDED.updated_by, "
|
||||||
|
"updated_at = now()",
|
||||||
|
(key, Jsonb(value), by),
|
||||||
|
)
|
||||||
|
|
||||||
def notifier_revoke_token(self, *, token: str) -> None:
|
def notifier_revoke_token(self, *, token: str) -> None:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||||
@@ -1830,6 +1961,21 @@ class ProjectStore:
|
|||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def list_my_overdue(self, *, assignee_email: str, today: Any, limit: int = 200) -> list[dict[str, Any]]:
|
||||||
|
"""내가 담당인 미완료 업무 중 마감일이 오늘 이전인 것(세부 업무 포함, 마감 오래된 것부터)."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT t.id, t.title, t.due_date, t.project_id, t.parent_task_id, "
|
||||||
|
" p.name AS project_name, p.color AS project_color, pt.title AS parent_title "
|
||||||
|
"FROM tasks t JOIN projects p ON p.id = t.project_id "
|
||||||
|
"LEFT JOIN tasks pt ON pt.id = t.parent_task_id "
|
||||||
|
"WHERE t.assignee_email = %s AND t.completed_at IS NULL "
|
||||||
|
" AND t.due_date IS NOT NULL AND t.due_date < %s "
|
||||||
|
"ORDER BY t.due_date ASC, t.id ASC LIMIT %s",
|
||||||
|
(store.norm_str(assignee_email, lower=True), today, int(limit)),
|
||||||
|
).fetchall()
|
||||||
|
return [self._serialize(r) for r in rows]
|
||||||
|
|
||||||
def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]:
|
def list_my_open_refs(self, *, assignee_email: str) -> list[dict[str, Any]]:
|
||||||
"""내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다."""
|
"""내가 담당인 미완료 작업 전부의 (id, project_id) — "내 작업" 배지를 제한 없이 정확히 센다."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
@@ -1876,8 +2022,25 @@ class ProjectStore:
|
|||||||
).fetchall()
|
).fetchall()
|
||||||
return [r["user_email"] for r in rows]
|
return [r["user_email"] for r in rows]
|
||||||
|
|
||||||
|
def list_followers_of(self, *, task_ids: list[int]) -> dict[int, list[str]]:
|
||||||
|
"""여러 업무의 협업자를 한 번에 — 업무 창 세부 업무 줄의 협업자 아이콘용."""
|
||||||
|
ids = [int(i) for i in task_ids]
|
||||||
|
if not ids:
|
||||||
|
return {}
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT task_id, user_email FROM task_followers WHERE task_id = ANY(%s) "
|
||||||
|
"ORDER BY created_at ASC, user_email ASC",
|
||||||
|
(ids,),
|
||||||
|
).fetchall()
|
||||||
|
out: dict[int, list[str]] = {i: [] for i in ids}
|
||||||
|
for r in rows:
|
||||||
|
out[int(r["task_id"])].append(r["user_email"])
|
||||||
|
return out
|
||||||
|
|
||||||
def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]:
|
def add_followers(self, *, task_id: int, emails: list[str]) -> list[str]:
|
||||||
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다."""
|
"""팔로워 추가(이미 있으면 무시). 새로 추가된 이메일만 돌려준다.
|
||||||
|
그 업무의 담당자는 넣지 않는다 — 협업자는 담당자 외의 멤버(2026-10-13)."""
|
||||||
targets = store.normalize_emails(emails)
|
targets = store.normalize_emails(emails)
|
||||||
if not targets:
|
if not targets:
|
||||||
return []
|
return []
|
||||||
@@ -1885,11 +2048,18 @@ class ProjectStore:
|
|||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"INSERT INTO task_followers (task_id, user_email) "
|
"INSERT INTO task_followers (task_id, user_email) "
|
||||||
"SELECT %s, e FROM unnest(%s::text[]) AS e "
|
"SELECT %s, e FROM unnest(%s::text[]) AS e "
|
||||||
|
"WHERE e <> COALESCE((SELECT lower(assignee_email) FROM tasks WHERE id = %s), '') "
|
||||||
"ON CONFLICT DO NOTHING RETURNING user_email",
|
"ON CONFLICT DO NOTHING RETURNING user_email",
|
||||||
(task_id, targets),
|
(task_id, targets, task_id),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
return [r["user_email"] for r in rows]
|
return [r["user_email"] for r in rows]
|
||||||
|
|
||||||
|
def _drop_assignee_follower(self, conn: Any, task_id: int, email: str) -> None:
|
||||||
|
"""새 담당자는 협업자에서 뺀다(같은 트랜잭션). 008 미적용이면 건너뜀."""
|
||||||
|
if email and self._table_exists(conn, "task_followers"):
|
||||||
|
conn.execute("DELETE FROM task_followers WHERE task_id = %s AND user_email = %s",
|
||||||
|
(task_id, store.norm_str(email, lower=True)))
|
||||||
|
|
||||||
def remove_follower(self, *, task_id: int, user_email: str) -> None:
|
def remove_follower(self, *, task_id: int, user_email: str) -> None:
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
@@ -2771,7 +2941,23 @@ class ProjectStore:
|
|||||||
return (self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "")
|
return (self._MEETING_ITEM_COLS + (", line_key" if self._meeting_keys(conn) else "")
|
||||||
+ (", content_row_span" if self._meeting_cells(conn) else "")
|
+ (", content_row_span" if self._meeting_cells(conn) else "")
|
||||||
+ (", result_note" if self._meeting_v20(conn) else "")
|
+ (", result_note" if self._meeting_v20(conn) else "")
|
||||||
+ (", target_text, result_text" if self._meeting_v21(conn) else ""))
|
+ (", target_text, result_text" if self._meeting_v21(conn) else "")
|
||||||
|
+ (", label_cont" if self._meeting_v27(conn) else ""))
|
||||||
|
|
||||||
|
def _meeting_v27(self, conn: Any) -> bool:
|
||||||
|
"""마이그레이션 027 — 항목 칸 묶음(label_cont: 바로 위 줄의 항목 칸에 이어 붙는 줄)."""
|
||||||
|
if getattr(self, "_meeting_v27_ok", False):
|
||||||
|
return True
|
||||||
|
ok = self._column_exists(conn, "goal_meeting_items", "label_cont")
|
||||||
|
if ok:
|
||||||
|
self._meeting_v27_ok = True
|
||||||
|
return ok
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _meeting_conts(rows: list[dict[str, Any]]) -> list[bool]:
|
||||||
|
"""줄 순서대로 '실제로 이어 붙은 줄'인가 — label_cont 이고 바로 위 줄이 같은 구역일 때만(구역 첫 줄은 늘 묶음 첫 줄)."""
|
||||||
|
return [bool(r.get("label_cont")) and i > 0 and rows[i - 1]["section"] == r["section"]
|
||||||
|
for i, r in enumerate(rows)]
|
||||||
|
|
||||||
def _meeting_v21(self, conn: Any) -> bool:
|
def _meeting_v21(self, conn: Any) -> bool:
|
||||||
"""마이그레이션 021 — 정량 목표·결과 글(target_text·result_text, 예: "20개")."""
|
"""마이그레이션 021 — 정량 목표·결과 글(target_text·result_text, 예: "20개")."""
|
||||||
@@ -2994,6 +3180,7 @@ class ProjectStore:
|
|||||||
if ws.weekday() != 0 and not self._meeting_v20(conn):
|
if ws.weekday() != 0 and not self._meeting_v20(conn):
|
||||||
raise store.MeetingMigration020Needed() # 월요일만 허용하던 CHECK 가 아직 있다
|
raise store.MeetingMigration020Needed() # 월요일만 허용하던 CHECK 가 아직 있다
|
||||||
keyed = self._meeting_keys(conn)
|
keyed = self._meeting_keys(conn)
|
||||||
|
v27 = self._meeting_v27(conn)
|
||||||
ins = conn.execute(
|
ins = conn.execute(
|
||||||
"INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) "
|
"INSERT INTO goal_meetings (week_start, created_by, updated_by) VALUES (%s, %s, %s) "
|
||||||
"ON CONFLICT (week_start) DO NOTHING RETURNING week_start",
|
"ON CONFLICT (week_start) DO NOTHING RETURNING week_start",
|
||||||
@@ -3001,7 +3188,8 @@ class ProjectStore:
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
if ins is None:
|
if ins is None:
|
||||||
return False
|
return False
|
||||||
src_cols = "id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
src_cols = ("id, section, section_color, label, marketplace_code, sort_order" + (", line_key" if keyed else "")
|
||||||
|
+ (", label_cont" if v27 else ""))
|
||||||
src_items: list[dict[str, Any]] = []
|
src_items: list[dict[str, Any]] = []
|
||||||
src_is_prev = True
|
src_is_prev = True
|
||||||
for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)):
|
for cmp_, order, is_prev in (("<", "DESC", True), (">", "ASC", False)):
|
||||||
@@ -3037,6 +3225,12 @@ class ProjectStore:
|
|||||||
"marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
"marketplace_code, carry_from, sort_order, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||||
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who),
|
(ws, r["section"], r["section_color"], r["label"], r["marketplace_code"], carry, n, who),
|
||||||
)
|
)
|
||||||
|
if v27 and r.get("label_cont"):
|
||||||
|
# 항목 칸 묶음도 그대로 이어받는다(027) — 방금 넣은 줄(같은 주차·순서)
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_meeting_items SET label_cont = true WHERE week_start = %s AND sort_order = %s",
|
||||||
|
(ws, n),
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
n = 0
|
n = 0
|
||||||
for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]:
|
for name, color in sections or [(k, "") for k in store.MEETING_TEMPLATE]:
|
||||||
@@ -3103,9 +3297,14 @@ class ProjectStore:
|
|||||||
|
|
||||||
def add_meeting_item(
|
def add_meeting_item(
|
||||||
self, *, week_start: date, section: str, section_color: str = "", label: str = "",
|
self, *, week_start: date, section: str, section_color: str = "", label: str = "",
|
||||||
ref_item_id: int | None = None, place: str = "below", updated_by: str = "",
|
ref_item_id: int | None = None, place: str = "below", updated_by: str = "", same_label: bool = False,
|
||||||
) -> int:
|
) -> int:
|
||||||
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역)."""
|
"""줄 추가 — 기준 줄 위/아래(같은 구역), 없으면 그 구역 끝(구역이 없으면 맨 끝 = 새 구역).
|
||||||
|
|
||||||
|
same_label(주요 업무 칸에서 추가, 027) = 새 줄을 기준 줄과 **같은 항목 칸** 안에: 아래면 새 줄이 이어 붙고(label_cont),
|
||||||
|
위면 — 기준 줄이 묶음 첫 줄이면 새 줄이 첫 줄이 되어 이름을 넘겨받고 기준 줄이 이어 붙는다(연간 목표 016 과 같은 규칙)."""
|
||||||
|
if same_label and ref_item_id is None:
|
||||||
|
raise ValueError("같은 항목 칸에 추가하려면 기준 줄이 필요합니다.")
|
||||||
sec = store.norm_str(section)
|
sec = store.norm_str(section)
|
||||||
if not sec or len(sec) > store.MEETING_LABEL_MAX:
|
if not sec or len(sec) > store.MEETING_LABEL_MAX:
|
||||||
raise ValueError("구역 이름을 입력하세요(50자 이하).")
|
raise ValueError("구역 이름을 입력하세요(50자 이하).")
|
||||||
@@ -3136,14 +3335,31 @@ class ProjectStore:
|
|||||||
i = same[-1] + 1 if same else len(ids)
|
i = same[-1] + 1 if same else len(ids)
|
||||||
if any(a < i <= b for a, b in self._meeting_merge_ranges(rows)):
|
if any(a < i <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||||
raise ValueError("병합된 셀 안에 줄을 추가하려면 먼저 병합을 해제해 주세요.")
|
raise ValueError("병합된 셀 안에 줄을 추가하려면 먼저 병합을 해제해 주세요.")
|
||||||
|
cont = False
|
||||||
|
if same_label:
|
||||||
|
if not self._meeting_v27(conn):
|
||||||
|
raise store.MeetingMigration027Needed()
|
||||||
|
k = ids.index(ref_item_id)
|
||||||
|
ref = rows[k]
|
||||||
|
if ref["section"] != sec:
|
||||||
|
raise ValueError("기준 줄과 같은 구역이어야 합니다.")
|
||||||
|
if place == "above" and not self._meeting_conts(rows)[k]:
|
||||||
|
# 묶음 첫 줄 위 — 새 줄이 첫 줄(이름을 넘겨받음), 기준 줄은 이어 붙는다
|
||||||
|
lb = ref["label"]
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET label = '', label_cont = true WHERE id = %s",
|
||||||
|
(ref_item_id,))
|
||||||
|
else:
|
||||||
|
lb, cont = "", True
|
||||||
# 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다
|
# 새 줄 = 새 연결키(018) — 이름이 같은 다른 줄과 섞이지 않는다
|
||||||
keyed = self._meeting_keys(conn)
|
keyed = self._meeting_keys(conn)
|
||||||
|
v27 = self._meeting_v27(conn)
|
||||||
new_id = int(conn.execute(
|
new_id = int(conn.execute(
|
||||||
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
|
"INSERT INTO goal_meeting_items (week_start, section, section_color, label, marketplace_code, "
|
||||||
"sort_order, updated_by" + (", line_key" if keyed else "") + ") VALUES (%s,%s,%s,%s,%s,0,%s"
|
"sort_order, updated_by" + (", line_key" if keyed else "") + (", label_cont" if v27 else "")
|
||||||
+ (",%s" if keyed else "") + ") RETURNING id",
|
+ ") VALUES (%s,%s,%s,%s,%s,0,%s" + (",%s" if keyed else "") + (",%s" if v27 else "") + ") RETURNING id",
|
||||||
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
|
(week_start, sec, color, lb, store.guess_meeting_market(sec, lb),
|
||||||
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ())),
|
store.norm_str(updated_by, lower=True), *((str(uuid.uuid4()),) if keyed else ()),
|
||||||
|
*((cont,) if v27 else ())),
|
||||||
).fetchone()["id"])
|
).fetchone()["id"])
|
||||||
ids.insert(i, new_id)
|
ids.insert(i, new_id)
|
||||||
for n, x in enumerate(ids):
|
for n, x in enumerate(ids):
|
||||||
@@ -3299,6 +3515,15 @@ class ProjectStore:
|
|||||||
i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id)
|
i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id)
|
||||||
if any(a <= i <= b for a, b in self._meeting_merge_ranges(rows)):
|
if any(a <= i <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||||
raise ValueError("병합된 셀의 줄을 삭제하려면 먼저 병합을 해제해 주세요.")
|
raise ValueError("병합된 셀의 줄을 삭제하려면 먼저 병합을 해제해 주세요.")
|
||||||
|
if self._meeting_v27(conn):
|
||||||
|
# 항목 칸 묶음 첫 줄을 지우면 바로 아래 이어 붙은 줄이 첫 줄이 되고 이름을 넘겨받는다(비어 있으면)
|
||||||
|
conts = self._meeting_conts(rows)
|
||||||
|
if not conts[i] and i + 1 < len(rows) and conts[i + 1]:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE goal_meeting_items SET label_cont = false, "
|
||||||
|
"label = CASE WHEN label = '' THEN %s ELSE label END WHERE id = %s",
|
||||||
|
(rows[i]["label"], rows[i + 1]["id"]),
|
||||||
|
)
|
||||||
row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone()
|
row = conn.execute("DELETE FROM goal_meeting_items WHERE id = %s RETURNING id", (item_id,)).fetchone()
|
||||||
if row is None:
|
if row is None:
|
||||||
raise KeyError(item_id)
|
raise KeyError(item_id)
|
||||||
@@ -3316,10 +3541,326 @@ class ProjectStore:
|
|||||||
return
|
return
|
||||||
if any(a <= i <= b or a <= j <= b for a, b in self._meeting_merge_ranges(rows)):
|
if any(a <= i <= b or a <= j <= b for a, b in self._meeting_merge_ranges(rows)):
|
||||||
raise ValueError("병합된 셀의 줄을 이동하려면 먼저 병합을 해제해 주세요.")
|
raise ValueError("병합된 셀의 줄을 이동하려면 먼저 병합을 해제해 주세요.")
|
||||||
|
conts = self._meeting_conts(rows)
|
||||||
|
in_group = lambda k: conts[k] or (k + 1 < len(rows) and conts[k + 1]) # noqa: E731
|
||||||
|
if in_group(i) or in_group(j):
|
||||||
|
raise ValueError("같은 항목 칸으로 묶인 줄은 옮길 수 없습니다. 항목 칸을 나눈 뒤 옮기세요.")
|
||||||
ids[i], ids[j] = ids[j], ids[i]
|
ids[i], ids[j] = ids[j], ids[i]
|
||||||
for n, x in enumerate(ids):
|
for n, x in enumerate(ids):
|
||||||
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
|
||||||
|
def move_meeting_group(self, *, item_id: int, before_item_id: int | None) -> bool:
|
||||||
|
"""항목 칸 끌어 옮기기(2026-10-19) — item_id 가 든 묶음(같은 항목 칸으로 이어 붙은 줄 + 걸친 세로 병합)을 통째로
|
||||||
|
같은 구역의 before_item_id 묶음 앞에(None = 구역 맨 끝). 묶음 안 줄 순서·병합은 그대로 따라간다. 바뀌면 True."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
rows = self._locked_meeting_items(conn, item_id)
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
conts = self._meeting_conts(rows)
|
||||||
|
merges = self._meeting_merge_ranges(rows)
|
||||||
|
# 묶음 경계 = 이어 붙은 줄이 아니고 병합 범위 안쪽도 아닌 줄(구역이 바뀌는 줄은 늘 경계)
|
||||||
|
starts = [k for k in range(len(rows))
|
||||||
|
if k == 0 or rows[k]["section"] != rows[k - 1]["section"]
|
||||||
|
or (not conts[k] and not any(a < k <= b for a, b in merges))]
|
||||||
|
i = ids.index(item_id)
|
||||||
|
s = max(k for k in starts if k <= i)
|
||||||
|
e = next((k for k in starts if k > s), len(rows))
|
||||||
|
section = rows[s]["section"]
|
||||||
|
block = ids[s:e]
|
||||||
|
rest = ids[:s] + ids[e:]
|
||||||
|
if before_item_id is None:
|
||||||
|
sec_idx = [n for n, x in enumerate(rest) if rows[ids.index(x)]["section"] == section]
|
||||||
|
pos = (sec_idx[-1] + 1) if sec_idx else s
|
||||||
|
else:
|
||||||
|
if before_item_id not in ids:
|
||||||
|
raise KeyError(before_item_id)
|
||||||
|
b = ids.index(before_item_id)
|
||||||
|
if rows[b]["section"] != section:
|
||||||
|
raise ValueError("같은 구역 안에서만 옮길 수 있습니다.")
|
||||||
|
if b not in starts:
|
||||||
|
raise store.GoalCellConflict("묶인 줄 사이에는 넣을 수 없습니다. 새로고침해 주세요.")
|
||||||
|
if s <= b < e:
|
||||||
|
return False
|
||||||
|
pos = rest.index(before_item_id)
|
||||||
|
order = rest[:pos] + block + rest[pos:]
|
||||||
|
if order == ids:
|
||||||
|
return False
|
||||||
|
for n, x in enumerate(order):
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
return True
|
||||||
|
|
||||||
|
def move_meeting_section(self, *, item_id: int, direction: int) -> None:
|
||||||
|
"""구역(표 첫 열 "구분") 통째로 한 칸 위/아래 — item_id 가 든 구역 묶음(이어진 같은 구역 줄)과 옆 구역 묶음의
|
||||||
|
자리를 바꾼다. 묶음 안 줄 순서·세로 병합(content_row_span)은 그대로 따라간다. 맨 위/맨 아래면 그대로."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
rows = self._locked_meeting_items(conn, item_id)
|
||||||
|
ids = [int(r["id"]) for r in rows]
|
||||||
|
blocks: list[list[int]] = [] # 이어진 같은 구역 줄 묶음(화면의 tbody 하나)
|
||||||
|
for i, r in enumerate(rows):
|
||||||
|
if i and r["section"] == rows[i - 1]["section"]:
|
||||||
|
blocks[-1].append(ids[i])
|
||||||
|
else:
|
||||||
|
blocks.append([ids[i]])
|
||||||
|
b = next(n for n, blk in enumerate(blocks) if item_id in blk)
|
||||||
|
j = b + (1 if direction > 0 else -1)
|
||||||
|
if not 0 <= j < len(blocks):
|
||||||
|
return
|
||||||
|
blocks[b], blocks[j] = blocks[j], blocks[b]
|
||||||
|
order = [x for blk in blocks for x in blk]
|
||||||
|
for n, x in enumerate(order):
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET sort_order = %s WHERE id = %s", (n, x))
|
||||||
|
|
||||||
|
def split_meeting_label(self, *, item_id: int) -> int:
|
||||||
|
"""항목 칸 나누기(027) — item_id(묶음 첫 줄) 아래 이어 붙은 줄들을 각자 항목 칸으로(이름은 빈 칸). 나눈 줄 수."""
|
||||||
|
with self._pool.connection() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._require_meetings(conn)
|
||||||
|
if not self._meeting_v27(conn):
|
||||||
|
raise store.MeetingMigration027Needed()
|
||||||
|
rows = self._locked_meeting_items(conn, item_id)
|
||||||
|
conts = self._meeting_conts(rows)
|
||||||
|
i = next(n for n, r in enumerate(rows) if int(r["id"]) == item_id)
|
||||||
|
n = 0
|
||||||
|
for k in range(i + 1, len(rows)):
|
||||||
|
if not conts[k]:
|
||||||
|
break
|
||||||
|
conn.execute("UPDATE goal_meeting_items SET label_cont = false WHERE id = %s", (rows[k]["id"],))
|
||||||
|
n += 1
|
||||||
|
return n
|
||||||
|
|
||||||
|
# ── 회의록 작업 등록 표(025) — 주차별 한 표, 모두가 같이 본다. [적용] 전 줄은 고치고, [적용]은 한 번만 ──
|
||||||
|
# 026 — 작업 칸(parent_task_id): 고르면 [적용] 때 그 작업의 세부 작업으로(비우면 그 섹션에 새 작업).
|
||||||
|
# 025 의 parent_id(표 안 줄끼리 세부 작업)는 화면에서 쓰지 않는다(열·값은 그대로, 읽기·쓰기 안 함).
|
||||||
|
_MT_BASE = ("id, week_start, sort_order, title, assignee_email, project_id, stage_id, task_id, "
|
||||||
|
"created_by, updated_by, created_at, updated_at")
|
||||||
|
|
||||||
|
def _mt_v26(self, conn: Any) -> bool:
|
||||||
|
"""026(작업 칸 parent_task_id) 적용 여부 — 적용되면 한 번만 확인."""
|
||||||
|
if getattr(self, "_mt_v26_ok", False):
|
||||||
|
return True
|
||||||
|
ok = self._column_exists(conn, "goal_meeting_tasks", "parent_task_id")
|
||||||
|
if ok:
|
||||||
|
self._mt_v26_ok = True
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def _mt_cols(self, conn: Any, prefix: str = "") -> str:
|
||||||
|
cols = [prefix + c.strip() for c in self._MT_BASE.split(",")]
|
||||||
|
if self._mt_v26(conn):
|
||||||
|
cols.append(prefix + "parent_task_id")
|
||||||
|
return ", ".join(cols)
|
||||||
|
|
||||||
|
def _mt_conn(self) -> Any:
|
||||||
|
return self._pool.connection()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _mt_call(fn: Any) -> Any:
|
||||||
|
try:
|
||||||
|
return fn()
|
||||||
|
except psycopg_errors.UndefinedTable:
|
||||||
|
raise store.MeetingTaskMigrationNeeded()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _mt_row(r: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
out = {k: r.get(k) for k in ("id", "sort_order", "title", "assignee_email", "project_id",
|
||||||
|
"stage_id", "task_id", "parent_task_id", "created_by", "updated_by")}
|
||||||
|
for k in ("id", "project_id", "stage_id", "task_id", "parent_task_id"):
|
||||||
|
out[k] = int(out[k]) if out[k] is not None else None
|
||||||
|
out["week_start"] = r["week_start"].isoformat()
|
||||||
|
out["updated_at"] = r["updated_at"].astimezone(KST).isoformat(timespec="seconds") if r.get("updated_at") else ""
|
||||||
|
for k in ("project_name", "project_status", "stage_name", "task_title", "task_project_id", "parent_task_title"):
|
||||||
|
if k in r:
|
||||||
|
out[k] = r[k]
|
||||||
|
if "task_exists" in r:
|
||||||
|
out["task_exists"] = bool(r["task_exists"])
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _mt_clean(self, conn: Any, fields: dict[str, Any], *, project_id: Any = None) -> dict[str, Any]:
|
||||||
|
"""고칠 칸 정리 — title(200자)·assignee_email·project_id·stage_id(그 프로젝트 섹션)·parent_task_id(그 프로젝트 작업, 026).
|
||||||
|
프로젝트가 바뀌면 섹션·작업을 비운다."""
|
||||||
|
clean: dict[str, Any] = {}
|
||||||
|
v26 = self._mt_v26(conn)
|
||||||
|
if "title" in fields:
|
||||||
|
t = store.norm_str(fields.get("title"))
|
||||||
|
if len(t) > 200:
|
||||||
|
raise ValueError("업무 제목은 200자 이하로 입력하세요.")
|
||||||
|
clean["title"] = t
|
||||||
|
if "assignee_email" in fields:
|
||||||
|
clean["assignee_email"] = store.norm_str(fields.get("assignee_email") or "", lower=True)
|
||||||
|
pid = project_id
|
||||||
|
if "project_id" in fields:
|
||||||
|
raw = fields.get("project_id")
|
||||||
|
try:
|
||||||
|
pid = int(raw) if raw not in (None, "") else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("프로젝트 값이 올바르지 않습니다.")
|
||||||
|
clean["project_id"] = pid
|
||||||
|
if "stage_id" not in fields:
|
||||||
|
clean["stage_id"] = None
|
||||||
|
if v26 and "parent_task_id" not in fields:
|
||||||
|
clean["parent_task_id"] = None
|
||||||
|
if "stage_id" in fields:
|
||||||
|
sid = fields.get("stage_id")
|
||||||
|
if sid in (None, ""):
|
||||||
|
clean["stage_id"] = None
|
||||||
|
else:
|
||||||
|
if pid is None:
|
||||||
|
raise ValueError("프로젝트를 먼저 고르세요.")
|
||||||
|
clean["stage_id"] = self._check_stage_in_project(conn, sid, int(pid))
|
||||||
|
if "parent_task_id" in fields:
|
||||||
|
if not v26:
|
||||||
|
raise store.MeetingParentTaskMigrationNeeded()
|
||||||
|
raw = fields.get("parent_task_id")
|
||||||
|
if raw in (None, ""):
|
||||||
|
clean["parent_task_id"] = None
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
tid = int(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValueError("업무 값이 올바르지 않습니다.")
|
||||||
|
if pid is None:
|
||||||
|
raise ValueError("프로젝트를 먼저 고르세요.")
|
||||||
|
t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (tid,)).fetchone()
|
||||||
|
if t is None or int(t["project_id"]) != int(pid):
|
||||||
|
raise ValueError("이 프로젝트의 업무가 아닙니다.")
|
||||||
|
clean["parent_task_id"] = tid
|
||||||
|
return clean
|
||||||
|
|
||||||
|
def _mt_select(self, conn: Any, where: str, params: tuple[Any, ...]) -> list[dict[str, Any]]:
|
||||||
|
"""줄 + 프로젝트·섹션·고른 작업 이름 + 만든 작업 존재 여부(목록·한 줄 응답 공용)."""
|
||||||
|
v26 = self._mt_v26(conn)
|
||||||
|
return conn.execute(
|
||||||
|
f"SELECT {self._mt_cols(conn, 'm.')}, "
|
||||||
|
" p.name AS project_name, p.status AS project_status, s.name AS stage_name, "
|
||||||
|
" t.title AS task_title, t.project_id AS task_project_id, (t.id IS NOT NULL) AS task_exists"
|
||||||
|
+ (", pt.title AS parent_task_title " if v26 else " ") +
|
||||||
|
"FROM goal_meeting_tasks m "
|
||||||
|
"LEFT JOIN projects p ON p.id = m.project_id "
|
||||||
|
"LEFT JOIN project_stages s ON s.id = m.stage_id "
|
||||||
|
"LEFT JOIN tasks t ON t.id = m.task_id "
|
||||||
|
+ ("LEFT JOIN tasks pt ON pt.id = m.parent_task_id " if v26 else "") +
|
||||||
|
f"WHERE {where} ORDER BY m.sort_order, m.id", params,
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
def list_meeting_tasks(self, *, week_start: date) -> list[dict[str, Any]]:
|
||||||
|
"""그 주차 표 — 순서대로. 프로젝트·섹션·고른 작업 이름, 만든 작업 존재 여부를 붙인다."""
|
||||||
|
def run() -> list[dict[str, Any]]:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
return [self._mt_row(r) for r in self._mt_select(conn, "m.week_start = %s", (week_start,))]
|
||||||
|
return self._mt_call(run)
|
||||||
|
|
||||||
|
def get_meeting_task(self, *, item_id: int) -> dict[str, Any] | None:
|
||||||
|
def run() -> dict[str, Any] | None:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
rows = self._mt_select(conn, "m.id = %s", (item_id,))
|
||||||
|
return self._mt_row(rows[0]) if rows else None
|
||||||
|
return self._mt_call(run)
|
||||||
|
|
||||||
|
def add_meeting_task(self, *, week_start: date, fields: dict[str, Any], by: str = "",
|
||||||
|
task_id: int | None = None) -> dict[str, Any]:
|
||||||
|
"""줄 추가(빈 줄도). task_id = 예전 브라우저 표에서 옮겨 온 이미 등록된 줄."""
|
||||||
|
who = store.norm_str(by, lower=True)
|
||||||
|
|
||||||
|
def run() -> int:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
self._check_meeting_open(conn, week_start)
|
||||||
|
clean = self._mt_clean(conn, fields)
|
||||||
|
nxt = conn.execute("SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM goal_meeting_tasks "
|
||||||
|
"WHERE week_start = %s", (week_start,)).fetchone()["n"]
|
||||||
|
cols = ["week_start", "sort_order", "title", "assignee_email", "project_id", "stage_id", "task_id",
|
||||||
|
"created_by", "updated_by"]
|
||||||
|
vals = [week_start, int(nxt), clean.get("title", ""), clean.get("assignee_email", ""),
|
||||||
|
clean.get("project_id"), clean.get("stage_id"), task_id, who, who]
|
||||||
|
if clean.get("parent_task_id") is not None:
|
||||||
|
cols.append("parent_task_id")
|
||||||
|
vals.append(clean["parent_task_id"])
|
||||||
|
return int(conn.execute(
|
||||||
|
f"INSERT INTO goal_meeting_tasks ({', '.join(cols)}) VALUES ({', '.join(['%s'] * len(cols))}) "
|
||||||
|
"RETURNING id", vals,
|
||||||
|
).fetchone()["id"])
|
||||||
|
return self.get_meeting_task(item_id=self._mt_call(run)) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def update_meeting_task(self, *, item_id: int, fields: dict[str, Any], by: str = "") -> dict[str, Any]:
|
||||||
|
"""[적용] 전 줄만 고친다(줄을 잠그고 — 다른 사람이 막 [적용]한 줄은 409). 회의 완료된 주차면 잠금."""
|
||||||
|
def run() -> None:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute("SELECT week_start, project_id, task_id FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||||
|
(item_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
self._check_meeting_open(conn, row["week_start"])
|
||||||
|
if row["task_id"] is not None:
|
||||||
|
raise store.GoalCellConflict("이미 [적용]해 업무로 만든 줄입니다. 새로고침해 주세요.")
|
||||||
|
clean = self._mt_clean(conn, fields, project_id=row["project_id"])
|
||||||
|
if not clean:
|
||||||
|
return
|
||||||
|
sets = ", ".join(f"{k} = %s" for k in clean)
|
||||||
|
conn.execute(f"UPDATE goal_meeting_tasks SET {sets}, updated_by = %s, updated_at = now() WHERE id = %s",
|
||||||
|
(*clean.values(), store.norm_str(by, lower=True), item_id))
|
||||||
|
self._mt_call(run)
|
||||||
|
return self.get_meeting_task(item_id=item_id) # type: ignore[return-value]
|
||||||
|
|
||||||
|
def delete_meeting_task(self, *, item_id: int) -> dict[str, Any]:
|
||||||
|
"""줄 지우기. 만든 작업은 라우터·화면이 따로 지운다(휴지통)."""
|
||||||
|
def run() -> dict[str, Any]:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||||
|
(item_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
self._check_meeting_open(conn, row["week_start"])
|
||||||
|
conn.execute("DELETE FROM goal_meeting_tasks WHERE id = %s", (item_id,))
|
||||||
|
return self._mt_row(row)
|
||||||
|
return self._mt_call(run)
|
||||||
|
|
||||||
|
# [적용] 때 라우터가 권한·담당자를 확인한 줄 값 — 잠근 뒤 이 값이 그대로여야 만든다(그사이 고쳐졌으면 409)
|
||||||
|
MT_APPLY_KEYS = ("title", "project_id", "stage_id", "assignee_email", "parent_task_id")
|
||||||
|
|
||||||
|
def apply_meeting_task(self, *, item_id: int, task_fields: dict[str, Any] | None,
|
||||||
|
expect: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool, dict[str, Any] | None]:
|
||||||
|
"""[적용] — 줄을 잠그고 아직 업무가 없을 때만 업무를 만들어 task_id 를 남긴다. **업무 INSERT 와 줄 연결이 같은 연결·
|
||||||
|
같은 트랜잭션**이라(2026-10-15 검토 F02) 연결 기록이 실패하면 업무도 롤백되고, 재시도·동시 클릭에도 업무는 하나다.
|
||||||
|
트랜잭션 안에서는 이 연결 하나만 쓴다(같은 풀의 다른 연결을 기다리지 않음).
|
||||||
|
|
||||||
|
task_fields = _insert_task 인자(라우터가 잠그기 전에 권한·담당자를 확인해 만든 값, project_id·parent_task_id 포함).
|
||||||
|
expect = 그 확인에 쓴 줄(get_meeting_task) — 잠근 줄의 MT_APPLY_KEYS 가 다르면 GoalCellConflict(다시 [적용]).
|
||||||
|
작업 칸(parent_task_id)이면 그 업무의 세부 업무(섹션 없음) — 상위 업무가 같은 프로젝트에 아직 있는지 잠근 뒤 다시 본다.
|
||||||
|
돌려주는 값: (줄, 이번에 만들었는가, 만든 업무|None). 알림·메일은 라우터가 커밋 뒤에."""
|
||||||
|
def run() -> tuple[int, bool, tuple[int, Any] | None]:
|
||||||
|
with self._mt_conn() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
row = conn.execute(f"SELECT {self._mt_cols(conn)} FROM goal_meeting_tasks WHERE id = %s FOR UPDATE",
|
||||||
|
(item_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise KeyError(item_id)
|
||||||
|
self._check_meeting_open(conn, row["week_start"])
|
||||||
|
if row["task_id"] is not None:
|
||||||
|
return item_id, False, None
|
||||||
|
use = self._mt_row(row)
|
||||||
|
if task_fields is None or (expect is not None and any(
|
||||||
|
use.get(k) != expect.get(k) for k in self.MT_APPLY_KEYS)):
|
||||||
|
raise store.GoalCellConflict("그사이 줄이 바뀌었습니다. 새로고침한 뒤 다시 [적용]해 주세요.")
|
||||||
|
parent_task = use.get("parent_task_id")
|
||||||
|
if parent_task is not None:
|
||||||
|
t = conn.execute("SELECT project_id FROM tasks WHERE id = %s", (parent_task,)).fetchone()
|
||||||
|
if t is None or use["project_id"] is None or int(t["project_id"]) != int(use["project_id"]):
|
||||||
|
raise ValueError("고른 업무가 없어졌거나 다른 프로젝트로 옮겨졌습니다. 업무 칸을 다시 고르세요.")
|
||||||
|
task_row, done_at = self._insert_task(conn, **task_fields)
|
||||||
|
conn.execute("UPDATE goal_meeting_tasks SET task_id = %s, updated_at = now() WHERE id = %s",
|
||||||
|
(int(task_row["id"]), item_id))
|
||||||
|
return item_id, True, (int(task_row["id"]), done_at)
|
||||||
|
iid, made, info = self._mt_call(run)
|
||||||
|
task = None
|
||||||
|
if info is not None:
|
||||||
|
task = self.get_task(task_id=info[0])
|
||||||
|
task["_newly_completed"] = info[1] is not None
|
||||||
|
return self.get_meeting_task(item_id=iid), made, task # type: ignore[return-value]
|
||||||
|
|
||||||
def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
|
def goal_month_targets(self, *, year: int, month: int) -> dict[str, Any]:
|
||||||
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
|
"""회의록 머리 — 그 달 매출 목표·실적, 로아스 목표(목표 표 숫자), 매출 단위. 목표 표가 없으면 빈 값."""
|
||||||
with self._pool.connection() as conn:
|
with self._pool.connection() as conn:
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ko">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>DBX</title>
|
||||||
|
<style>
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;font-family:"맑은 고딕","Malgun Gothic",-apple-system,sans-serif;background:#f4f5f7;color:#222;line-height:1.75}
|
||||||
|
.top{position:sticky;top:0;z-index:10}
|
||||||
|
header{display:flex;align-items:center;justify-content:space-between;background:#1f2937;color:#fff;padding:14px 24px;font-size:22px;font-weight:700}
|
||||||
|
.close{border:1px solid rgba(255,255,255,.35);background:transparent;color:#fff;font-size:14px;font-weight:600;padding:6px 16px;border-radius:6px;cursor:pointer;font-family:inherit}
|
||||||
|
.close:hover{background:rgba(255,255,255,.12)}
|
||||||
|
nav{position:relative;display:flex;flex-wrap:wrap;gap:4px;background:#fff;padding:8px 16px;border-bottom:1px solid #ddd}
|
||||||
|
/* 탭 — Project 뷰 탭(보드/목록/…)처럼 고른 탭 뒤 옅은 보라 사각형이 새 탭으로 미끄러진다 */
|
||||||
|
.tab{position:relative;z-index:1;border:none;background:none;padding:8px 14px;border-radius:6px;font-size:15px;font-weight:600;cursor:pointer;color:#6b7280;font-family:inherit;transition:color .2s}
|
||||||
|
.tab:hover{color:#1e1f21}
|
||||||
|
.tab.active{color:#1e1f21}
|
||||||
|
.tab-hl{position:absolute;top:0;left:0;z-index:0;background:#ebe8fd;border-radius:6px;pointer-events:none;
|
||||||
|
transition:transform .22s cubic-bezier(.4,0,.2,1),width .22s cubic-bezier(.4,0,.2,1),height .22s cubic-bezier(.4,0,.2,1)}
|
||||||
|
.tab-hl.no-anim{transition:none}
|
||||||
|
main{max-width:860px;margin:24px auto;padding:0 16px}
|
||||||
|
.panel{display:none;background:#fff;border-radius:12px;padding:28px 32px;box-shadow:0 2px 8px rgba(0,0,0,.06)}
|
||||||
|
.panel.active{display:block;animation:fade .25s}
|
||||||
|
@keyframes fade{from{opacity:0}to{opacity:1}}
|
||||||
|
h2{margin-top:0;font-size:24px;border-left:5px solid #2563eb;padding-left:12px}
|
||||||
|
h3{margin:28px 0 8px;font-size:18px;color:#1e40af}
|
||||||
|
p{margin:0 0 18px}
|
||||||
|
.video{position:relative;padding-top:56.25%;margin:16px 0 8px;border-radius:10px;overflow:hidden;background:#000}
|
||||||
|
.video iframe{position:absolute;inset:0;width:100%;height:100%}
|
||||||
|
.yt-link{display:flex;align-items:center;gap:12px;margin-bottom:20px;text-decoration:none;color:#c00;font-size:14px}
|
||||||
|
.yt-link img{width:120px;border-radius:6px}
|
||||||
|
/* 형광펜 — 노랑 음영 */
|
||||||
|
mark{background:#fff35c;color:inherit;padding:1px 2px;border-radius:2px;-webkit-box-decoration-break:clone;box-decoration-break:clone}
|
||||||
|
b{font-weight:700}
|
||||||
|
.photo{display:block;max-width:100%;height:auto;margin:12px 0 8px;border-radius:10px}
|
||||||
|
.link-card{display:block;padding:12px 16px;margin:12px 0 20px;background:#eef2ff;border-radius:8px;color:#1e40af;text-decoration:none;word-break:break-all;font-size:14px}
|
||||||
|
.link-card:hover .news-title{text-decoration:underline}
|
||||||
|
.news-title{display:block;margin-top:10px;padding-top:10px;border-top:1px solid #c7d2fe;font-size:18px;font-weight:700;line-height:1.5;color:#111827;word-break:keep-all}
|
||||||
|
.news-sub{display:block;margin-top:2px;font-size:15px;color:#374151;word-break:keep-all}
|
||||||
|
.news-src{display:block;margin-top:4px;font-size:13px;color:#6b7280}
|
||||||
|
@media(max-width:600px){.panel{padding:20px}.tab{padding:10px 12px;font-size:14px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="top">
|
||||||
|
<header>DBX<button type="button" class="close" onclick="window.close()">닫기</button></header>
|
||||||
|
<nav role="tablist">
|
||||||
|
<button class="tab active" data-i="0" role="tab">DBX 존재이유</button>
|
||||||
|
<button class="tab" data-i="3" role="tab">일을 잘한다는 것</button>
|
||||||
|
<button class="tab" data-i="4" role="tab">일 못하는 사람 특징</button>
|
||||||
|
<button class="tab" data-i="2" role="tab">부자/성공</button>
|
||||||
|
<button class="tab" data-i="5" role="tab">마케팅?</button>
|
||||||
|
<button class="tab" data-i="1" role="tab">인생을 결정하는 단 1가지</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
<main>
|
||||||
|
<section class="panel active" id="p0" role="tabpanel">
|
||||||
|
<h2>DBX 존재이유 / 일하는 법</h2>
|
||||||
|
<p>회사의 존재이유 :<br>구성원의 지속 가능 행복실현 / <mark>일 자체가 재미있는 사람들의 채용</mark> / 선별 1순위<br>what? 우리만의 제품으로<br>how? 강력한 콘텐츠로</p>
|
||||||
|
<p>집착 / 몰입 / 고성과<br>=>커머스 선두주자를 학습하고 기존 성과 난 자사 콘텐츠 <mark>학습하며(80%)</mark><br><mark>우리만의 콘텐츠(20%)</mark>를 끊임없이 <mark>빠른 속도로 테스트</mark>합니다.</p>
|
||||||
|
<p>고성과 콘텐츠 인사이트 학습(잘하는 경쟁사)<br>끊임없는 시도 끝 우리만의 mim 탄생<br>必!!!) 잘하고 있는(성장 중인) 회사 브랜드 콘텐츠 참고할 것<br>최근 눈여겨볼 브랜드들 직원들이 업데이트할 수 있게 해야 함</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" id="p1" role="tabpanel">
|
||||||
|
<h2>인생을 결정하는 단 1가지</h2>
|
||||||
|
<p>같은 라면 가게에서 일을 해도<br>누구는 가게를 물려받는데</p>
|
||||||
|
<p>누구는 도대체 왜?<br>무엇 때문에?<br>몇 년째 불평불만하며<br>파만 썰고 있을까요??</p>
|
||||||
|
<p>똑같은 직장에서 함께 시작했어도<br>누구는 1~2년 만에 연봉도 오르고<br>없어서는 안 될 중요한 존재가 되는데</p>
|
||||||
|
<p>누구는 있으나 없으나....<br>오히려 없는 게 낫다는 생각이 들게 하는<br>계륵 같은 존재가 될까요????</p>
|
||||||
|
<p>학벌, 인맥, 물려받은 재산?</p>
|
||||||
|
<div class="video"><iframe src="https://www.youtube.com/embed/Ttwoztq_-Bw" title="YouTube video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
|
||||||
|
<a class="yt-link" href="https://www.youtube.com/watch?v=Ttwoztq_-Bw" target="_blank" rel="noopener"><img src="https://img.youtube.com/vi/Ttwoztq_-Bw/hqdefault.jpg" alt=""><span>▶ YouTube에서 보기</span></a>
|
||||||
|
<p>모든 건 태도에서부터 옵니다.</p>
|
||||||
|
<p>두 사람이 똑같이 오프라인 매장에서 물건을 팔았습니다.<br>10년 후 아직도 판매직을 전전하며<br>불평불만에 가득한 A<br>일 많이 시키고 복지도 꽝이고<br>업무 환경도 XX 같다고 신세 한탄만 하는 A</p>
|
||||||
|
<p>고객 하나하나<br>성심성의껏 응대하며 최선을 다해<br>친절하게 고객을 만족시킨 B<br>우연히 매장을 찾은 굴지의 기업 대표님이 감동하여<br>상품개발자로 발탁.</p>
|
||||||
|
<p>10년 만에 임원으로 승진한 B(저의 지인입니다)</p>
|
||||||
|
<a class="link-card" href="https://www.econovill.com/news/articleView.html?idxno=560001" target="_blank" rel="noopener">🔗 https://www.econovill.com/news/articleView.html?idxno=560001
|
||||||
|
<strong class="news-title">[ER초대석] “제네시스 G90, 향기로 가치를 더하다”</strong>
|
||||||
|
<span class="news-sub">경규혜 센트온 책임 “향기, 완성차 차별화 소재로 부상”</span>
|
||||||
|
<span class="news-src">이코노믹리뷰 · 2022.01.08</span></a>
|
||||||
|
<p>당신의 10년 후.<br>오늘의 당신 태도가 만들고 있습니다.</p>
|
||||||
|
<p>우연을 가장한 절호의 기회<br>얼마나 놓치고 있나요?</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" id="p2" role="tabpanel">
|
||||||
|
<h2>부자/성공</h2>
|
||||||
|
<p>누구나 다 부자가 되고 싶어 합니다.<br>저보고도 어떻게 단기간에 매출을 올릴 수 있는지<br>어떻게 직장 생활에서 30대에 1억 연봉에 도달하는지 많은 분들이 묻습니다.</p>
|
||||||
|
<p>당신은 얼마나 많은 시도를 하고 얼마나 많은 성공과 실패를 했나요???<br>오늘 최선을 다해 노력하고 성과를 위해 집착하고 있나요???<br>저는 밤을 새워 일한 적도 있고<br>새벽 3시에 뛰쳐나간 적도 있으며<br>물에 잠긴 회사 자산을 위해 밤새 물을 퍼낸 적도 있습니다.<br>연휴 기간에 일한 적은 셀 수도 없으며<br>정당하게 일한 이유로 부당하게 회사에서 잘린 적도 있습니다.</p>
|
||||||
|
<p>십수 개의 브랜드를 만들었고 끊임없는 성공과 실패를 통해<br>무엇을 해야 하는지 무엇을 하면 안 되는지 경험으로, 학습으로 익혔고<br>지금도 배우고 있습니다.</p>
|
||||||
|
<p>우리나라 수능에서 1등급(상위 3%)을 받으려면 12년의 교육 과정이 필요합니다.<br>며칠 숫자 배운 사람에게 1등급은 불가능하지요<br>어떤 문제든 풀 수 있는 능력을 키우려면 수십 수백 수천 시간의<br>노력과 학습이 필요합니다.</p>
|
||||||
|
<p>그렇다면 상품, 마케팅으로 100억을 벌려면 얼마만큼의 노력이 필요할까요?</p>
|
||||||
|
<p>지난 것은 필요 없습니다.</p>
|
||||||
|
<p>오늘, 지금 당신은 무엇을 하고 있나요??</p>
|
||||||
|
<p>당신의 오늘이 당신의 차와 집, 아이의 학교, 아내가 당신을 바라보는 눈빛을 만들고 있습니다.</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" id="p3" role="tabpanel">
|
||||||
|
<h2>일을 잘한다는 것</h2>
|
||||||
|
<p><b>일을 잘한다 = 문제해결능력이 뛰어나다는 것</b></p>
|
||||||
|
<p>문제해결 능력이 뛰어나기 위해선<br>간절한 몰입과 끊임없는 시도를 통한 경험이 축적되어야 합니다.</p>
|
||||||
|
<p>영화 '타짜'에서 고니가 평경장에게 배워 최고의 타짜가 되는 과정,<br>영화 위플래쉬 등.(타짜, 위플래쉬 꼭 보세요)</p>
|
||||||
|
<p>비유하자면 수능에서 4점짜리 킬러문항의 경우,<br>대부분의 경우 어디서부터 어떻게 접근해야 하는지조차 가늠하기 어렵지만,<br>낮은 단계에서부터 실력을 쌓고-바로 정답 보지 말고-몇 시간이고 며칠이고 고민을 하며 문제해결을 했을 때 실력이 쌓이게 됩니다.</p>
|
||||||
|
<p>이러한 문제들은 공식이 3-4개가 순차적으로 밑에서 풀어와야 하는데,<br>어디서부터 접근을 해야 하는지가 중요하기 때문이지요.</p>
|
||||||
|
<p>이렇게 몰입해 해결하다 보면 처음엔 며칠이 걸리지만,<br>결국 수능 시험장에서는 10분 내로 풀 수 있는 경지에 이르게 됩니다.</p>
|
||||||
|
<p>십수 년 있다 보니, 모든 업무에서 일을 잘하는 사람도 같은 패턴입니다.</p>
|
||||||
|
<p><b>이것이 최선의 방법인지, 옳은 접근인지 습관적으로 의문을 던져야 한다.</b><br>대부분의 사람은 주어진 방법에 의문을 갖지 않고...<br>주어진 매뉴얼과 시킨 방법으로 최선을 다합니다.<br>"원래 그래"라고 하며 관습적으로 일을 하지요<br>이렇게 해서는 절대 근본적인 문제해결은 불가능합니다.</p>
|
||||||
|
<h3>2. 몰입의 시간이 필요하다 (축적의 시간)</h3>
|
||||||
|
<p>문제 해결을 위해 몇 시간 며칠 머릿속에서 빼지 않고 계속 생각해야 합니다.<br>그러다 보면 어느 순간 우연히 해결방법을 찾게 됩니다.<br>누군가 이 문제에 대해 해결방법을 알고 있을 수 있고, 간단한 질문으로 해결되는 경우도 있습니다. 몰입하지 않으면 이런 실마리가 나올 리가 없죠<br>성과지표의 혁신은 여기에서 시작됩니다.</p>
|
||||||
|
<h3>3. why를 통해 depth를 몇 단계 내려가야 한다.</h3>
|
||||||
|
<p>어렵고 복잡한 문제일수록 문제의 원인이 깊게 숨어 있습니다.<br>5depth까지는 내려가서 그 깊숙한 문제부터 순차적으로 해결해야 표면적인 문제가 해결되는 경우가 많죠</p>
|
||||||
|
<p>문제 : 로아스가 나오지 않는다.<br>1depth : 콘텐츠 잘 만드는 브랜드의 것을 차용한다.<br>2depth : 상세페이지를 바꾼다<br>3depth : 콘텐츠 양을 늘린다.<br>4depth : 콘텐츠 잘 만드는 사람 채용을 한다.<br>5depth : 실패를 하더라도 우리만의 콘텐츠를 지속적으로 생산한다.<br>=>로아스 500% 달성.</p>
|
||||||
|
<p>단순히 대부분의 브랜드들은 1depth에서 끝이 나지만...<br>그러나 기존에 사람들은 왜 우리 걸 샀지??? 이들이 원하는 메시지는??<br>누가 무엇을 어떻게 해야 하나??<br>끊임없는 몰입 > 시도를 통해 직접 컨택한 재구매자들의 정기적인 출연을 통해<br>획기적인 로아스를 달성할 수 있었습니다.<br>(많은 브랜드에서 우리를 차용하나 선점 효과로 인해 우리와 같은 성과는 나오지 않음)</p>
|
||||||
|
<h3>4. 안되는 것은 없다.</h3>
|
||||||
|
<p>대기업에서 미디어 커머스로 이직했을 때,<br>3달 안에 10억을 만드는 미션을 받았습니다.<br>실제 해당기업 인사팀에서도 불가능하다고 혀를 내둘렀으나,<br>10억 훨씬 넘는 매출을 2달 만에 달성했습니다.</p>
|
||||||
|
<p>3일 밤을 새워 되는 방법 a, b, c를 뽑아내고 으쌰으쌰 파이팅 넘치는 조직을 만들고<br>즉시 실행했습니다. (안 된다, 부정적인 마인드 가진 직원부터 솎아내야 함)</p>
|
||||||
|
<p>일 잘하는 팀장이 입사하면(나도 그랬다) 조직부터 휘어잡습니다.<br>나이브한 팀원은 내보내고 본인의 파이팅을 서포트할 수 있는 팀원부터 구성하죠<br>기존에 있던 회사에서 데리고 오기도 하고, 타깃 회사에서 부족한 부분의 경력직도 채우는 것부터 시작합니다<br>최적의 상황을 만들고 본격적으로 달립니다. 되도록 구조를 만들고 시작하는 것이 핵심입니다.</p>
|
||||||
|
<p>단순히 열심히 한다고 생산성이 2배 3배 올라가지 않습니다.<br>구조부터 해결해야 합니다. 매우 고난도의 능력이며, 시장에서 그런 능력을 가진 사람은 매우 귀합니다.<br>그리고 그런 사람은 뭘하든 어떤 조직에서는 심장이 되지요.</p>
|
||||||
|
<p><b><mark>조직에서 당신은 계륵입니까 심장입니까??</mark></b></p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" id="p4" role="tabpanel">
|
||||||
|
<h2>일 못하는 사람 특징</h2>
|
||||||
|
<p>13년 직장 생활과<br>5년의 사업을 하며 수많은 사람을 만났습니다.</p>
|
||||||
|
<p>어떤 사람은 아무 경력 없이 입사를 해서<br>적응하고-성과내고-리더십까지 발휘해<br>누구나 다 원하는 사람이 되어있고</p>
|
||||||
|
<p>어떤 사람은 수년 수십 년 동안 그 자리에 머물러 있는 사람도 있죠.</p>
|
||||||
|
<p>모두가 다 그런 것은 아니지만 일 못하는 사람의 특징은 아래와 같습니다.</p>
|
||||||
|
<p>자신을 높게 평가한다.<br>"당신은 특별하지 않습니다."<br>이상하게 일 잘하는 사람은 자신을 낮춘다.<br>아직도 배울 게 많고 아직도 못하는 일이 많은데 잘난 게 없다고 스스로를 평가합니다.</p>
|
||||||
|
<h3>2. 타인에 대한 무관심</h3>
|
||||||
|
<p>우리 영역에서 가장 중요한 것은 고객의 마음을 읽는 것입니다.<br>고객이 무엇을 좋아하는지, 어떤 제품을, 어떤 채널에서, 어떤 메시지를 들어야<br>구매 전환으로 이어지는지 연결하고 추적하고 가설을 세우고 입증하는 능력이 필요합니다.</p>
|
||||||
|
<p>여기서 소위 '멘탈이 좋다는' 사람들이 있는데,<br>멘탈이 좋다는 것은 타인의 피드백에 무감각하다는 말이기도 합니다.<br>다른 이의 의견에 무감각하고 모든 중심은 본인에게 나오고 (정말 답답하다)<br>본인 생각만 중요시하고 있습니다.</p>
|
||||||
|
<p>회사 내에서 실수해서 혼날 때 표정을 보면 일 못하는 사람임을 단박에 알 수 있다<br>한 귀로 듣고 한 귀로 흘리는 그 표정.</p>
|
||||||
|
<p>기획이든 cs든 마케팅이든 영업이든 모든 것을 고객이 준다는 것이 핵심인데<br>평소에 타인에게 무관심하고 본인 중심적이니</p>
|
||||||
|
<p>당연히 능력이 없을 수밖에....</p>
|
||||||
|
<h3>3. 본인만의 근거 없는 고집(뇌피셜)</h3>
|
||||||
|
<p>짬도 안 되고 똑똑하지도 않은데 본인이 생각한 부분에 대한 확고한 고집이 있습니다.<br>유연하게 사고하고, 타인의 의견과 시장의 흐름을 읽고 유연하게 대처하는 능력이 필요합니다.<br>그런데 본인이 명확하게 저는 000하고 싶어요 000해야한다고 생각해요 라는<br>본인 상상을 통해 나온 것을 주장하는 사람들이 있습니다.</p>
|
||||||
|
<p>그것은 숫자나 목표가 아니라 방향성에 관한 것인데,</p>
|
||||||
|
<p>반복된 성공 실패를 통해 학습하지도 않았고,<br>구체적인 숫자를 근거로 얘기하는 것도 아닌 것은<br>그냥 본인 뇌피셜일 뿐 그 누구의 지지도 받기 어려우니<br>이런 사람들은 결국 회사에 불만이 많고,<br>타인에게 본인이 욕먹는 원인을 외부로 돌리는 경우가 많습니다.</p>
|
||||||
|
<p>유연하게 생각하는 태도가 중요합니다.<br>모든 부분에서의 유연성이 아니라 시장에 관해선 보다 높은 정보나 수준 높은 사람의 정보를 들으면<br>받아들이는 태도가 필요합니다.</p>
|
||||||
|
</section>
|
||||||
|
<section class="panel" id="p5" role="tabpanel">
|
||||||
|
<h2>마케팅?</h2>
|
||||||
|
<p>선택과 집중<br>바로척 병원 = 정형외과와 내과를 하지만,<br>광고 홍보, 브랜드화는 척추 병원, 선택 집중으로 보여 줍니다<br>척추 병원들 중에서도, 허리, 목 등의 부위 특화가 아니라, 속도와 통증입니다,</p>
|
||||||
|
<p>더 잘 더 제대로 더 싸게 고친다고 하지 않고, 더 안 아프고, 더 빠르게...</p>
|
||||||
|
<p>이제 어느 병원을 가든, 고치는 것은 그리 차이 없고, 기술과 서비스의 상향 평준화,</p>
|
||||||
|
<h3>1. 스쳐 지나만 봐도 뇌리에 박히는 컨셉</h3>
|
||||||
|
<h3>2. 키컬러 폰트의 적절함</h3>
|
||||||
|
<img class="photo" src="/static/dbx/inline.jpg?v=20261015" alt="연세바로척병원 건물 외벽 광고 — 반반하다 바로척! 아픔 반! 시간 반!" loading="lazy">
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
const nav=document.querySelector('nav'),hl=document.createElement('span');
|
||||||
|
hl.className='tab-hl';nav.insertBefore(hl,nav.firstChild);
|
||||||
|
// 고른 탭 위치·크기로 사각형을 옮긴다(탭이 두 줄로 접혀도 위아래까지 따라감). animate=false 는 즉시.
|
||||||
|
function moveHl(animate){
|
||||||
|
const a=nav.querySelector('.tab.active');if(!a)return;
|
||||||
|
if(!animate)hl.classList.add('no-anim');
|
||||||
|
hl.style.width=a.offsetWidth+'px';hl.style.height=a.offsetHeight+'px';
|
||||||
|
hl.style.transform='translate('+a.offsetLeft+'px,'+a.offsetTop+'px)';
|
||||||
|
if(!animate){void hl.offsetWidth;hl.classList.remove('no-anim');}
|
||||||
|
}
|
||||||
|
document.querySelectorAll('.tab').forEach(b=>b.addEventListener('click',()=>{
|
||||||
|
document.querySelectorAll('.tab,.panel').forEach(e=>e.classList.remove('active'));
|
||||||
|
b.classList.add('active');document.getElementById('p'+b.dataset.i).classList.add('active');window.scrollTo({top:0});
|
||||||
|
moveHl(true);
|
||||||
|
}));
|
||||||
|
moveHl(false);
|
||||||
|
window.addEventListener('resize',()=>moveHl(false));
|
||||||
|
document.fonts&&document.fonts.ready.then(()=>moveHl(false));
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+450
-57
@@ -86,6 +86,19 @@ def _require_user(request: Request) -> dict[str, Any]:
|
|||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _page_user(request: Request) -> Any:
|
||||||
|
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
|
||||||
|
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
|
||||||
|
from urllib.parse import quote # noqa: WPS433
|
||||||
|
|
||||||
|
from app.main import get_current_user_record # noqa: WPS433
|
||||||
|
|
||||||
|
if get_current_user_record(request) is None:
|
||||||
|
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
||||||
|
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
||||||
|
return _require_user(request)
|
||||||
|
|
||||||
|
|
||||||
def _require_pro(request: Request) -> dict[str, Any]:
|
def _require_pro(request: Request) -> dict[str, Any]:
|
||||||
"""Pro user 이상(수퍼관리자·Admin·Pro user) — access.is_pro."""
|
"""Pro user 이상(수퍼관리자·Admin·Pro user) — access.is_pro."""
|
||||||
user = _require_user(request)
|
user = _require_user(request)
|
||||||
@@ -130,15 +143,15 @@ def _accessible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
|||||||
return access.visible_project_ids(st, user)
|
return access.visible_project_ids(st, user)
|
||||||
|
|
||||||
|
|
||||||
_TASK_DENIED = "이 작업을 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요."
|
_TASK_DENIED = "이 업무를 볼 권한이 없습니다. 프로젝트 관리자에게 멤버 배정을 요청하세요."
|
||||||
_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 작업이라 읽기만 할 수 있습니다. "
|
_TASK_READ_ONLY = ("다른 프로젝트에서 연결된 업무라 읽기만 할 수 있습니다. "
|
||||||
"변경은 원 소속 프로젝트 멤버만 할 수 있습니다.")
|
"변경은 원 소속 프로젝트 멤버만 할 수 있습니다.")
|
||||||
|
|
||||||
|
|
||||||
def _task_or_404(st: Any, task_id: int) -> dict[str, Any]:
|
def _task_or_404(st: Any, task_id: int) -> dict[str, Any]:
|
||||||
task = st.get_task(task_id=task_id)
|
task = st.get_task(task_id=task_id)
|
||||||
if task is None:
|
if task is None:
|
||||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||||
return task
|
return task
|
||||||
|
|
||||||
|
|
||||||
@@ -394,7 +407,7 @@ def _notify_completed(
|
|||||||
subject=store.build_subject_completed(project_name=project_name, task_title=task["title"]),
|
subject=store.build_subject_completed(project_name=project_name, task_title=task["title"]),
|
||||||
body=(
|
body=(
|
||||||
f"프로젝트: {project_name}\n"
|
f"프로젝트: {project_name}\n"
|
||||||
f"완료된 작업: {task['title']}\n"
|
f"완료된 업무: {task['title']}\n"
|
||||||
f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n"
|
f"담당자: {task.get('assignee_name') or task.get('assignee_email') or '-'}\n"
|
||||||
f"완료 처리: {actor}\n"
|
f"완료 처리: {actor}\n"
|
||||||
),
|
),
|
||||||
@@ -402,7 +415,7 @@ def _notify_completed(
|
|||||||
_inbox(
|
_inbox(
|
||||||
st, recipients=_task_recipients(st, project, task, exclude=actor),
|
st, recipients=_task_recipients(st, project, task, exclude=actor),
|
||||||
actor=actor, project_id=task["project_id"], task_id=task["id"],
|
actor=actor, project_id=task["project_id"], task_id=task["id"],
|
||||||
ntype="completed", title=f"작업 완료: {task['title']}", body=project_name,
|
ntype="completed", title=f"업무 완료: {task['title']}", body=project_name,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -636,7 +649,9 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
|||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _render_config_needed(request, user)
|
return _render_config_needed(request, user)
|
||||||
@@ -667,8 +682,8 @@ def my_tasks_page(request: Request) -> HTMLResponse:
|
|||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user),
|
||||||
"nav_items": build_erp_nav(user, active="project"),
|
"nav_items": build_erp_nav(user, active="project"),
|
||||||
"page_title": "내 작업",
|
"page_title": "내 업무",
|
||||||
"page_subtitle": "내가 담당자인 작업을 한 곳에서 봅니다.",
|
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
|
||||||
"force_sidebar_collapsed": True,
|
"force_sidebar_collapsed": True,
|
||||||
"nav_projects": nav_projects,
|
"nav_projects": nav_projects,
|
||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
@@ -728,11 +743,11 @@ def task_permalink(request: Request, task_id: int):
|
|||||||
|
|
||||||
task = st.get_task(task_id=task_id)
|
task = st.get_task(task_id=task_id)
|
||||||
if task is None:
|
if task is None:
|
||||||
return _denied("작업을 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
|
return _denied("업무를 찾을 수 없습니다. 삭제되었을 수 있습니다.", 404)
|
||||||
target = _task_open_project(st, user, task)
|
target = _task_open_project(st, user, task)
|
||||||
if target is None:
|
if target is None:
|
||||||
return _denied(
|
return _denied(
|
||||||
"이 작업이 속한 프로젝트의 멤버만 볼 수 있습니다. "
|
"이 업무가 속한 프로젝트의 멤버만 볼 수 있습니다. "
|
||||||
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
|
||||||
403,
|
403,
|
||||||
)
|
)
|
||||||
@@ -764,7 +779,9 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
|||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _render_config_needed(request, user)
|
return _render_config_needed(request, user)
|
||||||
@@ -882,6 +899,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
|||||||
{
|
{
|
||||||
"user": user,
|
"user": user,
|
||||||
**_role_ctx(user),
|
**_role_ctx(user),
|
||||||
|
"pj_options": _project_options(st),
|
||||||
"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"],
|
||||||
@@ -950,6 +968,43 @@ def _db_or_503(request: Request) -> Any:
|
|||||||
return st
|
return st
|
||||||
|
|
||||||
|
|
||||||
|
def _project_options(st: Any) -> dict[str, Any]:
|
||||||
|
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
|
||||||
|
if st is None:
|
||||||
|
return store.normalize_project_options(None)
|
||||||
|
try:
|
||||||
|
return store.normalize_project_options(st.get_project_options())
|
||||||
|
except Exception: # noqa: BLE001 — 옵션 때문에 프로젝트 화면이 안 열리면 안 된다
|
||||||
|
logger.warning("Project 옵션 읽기 실패 — 기본값 사용", exc_info=True)
|
||||||
|
return store.normalize_project_options(None)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/options")
|
||||||
|
def api_get_options(request: Request) -> JSONResponse:
|
||||||
|
"""Project 옵션 창 — 시스템 전체 설정(모든 사용자에게 적용)과 내가 바꿀 수 있는지(Admin 이상)."""
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
return JSONResponse({"options": _project_options(st), "can_edit": access.is_project_admin(user)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/options")
|
||||||
|
def api_put_options(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""시스템 Project 옵션 저장 — 수퍼관리자·Admin 만. 보낸 키만 바꾼다. 029 미적용이면 503."""
|
||||||
|
user = _require_user(request)
|
||||||
|
if not access.is_project_admin(user):
|
||||||
|
raise HTTPException(status_code=403, detail="수퍼관리자·Admin 만 바꿀 수 있습니다.")
|
||||||
|
st = _db_or_503(request)
|
||||||
|
try:
|
||||||
|
values = store.validate_project_options(payload)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
try:
|
||||||
|
st.set_project_options(values=values, updated_by=user.get("email", ""))
|
||||||
|
except UndefinedTable:
|
||||||
|
raise HTTPException(status_code=503, detail="DB 마이그레이션 029(Project 옵션)가 아직 적용되지 않았습니다.")
|
||||||
|
return JSONResponse({"options": _project_options(st)})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/projects")
|
@router.get("/api/projects")
|
||||||
def api_list_projects(request: Request) -> JSONResponse:
|
def api_list_projects(request: Request) -> JSONResponse:
|
||||||
user = _require_user(request)
|
user = _require_user(request)
|
||||||
@@ -1448,6 +1503,18 @@ def api_my_tasks(request: Request) -> JSONResponse:
|
|||||||
return JSONResponse({"tasks": _my_visible_tasks(st, user)})
|
return JSONResponse({"tasks": _my_visible_tasks(st, user)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/my-overdue")
|
||||||
|
def api_my_overdue(request: Request) -> JSONResponse:
|
||||||
|
"""마감이 지난 내 미완료 업무(마감일이 오늘(한국시간) 이전) — ERP 모든 화면 위쪽 알림(static/erp-overdue.js)이 쓴다.
|
||||||
|
지금 볼 수 있는 업무만, 마감이 오래된 것부터."""
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
today = today_kst()
|
||||||
|
rows = access.filter_visible_tasks(st, user, st.list_my_overdue(assignee_email=user["email"], today=today))
|
||||||
|
keys = ("id", "title", "due_date", "project_id", "project_name", "project_color", "parent_task_id", "parent_title")
|
||||||
|
return JSONResponse({"today": today.isoformat(), "tasks": [{k: t.get(k) for k in keys} for t in rows]})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/my-tasks/open-count")
|
@router.get("/api/my-tasks/open-count")
|
||||||
def api_my_open_count(request: Request) -> JSONResponse:
|
def api_my_open_count(request: Request) -> JSONResponse:
|
||||||
"""사이드바 "내 업무" 배지 숫자만 — 목록 전체를 받지 않는다."""
|
"""사이드바 "내 업무" 배지 숫자만 — 목록 전체를 받지 않는다."""
|
||||||
@@ -1465,34 +1532,66 @@ def api_create_task(
|
|||||||
) -> JSONResponse:
|
) -> JSONResponse:
|
||||||
user = _require_user(request)
|
user = _require_user(request)
|
||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
|
task, skipped = _create_task_for(request, st, user, project_id, payload, bg)
|
||||||
|
return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
|
def _create_task_for(
|
||||||
|
request: Request, st: Any, user: dict[str, Any], project_id: int, payload: dict[str, Any],
|
||||||
|
bg: BackgroundTasks,
|
||||||
|
) -> tuple[dict[str, Any], list[str]]:
|
||||||
|
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
|
||||||
|
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
|
||||||
|
project, followers = _task_create_checks(request, st, user, project_id, payload)
|
||||||
|
try:
|
||||||
|
task = st.create_task(**_task_create_fields(user, project_id, payload))
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
except KeyError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc))
|
||||||
|
return task, _task_created_effects(request, st, user, project, task, followers, bg)
|
||||||
|
|
||||||
|
|
||||||
|
def _task_create_checks(request: Request, st: Any, user: dict[str, Any], project_id: int,
|
||||||
|
payload: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
|
||||||
|
"""만들기 전 확인 — 권한(멤버)·프로젝트·담당자·협업자. (프로젝트, 협업자). DB 쓰기·잠금 없음."""
|
||||||
_require_manage(request, st, user, project_id)
|
_require_manage(request, st, user, project_id)
|
||||||
project = st.get_project(project_id=project_id)
|
project = st.get_project(project_id=project_id)
|
||||||
if project is None:
|
if project is None:
|
||||||
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||||
_check_assignee(st, payload.get("assignee_email"), project_id)
|
_check_assignee(st, payload.get("assignee_email"), project_id)
|
||||||
try:
|
followers = _check_followers(st, payload.get("followers"), project_id)
|
||||||
task = st.create_task(
|
return project, followers
|
||||||
project_id=project_id,
|
|
||||||
title=payload.get("title", ""),
|
|
||||||
stage_id=payload.get("stage_id"),
|
def _task_create_fields(user: dict[str, Any], project_id: int, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
description=store.sanitize_description_html(payload.get("description", "")),
|
"""db.create_task / db._insert_task 인자."""
|
||||||
assignee_email=payload.get("assignee_email", ""),
|
return {
|
||||||
assignee_name=payload.get("assignee_name", ""),
|
"project_id": project_id,
|
||||||
priority=payload.get("priority", "normal"),
|
"title": payload.get("title", ""),
|
||||||
start_date=payload.get("start_date"),
|
"stage_id": payload.get("stage_id"),
|
||||||
due_date=payload.get("due_date"),
|
"description": store.sanitize_description_html(payload.get("description", "")),
|
||||||
start_time=payload.get("start_time"),
|
"assignee_email": payload.get("assignee_email", ""),
|
||||||
due_time=payload.get("due_time"),
|
"assignee_name": payload.get("assignee_name", ""),
|
||||||
created_by=user["email"],
|
"priority": payload.get("priority", "normal"),
|
||||||
parent_task_id=payload.get("parent_task_id"),
|
"start_date": payload.get("start_date"),
|
||||||
assignee_allowed=_registered_project_user,
|
"due_date": payload.get("due_date"),
|
||||||
)
|
"start_time": payload.get("start_time"),
|
||||||
except ValueError as exc:
|
"due_time": payload.get("due_time"),
|
||||||
raise HTTPException(status_code=400, detail=str(exc))
|
"created_by": user["email"],
|
||||||
except KeyError as exc:
|
"parent_task_id": payload.get("parent_task_id"),
|
||||||
raise HTTPException(status_code=404, detail=str(exc))
|
"assignee_allowed": _registered_project_user,
|
||||||
# 만든 사람·담당자는 자동 팔로워(아사나와 같은 규칙)
|
}
|
||||||
_follow(st, task["id"], [user["email"], task.get("assignee_email") or ""])
|
|
||||||
|
|
||||||
|
def _task_created_effects(request: Request, st: Any, user: dict[str, Any], project: dict[str, Any],
|
||||||
|
task: dict[str, Any], followers: list[str], bg: BackgroundTasks) -> list[str]:
|
||||||
|
"""업무를 만든(커밋된) 뒤의 부가 처리 — 자동 협업자·배정/완료 알림·관리자 메일(백그라운드)·@태그. 태그 못 한 이메일."""
|
||||||
|
project_id = int(task["project_id"])
|
||||||
|
# 만든 사람은 자동 협업자 + 만들 때 고른 협업자(세부 업무 추가 칸 등). 담당자는 협업자가 아니다(2026-10-13,
|
||||||
|
# db.add_followers 가 담당자를 거른다 — 만든 사람이 담당자여도 빠진다).
|
||||||
|
# 세부 업무는 만든 사람을 자동으로 넣지 않는다 — 고른 협업자만(2026-10-14 사용자 요청).
|
||||||
|
_follow(st, task["id"], ([] if task.get("parent_task_id") else [user["email"]]) + followers)
|
||||||
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
|
# 생성과 동시에 담당자 지정 시 관리자 메일 + 담당자 인앱 알림
|
||||||
if task.get("assignee_email"):
|
if task.get("assignee_email"):
|
||||||
_notify(
|
_notify(
|
||||||
@@ -1504,7 +1603,7 @@ def api_create_task(
|
|||||||
),
|
),
|
||||||
body=(
|
body=(
|
||||||
f"프로젝트: {project['name']}\n"
|
f"프로젝트: {project['name']}\n"
|
||||||
f"작업: {task['title']}\n"
|
f"업무: {task['title']}\n"
|
||||||
f"담당자: {task.get('assignee_name') or task['assignee_email']} "
|
f"담당자: {task.get('assignee_name') or task['assignee_email']} "
|
||||||
f"({task['assignee_email']})\n"
|
f"({task['assignee_email']})\n"
|
||||||
f"마감일: {task.get('due_date') or '-'}\n"
|
f"마감일: {task.get('due_date') or '-'}\n"
|
||||||
@@ -1514,23 +1613,35 @@ def api_create_task(
|
|||||||
_inbox(
|
_inbox(
|
||||||
st, recipients=[task["assignee_email"]], actor=user["email"],
|
st, recipients=[task["assignee_email"]], actor=user["email"],
|
||||||
project_id=project_id, task_id=task["id"], ntype="assigned",
|
project_id=project_id, task_id=task["id"], ntype="assigned",
|
||||||
title=f"작업 배정: {task['title']}",
|
title=f"업무 배정: {task['title']}",
|
||||||
body=f"{project['name']} · 마감 {task.get('due_date') or '-'}",
|
body=f"{project['name']} · 마감 {task.get('due_date') or '-'}",
|
||||||
)
|
)
|
||||||
# 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림.
|
# 완료 섹션에 바로 만든 작업 — 완료 섹션으로 옮긴 것과 같은 완료 알림.
|
||||||
if task.pop("_newly_completed", False):
|
if task.pop("_newly_completed", False):
|
||||||
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
|
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
|
||||||
skipped = _record_mentions(
|
return _record_mentions(
|
||||||
st, task=task,
|
st, task=task,
|
||||||
emails=store.extract_mentions_from_html(task.get("description") or ""),
|
emails=store.extract_mentions_from_html(task.get("description") or ""),
|
||||||
actor=user["email"], project_name=project["name"],
|
actor=user["email"], project_name=project["name"],
|
||||||
)
|
)
|
||||||
return JSONResponse({"task": task, "mention_skipped": skipped}, status_code=201)
|
|
||||||
|
|
||||||
|
|
||||||
_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
|
_ASSIGNEE_DENIED = "담당자는 이 프로젝트를 볼 수 있는 사람(멤버·소유자·관리자)이어야 합니다."
|
||||||
|
|
||||||
|
|
||||||
|
def _check_followers(st: Any, raw: Any, project_id: int) -> list[str]:
|
||||||
|
"""업무를 만들 때 같이 고른 협업자 — 협업자 추가 API 와 같은 기준(그 프로젝트를 볼 수 있는 사람만, 아니면 400)."""
|
||||||
|
if not raw:
|
||||||
|
return []
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
raise HTTPException(status_code=400, detail="협업자 목록이 올바르지 않습니다.")
|
||||||
|
emails = store.normalize_emails([str(e) for e in raw])
|
||||||
|
for em in emails:
|
||||||
|
if not access.can_assign(st, em, project_id):
|
||||||
|
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
||||||
|
return emails
|
||||||
|
|
||||||
|
|
||||||
def _check_assignee(st: Any, email: Any, project_id: int, *, previous: str = "") -> None:
|
def _check_assignee(st: Any, email: Any, project_id: int, *, previous: str = "") -> None:
|
||||||
"""새로 지정하는 담당자가 그 프로젝트를 볼 수 있는지 — 권한 없는 사람에게 배정 알림(작업 제목
|
"""새로 지정하는 담당자가 그 프로젝트를 볼 수 있는지 — 권한 없는 사람에게 배정 알림(작업 제목
|
||||||
등)이 가지 않게. 비우거나 그대로 두는 건 검사하지 않는다(멤버에서 빠진 예전 담당자 보존)."""
|
등)이 가지 않게. 비우거나 그대로 두는 건 검사하지 않는다(멤버에서 빠진 예전 담당자 보존)."""
|
||||||
@@ -1563,12 +1674,11 @@ def api_update_task(
|
|||||||
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:
|
||||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||||
|
|
||||||
project_name = task.get("project_name") or ""
|
project_name = task.get("project_name") or ""
|
||||||
project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name}
|
project = st.get_project(project_id=existing["project_id"]) or {"id": existing["project_id"], "name": project_name}
|
||||||
if task.get("_newly_assigned"):
|
if task.get("_newly_assigned"): # 담당자는 협업자가 아니다 — db.update_task 가 협업자에서 뺐다(2026-10-13)
|
||||||
_follow(st, task_id, [task["_newly_assigned"]])
|
|
||||||
_notify(
|
_notify(
|
||||||
bg, request,
|
bg, request,
|
||||||
subject=store.build_subject_assigned(
|
subject=store.build_subject_assigned(
|
||||||
@@ -1578,7 +1688,7 @@ def api_update_task(
|
|||||||
),
|
),
|
||||||
body=(
|
body=(
|
||||||
f"프로젝트: {project_name}\n"
|
f"프로젝트: {project_name}\n"
|
||||||
f"작업: {task['title']}\n"
|
f"업무: {task['title']}\n"
|
||||||
f"담당자: {task.get('assignee_name') or task['_newly_assigned']} "
|
f"담당자: {task.get('assignee_name') or task['_newly_assigned']} "
|
||||||
f"({task['_newly_assigned']})\n"
|
f"({task['_newly_assigned']})\n"
|
||||||
f"마감일: {task.get('due_date') or '-'}\n"
|
f"마감일: {task.get('due_date') or '-'}\n"
|
||||||
@@ -1588,7 +1698,7 @@ def api_update_task(
|
|||||||
_inbox(
|
_inbox(
|
||||||
st, recipients=[task["_newly_assigned"]], actor=user["email"],
|
st, recipients=[task["_newly_assigned"]], actor=user["email"],
|
||||||
project_id=existing["project_id"], task_id=task_id, ntype="assigned",
|
project_id=existing["project_id"], task_id=task_id, ntype="assigned",
|
||||||
title=f"작업 배정: {task['title']}",
|
title=f"업무 배정: {task['title']}",
|
||||||
body=f"{project_name} · 마감 {task.get('due_date') or '-'}",
|
body=f"{project_name} · 마감 {task.get('due_date') or '-'}",
|
||||||
)
|
)
|
||||||
if task.get("_newly_completed"):
|
if task.get("_newly_completed"):
|
||||||
@@ -1613,7 +1723,7 @@ def api_delete_task(request: Request, task_id: int) -> JSONResponse:
|
|||||||
try:
|
try:
|
||||||
removed_task_ids, trash_id = st.delete_task(task_id=task_id, deleted_by=user["email"])
|
removed_task_ids, trash_id = st.delete_task(task_id=task_id, deleted_by=user["email"])
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||||
# 휴지통(010)이 있으면 첨부 폴더도 휴지통으로(복구 대비), 없으면 예전처럼 삭제.
|
# 휴지통(010)이 있으면 첨부 폴더도 휴지통으로(복구 대비), 없으면 예전처럼 삭제.
|
||||||
if trash_id is not None:
|
if trash_id is not None:
|
||||||
_move_task_dirs_to_trash(request, removed_task_ids, trash_id)
|
_move_task_dirs_to_trash(request, removed_task_ids, trash_id)
|
||||||
@@ -1648,6 +1758,10 @@ def api_get_task(request: Request, task_id: int) -> JSONResponse:
|
|||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
task["followers"] = st.list_followers(task_id=task_id)
|
task["followers"] = st.list_followers(task_id=task_id)
|
||||||
|
# 세부 업무 줄의 협업자 아이콘(담당자 오른쪽) — 줄마다 다시 묻지 않게 한 번에.
|
||||||
|
by_sub = st.list_followers_of(task_ids=[s["id"] for s in task["subtasks"]])
|
||||||
|
for s in task["subtasks"]:
|
||||||
|
s["followers"] = by_sub.get(int(s["id"]), [])
|
||||||
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
|
except Exception: # noqa: BLE001 - 008 미적용이면 팔로워 UI 를 숨긴다
|
||||||
task["followers"] = None
|
task["followers"] = None
|
||||||
return JSONResponse({"task": task})
|
return JSONResponse({"task": task})
|
||||||
@@ -1700,6 +1814,59 @@ def api_move_subtask(
|
|||||||
return JSONResponse({"task": task})
|
return JSONResponse({"task": task})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/tasks/{task_id}/move-project")
|
||||||
|
def api_move_task_project(
|
||||||
|
request: Request,
|
||||||
|
task_id: int,
|
||||||
|
bg: BackgroundTasks,
|
||||||
|
payload: dict[str, Any] = Body(...),
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""메인 업무를 다른 프로젝트로 옮긴다 — 보드 카드·목록 줄을 왼쪽 프로젝트 목록으로 드래그 → 섹션 선택 창.
|
||||||
|
|
||||||
|
body: {"project_id": 대상, "stage_id": 대상 섹션 또는 null}. 원 소속 권한(FULL) + 대상 프로젝트 멤버여야 한다.
|
||||||
|
세부 업무는 함께 옮겨진다. 응답의 `unseen` = 대상 프로젝트를 볼 수 없는 담당자·협업자(화면이 안내).
|
||||||
|
"""
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
existing = _task_or_404(st, task_id)
|
||||||
|
_require_task(st, user, existing, write=True)
|
||||||
|
try:
|
||||||
|
target = int(payload.get("project_id"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="옮길 프로젝트(project_id)가 필요합니다.")
|
||||||
|
_require_manage(request, st, user, target)
|
||||||
|
project = st.get_project(project_id=target)
|
||||||
|
if project is None:
|
||||||
|
raise HTTPException(status_code=404, detail="프로젝트를 찾을 수 없습니다.")
|
||||||
|
try:
|
||||||
|
task = st.move_task_to_project(
|
||||||
|
task_id=task_id, project_id=target, stage_id=payload.get("stage_id"),
|
||||||
|
actor=user["email"], assignee_allowed=_registered_project_user,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc))
|
||||||
|
except KeyError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc))
|
||||||
|
task.pop("_moved_ids", None)
|
||||||
|
newly_assigned = task.pop("_newly_assigned", None)
|
||||||
|
if newly_assigned: # 대상 섹션 기본 담당자가 자동 배정됨 — 일반 배정과 같은 알림(담당자는 협업자가 아님)
|
||||||
|
_inbox(
|
||||||
|
st, recipients=[newly_assigned], actor=user["email"], project_id=target, task_id=task["id"],
|
||||||
|
ntype="assigned", title=f"업무 배정: {task['title']}",
|
||||||
|
body=f"{project['name']} · 마감 {task.get('due_date') or '-'}",
|
||||||
|
)
|
||||||
|
if task.pop("_newly_completed", False):
|
||||||
|
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
|
||||||
|
people = [task.get("assignee_email") or ""]
|
||||||
|
try:
|
||||||
|
people += st.list_followers(task_id=task_id)
|
||||||
|
except Exception: # noqa: BLE001 - 008 미적용
|
||||||
|
pass
|
||||||
|
unseen = sorted({store.norm_str(e, lower=True) for e in people if e} -
|
||||||
|
set(access.filter_recipients(st, task, [e for e in people if e])))
|
||||||
|
return JSONResponse({"task": task, "unseen": unseen})
|
||||||
|
|
||||||
|
|
||||||
# ────────────────────────────────────────────────────────────
|
# ────────────────────────────────────────────────────────────
|
||||||
# JSON API — 팔로워 (아사나의 협업자)
|
# JSON API — 팔로워 (아사나의 협업자)
|
||||||
# ────────────────────────────────────────────────────────────
|
# ────────────────────────────────────────────────────────────
|
||||||
@@ -1735,6 +1902,8 @@ def api_add_follower(
|
|||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
task = _task_for_followers(request, st, user, task_id)
|
task = _task_for_followers(request, st, user, task_id)
|
||||||
email = store.norm_str(payload.get("email") or user["email"], lower=True)
|
email = store.norm_str(payload.get("email") or user["email"], lower=True)
|
||||||
|
if email and email == store.norm_str(task.get("assignee_email") or "", lower=True):
|
||||||
|
raise HTTPException(status_code=400, detail="담당자는 협업자로 지정할 수 없습니다(협업자는 담당자 외의 멤버).")
|
||||||
if email != store.norm_str(user["email"], lower=True):
|
if email != store.norm_str(user["email"], lower=True):
|
||||||
if not access.can_assign(st, email, task["project_id"]):
|
if not access.can_assign(st, email, task["project_id"]):
|
||||||
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
raise HTTPException(status_code=400, detail="이 프로젝트 멤버만 협업자로 추가할 수 있습니다.")
|
||||||
@@ -1827,13 +1996,13 @@ def api_add_task_link(
|
|||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
task = st.get_task(task_id=task_id)
|
task = st.get_task(task_id=task_id)
|
||||||
if task is None:
|
if task is None:
|
||||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||||
try:
|
try:
|
||||||
target_project_id = int(payload.get("project_id"))
|
target_project_id = int(payload.get("project_id"))
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
raise HTTPException(status_code=400, detail="project_id 가 필요합니다.")
|
raise HTTPException(status_code=400, detail="project_id 가 필요합니다.")
|
||||||
if target_project_id == task["project_id"]:
|
if target_project_id == task["project_id"]:
|
||||||
raise HTTPException(status_code=400, detail="이미 이 작업의 기본 프로젝트입니다.")
|
raise HTTPException(status_code=400, detail="이미 이 업무의 기본 프로젝트입니다.")
|
||||||
_require_manage(request, st, user, target_project_id)
|
_require_manage(request, st, user, target_project_id)
|
||||||
already_linked = any(
|
already_linked = any(
|
||||||
link["project_id"] == target_project_id for link in st.list_task_links(task_id=task_id)
|
link["project_id"] == target_project_id for link in st.list_task_links(task_id=task_id)
|
||||||
@@ -1859,7 +2028,7 @@ def api_remove_task_link(request: Request, task_id: int, project_id: int) -> JSO
|
|||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
task = st.get_task(task_id=task_id)
|
task = st.get_task(task_id=task_id)
|
||||||
if task is None:
|
if task is None:
|
||||||
raise HTTPException(status_code=404, detail="작업을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="업무를 찾을 수 없습니다.")
|
||||||
_require_manage(request, st, user, task["project_id"])
|
_require_manage(request, st, user, task["project_id"])
|
||||||
_require_manage(request, st, user, project_id)
|
_require_manage(request, st, user, project_id)
|
||||||
st.remove_task_link(task_id=task_id, project_id=project_id)
|
st.remove_task_link(task_id=task_id, project_id=project_id)
|
||||||
@@ -2115,9 +2284,31 @@ def api_toggle_reaction(
|
|||||||
reactions = st.toggle_reaction(comment_id=comment_id, user_email=user["email"], emoji=emoji)
|
reactions = st.toggle_reaction(comment_id=comment_id, user_email=user["email"], emoji=emoji)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
|
raise HTTPException(status_code=404, detail="댓글을 찾을 수 없습니다.")
|
||||||
|
me = store.norm_str(user["email"], lower=True)
|
||||||
|
if any(r["emoji"] == emoji and me in r["users"] for r in reactions): # 켤 때만(끌 때는 알림 없음)
|
||||||
|
_notify_reaction(st, task=task, comment=comment, actor=user["email"], emoji=emoji)
|
||||||
return JSONResponse({"reactions": reactions})
|
return JSONResponse({"reactions": reactions})
|
||||||
|
|
||||||
|
|
||||||
|
def _notify_reaction(
|
||||||
|
st: Any, *, task: dict[str, Any], comment: dict[str, Any], actor: str, emoji: str,
|
||||||
|
) -> None:
|
||||||
|
"""댓글 이모티콘 반응 알림 — 그 댓글을 쓴 사람에게 어떤 이모티콘인지(자기 댓글·지금 볼 수 없는 사람은 제외)."""
|
||||||
|
author = store.norm_str(comment.get("author_email"), lower=True)
|
||||||
|
if not author or author == store.norm_str(actor, lower=True):
|
||||||
|
return
|
||||||
|
recipients = access.filter_recipients(st, task, [author])
|
||||||
|
if not recipients:
|
||||||
|
return
|
||||||
|
project = st.get_project(project_id=task["project_id"]) or {}
|
||||||
|
preview = (comment.get("body") or "").strip().replace("\n", " ")[:80] or "첨부 파일"
|
||||||
|
_inbox(
|
||||||
|
st, recipients=recipients, actor=actor, project_id=task["project_id"], task_id=task["id"],
|
||||||
|
ntype="reaction", title=f"내 댓글에 {emoji} 반응: {task['title']}",
|
||||||
|
body=f"{project.get('name') or task.get('project_name') or ''} · “{preview}”",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _comment_task_access(st: Any, user: dict[str, Any], comment_id: int) -> dict[str, Any]:
|
def _comment_task_access(st: Any, user: dict[str, Any], comment_id: int) -> dict[str, Any]:
|
||||||
"""댓글 수정·삭제 전 — 작성자라도 지금 그 작업의 원 소속 권한이 없으면 거절(멤버에서 빠진 뒤
|
"""댓글 수정·삭제 전 — 작성자라도 지금 그 작업의 원 소속 권한이 없으면 거절(멤버에서 빠진 뒤
|
||||||
자기 댓글을 고치거나 지우던 경로 차단). 작성자 본인/관리자 검사는 DB 쪽이 한다."""
|
자기 댓글을 고치거나 지우던 경로 차단). 작성자 본인/관리자 검사는 DB 쪽이 한다."""
|
||||||
@@ -2585,7 +2776,7 @@ def notifier_page(request: Request) -> Any:
|
|||||||
"my_open_total": _my_open_count(st, user),
|
"my_open_total": _my_open_count(st, user),
|
||||||
"mention_unread": _safe_mention_unread(st, user),
|
"mention_unread": _safe_mention_unread(st, user),
|
||||||
"page_title": "PC 알림 프로그램",
|
"page_title": "PC 알림 프로그램",
|
||||||
"page_subtitle": "브라우저가 뒤에 있어도 태그·작업 배정 알림을 화면 위에 크게",
|
"page_subtitle": "브라우저가 뒤에 있어도 태그·업무 배정 알림을 화면 위에 크게",
|
||||||
"force_sidebar_collapsed": True,
|
"force_sidebar_collapsed": True,
|
||||||
"color_palette": list(store.COLOR_PALETTE),
|
"color_palette": list(store.COLOR_PALETTE),
|
||||||
"project_icons": list(store.PROJECT_ICONS),
|
"project_icons": list(store.PROJECT_ICONS),
|
||||||
@@ -2714,7 +2905,9 @@ def trash_page(request: Request) -> HTMLResponse:
|
|||||||
"""휴지통 — Pro user 이상. 지운 업무(세부 업무 포함)를 3개월 보관, 복구(멤버인 프로젝트 것만)."""
|
"""휴지통 — Pro user 이상. 지운 업무(세부 업무 포함)를 3개월 보관, 복구(멤버인 프로젝트 것만)."""
|
||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
if not access.is_pro(user):
|
if not access.is_pro(user):
|
||||||
raise HTTPException(status_code=403, detail="Pro user 이상만 볼 수 있습니다.")
|
raise HTTPException(status_code=403, detail="Pro user 이상만 볼 수 있습니다.")
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
@@ -2734,7 +2927,7 @@ def trash_page(request: Request) -> HTMLResponse:
|
|||||||
"my_open_total": _my_open_count(st, user),
|
"my_open_total": _my_open_count(st, user),
|
||||||
"mention_unread": _safe_mention_unread(st, user),
|
"mention_unread": _safe_mention_unread(st, user),
|
||||||
"page_title": "휴지통",
|
"page_title": "휴지통",
|
||||||
"page_subtitle": "삭제한 작업 — 3개월 보관, Pro user 이상만 복구",
|
"page_subtitle": "삭제한 업무 — 3개월 보관, Pro user 이상만 복구",
|
||||||
"force_sidebar_collapsed": True,
|
"force_sidebar_collapsed": True,
|
||||||
"color_palette": list(store.COLOR_PALETTE),
|
"color_palette": list(store.COLOR_PALETTE),
|
||||||
"project_icons": list(store.PROJECT_ICONS),
|
"project_icons": list(store.PROJECT_ICONS),
|
||||||
@@ -2796,7 +2989,9 @@ def help_page(request: Request) -> HTMLResponse:
|
|||||||
DB 없이 그리는 정적 안내라 DB 설정 전에도 열린다."""
|
DB 없이 그리는 정적 안내라 DB 설정 전에도 열린다."""
|
||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
return render_template(
|
return render_template(
|
||||||
request,
|
request,
|
||||||
"project/help.html",
|
"project/help.html",
|
||||||
@@ -2810,12 +3005,30 @@ def help_page(request: Request) -> HTMLResponse:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_DBX_PAGE = Path(__file__).resolve().parent / "dbx.html"
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dbx", response_class=HTMLResponse)
|
||||||
|
def dbx_page(request: Request) -> HTMLResponse:
|
||||||
|
"""수신함 [성공하기] — 모듈 폴더의 dbx.html 을 그대로(별도 창, 닫기 버튼만). DB 없이 열린다."""
|
||||||
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
|
try:
|
||||||
|
html = _DBX_PAGE.read_text(encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
raise HTTPException(status_code=404, detail="페이지를 찾을 수 없습니다.")
|
||||||
|
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
@router.get("/inbox", response_class=HTMLResponse)
|
@router.get("/inbox", response_class=HTMLResponse)
|
||||||
def inbox_page(request: Request) -> HTMLResponse:
|
def inbox_page(request: Request) -> HTMLResponse:
|
||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _render_config_needed(request, user)
|
return _render_config_needed(request, user)
|
||||||
@@ -2839,7 +3052,7 @@ def inbox_page(request: Request) -> HTMLResponse:
|
|||||||
"goal_years": _goal_years_nav(st),
|
"goal_years": _goal_years_nav(st),
|
||||||
"my_open_total": my_open_total,
|
"my_open_total": my_open_total,
|
||||||
"page_title": "수신함",
|
"page_title": "수신함",
|
||||||
"page_subtitle": "나를 태그한 작업과 프로젝트 알림",
|
"page_subtitle": "나를 태그한 업무와 프로젝트 알림",
|
||||||
"force_sidebar_collapsed": True,
|
"force_sidebar_collapsed": True,
|
||||||
"color_palette": list(store.COLOR_PALETTE),
|
"color_palette": list(store.COLOR_PALETTE),
|
||||||
"project_icons": list(store.PROJECT_ICONS),
|
"project_icons": list(store.PROJECT_ICONS),
|
||||||
@@ -2914,6 +3127,20 @@ def _goal_area_layout(rows: list[dict[str, Any]], this_month: int) -> None:
|
|||||||
row["layout"] = out
|
row["layout"] = out
|
||||||
|
|
||||||
|
|
||||||
|
def _meeting_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||||
|
"""회의록 구역 한 덩어리의 항목 칸 묶음(027) — 이어 붙은 줄(label_cont, 구역 첫 줄 제외)은 항목 칸을 그리지 않고
|
||||||
|
(label_hidden) 묶음 첫 줄이 rowspan(label_span). label_shown = 그 줄이 속한 항목 이름(칸 이름표·접근성용)."""
|
||||||
|
grp: dict[str, Any] | None = None
|
||||||
|
for i, it in enumerate(rows):
|
||||||
|
if i and it.get("label_cont") and grp is not None:
|
||||||
|
it["label_hidden"] = True
|
||||||
|
grp["label_span"] += 1
|
||||||
|
else:
|
||||||
|
grp = it
|
||||||
|
it["label_hidden"], it["label_span"] = False, 1
|
||||||
|
it["label_shown"] = grp["label"]
|
||||||
|
|
||||||
|
|
||||||
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
|
def _goal_label_spans(rows: list[dict[str, Any]]) -> None:
|
||||||
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
|
"""항목 칸(2열) 묶음(016) — 묶음 첫 줄 label_span = 이어 붙은 줄 수 + 1, 이어 붙은 줄은 label_span 0(2열을 그리지 않음).
|
||||||
영역 첫 줄은 늘 묶음 첫 줄."""
|
영역 첫 줄은 늘 묶음 첫 줄."""
|
||||||
@@ -2946,6 +3173,12 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
|||||||
raise HTTPException(status_code=409, detail="회의가 완료되어 수정할 수 없습니다. 관리자가 [완료 해제]하면 다시 고칠 수 있습니다.")
|
raise HTTPException(status_code=409, detail="회의가 완료되어 수정할 수 없습니다. 관리자가 [완료 해제]하면 다시 고칠 수 있습니다.")
|
||||||
except store.MeetingMigration022Needed:
|
except store.MeetingMigration022Needed:
|
||||||
raise HTTPException(status_code=503, detail="회의 완료 기능은 project_db 마이그레이션 022 적용 후 사용할 수 있습니다.")
|
raise HTTPException(status_code=503, detail="회의 완료 기능은 project_db 마이그레이션 022 적용 후 사용할 수 있습니다.")
|
||||||
|
except store.MeetingMigration027Needed:
|
||||||
|
raise HTTPException(status_code=503, detail="같은 항목 칸 안 줄 추가·항목 칸 나누기는 project_db 마이그레이션 027 적용 후 사용할 수 있습니다.")
|
||||||
|
except store.MeetingParentTaskMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail="업무 칸(이미 있는 업무의 세부 업무로 등록)은 project_db 마이그레이션 026 적용 후 사용할 수 있습니다.")
|
||||||
|
except store.MeetingTaskMigrationNeeded:
|
||||||
|
raise HTTPException(status_code=503, detail="업무 등록 표(모두가 같이 보는 주차별 표)는 project_db 마이그레이션 025 적용 후 사용할 수 있습니다.")
|
||||||
except store.MeetingMigration020Needed:
|
except store.MeetingMigration020Needed:
|
||||||
raise HTTPException(status_code=503, detail="새 주차·결과 글·주차별 목표는 project_db 마이그레이션 020 적용 후 사용할 수 있습니다.")
|
raise HTTPException(status_code=503, detail="새 주차·결과 글·주차별 목표는 project_db 마이그레이션 020 적용 후 사용할 수 있습니다.")
|
||||||
except store.GoalCellConflict as exc:
|
except store.GoalCellConflict as exc:
|
||||||
@@ -2961,7 +3194,9 @@ def _goal_call(fn: Any, *args: Any, **kwargs: Any) -> Any:
|
|||||||
@router.get("/goals")
|
@router.get("/goals")
|
||||||
def goals_home(request: Request) -> RedirectResponse:
|
def goals_home(request: Request) -> RedirectResponse:
|
||||||
"""사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로."""
|
"""사이드바 "목표" 자체 주소 — 가장 최근 연도(없으면 올해)로."""
|
||||||
_require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
years = _goal_years_nav(st) if st is not None else [today_kst().year]
|
years = _goal_years_nav(st) if st is not None else [today_kst().year]
|
||||||
return RedirectResponse(url=f"/project/goals/{years[0]}", status_code=303)
|
return RedirectResponse(url=f"/project/goals/{years[0]}", status_code=303)
|
||||||
@@ -2974,7 +3209,9 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
|
|||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
from app.store import is_admin # noqa: WPS433
|
from app.store import is_admin # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _render_config_needed(request, user)
|
return _render_config_needed(request, user)
|
||||||
@@ -3426,6 +3663,7 @@ def _meeting_view(request: Request, st: Any, *, year: int, month: int, week: dat
|
|||||||
meeting["sections"] = sections
|
meeting["sections"] = sections
|
||||||
for sec in sections:
|
for sec in sections:
|
||||||
covered = 0
|
covered = 0
|
||||||
|
_meeting_label_spans(sec["rows"])
|
||||||
for i, it in enumerate(sec["rows"]):
|
for i, it in enumerate(sec["rows"]):
|
||||||
it["content_html"] = store.goal_text_html(it["content"])
|
it["content_html"] = store.goal_text_html(it["content"])
|
||||||
it["content_hidden"] = covered > 0
|
it["content_hidden"] = covered > 0
|
||||||
@@ -3505,7 +3743,9 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
|
|||||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||||
from app.store import has_module, is_admin # noqa: WPS433
|
from app.store import has_module, is_admin # noqa: WPS433
|
||||||
|
|
||||||
user = _require_user(request)
|
user = _page_user(request)
|
||||||
|
if not isinstance(user, dict):
|
||||||
|
return user
|
||||||
st = _store(request)
|
st = _store(request)
|
||||||
if st is None:
|
if st is None:
|
||||||
return _render_config_needed(request, user)
|
return _render_config_needed(request, user)
|
||||||
@@ -3669,7 +3909,8 @@ def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
|
|||||||
|
|
||||||
@router.post("/api/goals/meetings/{week_start}/items")
|
@router.post("/api/goals/meetings/{week_start}/items")
|
||||||
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
"""줄 추가 {section, label?, ref_item_id?, place?: above|below} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝)."""
|
"""줄 추가 {section, label?, ref_item_id?, place?: above|below, same_label?} — 기준 줄 위/아래, 없으면 구역 끝(새 구역이면 맨 끝).
|
||||||
|
same_label = 주요 업무 칸에서 추가 — 기준 줄과 같은 항목 칸 안에(027)."""
|
||||||
user = _require_user(request)
|
user = _require_user(request)
|
||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
ws = _goal_call(store.validate_week_start, week_start)
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
@@ -3681,6 +3922,7 @@ def api_add_meeting_item(request: Request, week_start: str, payload: dict[str, A
|
|||||||
item_id = _goal_call(
|
item_id = _goal_call(
|
||||||
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
|
st.add_meeting_item, week_start=ws, section=payload.get("section", ""), label=payload.get("label", ""),
|
||||||
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
|
ref_item_id=ref_id, place=payload.get("place") or "below", updated_by=user["email"],
|
||||||
|
same_label=bool(payload.get("same_label")),
|
||||||
)
|
)
|
||||||
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
|
return JSONResponse({"ok": True, "id": item_id}, status_code=201)
|
||||||
|
|
||||||
@@ -3737,3 +3979,154 @@ def api_move_meeting_item(request: Request, item_id: int, payload: dict[str, Any
|
|||||||
st = _db_or_503(request)
|
st = _db_or_503(request)
|
||||||
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
|
_goal_call(st.move_meeting_item, item_id=item_id, direction=int(payload.get("direction") or 0))
|
||||||
return JSONResponse({"ok": True})
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meeting-items/{item_id}/move-to")
|
||||||
|
def api_move_meeting_group(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""항목 칸 끌어 옮기기 {before_item_id: 그 묶음 앞 | null = 구역 맨 끝} — 묶인 줄·병합은 통째로, 같은 구역 안만.
|
||||||
|
줄 순서와 같은 권한(누구나, 회의 완료 전까지)."""
|
||||||
|
_require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
before = payload.get("before_item_id")
|
||||||
|
try:
|
||||||
|
before = None if before in (None, "") else int(before)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="before_item_id 가 올바르지 않습니다.")
|
||||||
|
moved = _goal_call(st.move_meeting_group, item_id=item_id, before_item_id=before)
|
||||||
|
return JSONResponse({"ok": True, "moved": bool(moved)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meeting-items/{item_id}/split-label")
|
||||||
|
def api_split_meeting_label(request: Request, item_id: int) -> JSONResponse:
|
||||||
|
"""항목 칸 나누기(027) — item_id = 묶음 첫 줄. 이어 붙은 줄들이 각자 항목 칸(이름 빈 칸)으로. 줄 순서와 같은 권한."""
|
||||||
|
_require_user(request)
|
||||||
|
n = _goal_call(_db_or_503(request).split_meeting_label, item_id=item_id)
|
||||||
|
return JSONResponse({"ok": True, "split": n})
|
||||||
|
|
||||||
|
|
||||||
|
# ── 회의록 작업 등록 표(025) — 주차별 한 표를 서버에(예전엔 각자 브라우저에만 있어 다른 사람 줄이 안 보였다) ──
|
||||||
|
# 보기·고치기: 회의록을 볼 수 있는 사람 누구나(회의 완료면 잠금). 줄에 고른 프로젝트는 내가 멤버인 것만 고를 수 있고,
|
||||||
|
# 내가 멤버가 아닌 프로젝트를 가리키는 남의 줄은 프로젝트·섹션 이름·만든 작업을 가린다. [적용] = 그 프로젝트 멤버만.
|
||||||
|
def _quick_view(st: Any, user: dict[str, Any], rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
seen: dict[int, bool] = {}
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
pid = r.get("project_id")
|
||||||
|
ok = True if pid is None else seen.setdefault(pid, access.can_manage_project(st, user, pid))
|
||||||
|
r = dict(r, visible=ok, registered=r.get("task_id") is not None) # 등록됨 여부는 누구에게나(작업 내용은 멤버만)
|
||||||
|
if not ok:
|
||||||
|
r.update(project_name="(볼 수 없는 프로젝트)", stage_name="", task_title="", task_id=None,
|
||||||
|
task_project_id=None, parent_task_id=None, parent_task_title="")
|
||||||
|
out.append(r)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _quick_fields(st: Any, user: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
fields = {k: payload[k] for k in ("title", "assignee_email", "project_id", "stage_id", "parent_task_id") if k in payload}
|
||||||
|
pid = fields.get("project_id")
|
||||||
|
if pid not in (None, ""):
|
||||||
|
try:
|
||||||
|
pid = int(pid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="프로젝트 값이 올바르지 않습니다.")
|
||||||
|
if not access.can_manage_project(st, user, pid):
|
||||||
|
raise HTTPException(status_code=403, detail="내가 멤버인 프로젝트만 고를 수 있습니다.")
|
||||||
|
return fields
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/api/goals/meetings/{week_start}/quick-tasks")
|
||||||
|
def api_list_quick_tasks(request: Request, week_start: str) -> JSONResponse:
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
rows = _goal_call(st.list_meeting_tasks, week_start=ws)
|
||||||
|
return JSONResponse({"tasks": _quick_view(st, user, rows)})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meetings/{week_start}/quick-tasks")
|
||||||
|
def api_add_quick_task(request: Request, week_start: str, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
|
||||||
|
"""줄 추가 {title?, assignee_email?, project_id?, stage_id?, parent_task_id?(작업 칸 — 그 작업의 세부 작업으로),
|
||||||
|
task_id?(예전 브라우저 표의 등록된 줄)}."""
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
ws = _goal_call(store.validate_week_start, week_start)
|
||||||
|
fields = _quick_fields(st, user, payload)
|
||||||
|
task_id = None
|
||||||
|
if payload.get("task_id") not in (None, ""):
|
||||||
|
# 옮겨 오는 등록된 줄 — 그 작업을 지금 내가 원 소속으로 다룰 수 있을 때만 이어 붙인다(남의 작업 id 를 끌어오지 못하게)
|
||||||
|
try:
|
||||||
|
t = st.get_task(task_id=int(payload["task_id"]))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
t = None
|
||||||
|
if t is not None and access.task_access(st, user, t) == access.FULL:
|
||||||
|
task_id = int(t["id"])
|
||||||
|
row = _goal_call(st.add_meeting_task, week_start=ws, fields=fields, by=user["email"], task_id=task_id)
|
||||||
|
return JSONResponse({"task": _quick_view(st, user, [row])[0]}, status_code=201)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/api/goals/meeting-quick-tasks/{item_id}")
|
||||||
|
def api_update_quick_task(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
fields = _quick_fields(st, user, payload)
|
||||||
|
row = _goal_call(st.update_meeting_task, item_id=item_id, fields=fields, by=user["email"])
|
||||||
|
return JSONResponse({"task": _quick_view(st, user, [row])[0]})
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/api/goals/meeting-quick-tasks/{item_id}")
|
||||||
|
def api_delete_quick_task(request: Request, item_id: int) -> JSONResponse:
|
||||||
|
"""줄 지우기. 이미 만든 작업은 화면이 따로 지운다(DELETE /api/tasks/{id} — 그 프로젝트 멤버만, 휴지통)."""
|
||||||
|
_require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
_goal_call(st.delete_meeting_task, item_id=item_id)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meeting-quick-tasks/{item_id}/apply")
|
||||||
|
def api_apply_quick_task(request: Request, item_id: int, bg: BackgroundTasks) -> JSONResponse:
|
||||||
|
"""[적용] — 그 줄로 프로젝트에 작업을 만든다(작업 창과 같은 권한·알림). 줄을 잠그고 한 번만 — 이미 만들었으면 그 결과.
|
||||||
|
|
||||||
|
순서(2026-10-15 검토 F02): ① 잠그기 전에 줄을 읽어 권한·담당자·협업자를 확인(DB 잠금 없이) ② DB 한 트랜잭션에서
|
||||||
|
줄 잠금 → 이미 만들었으면 그대로 / 줄이 그사이 바뀌었으면 409 → 업무 INSERT → 줄에 task_id(같은 연결 — 실패하면 둘 다
|
||||||
|
롤백, 재시도·동시 클릭에도 업무 하나) ③ 커밋된 뒤에만 협업자·알림·메일."""
|
||||||
|
user = _require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
snap = _goal_call(st.get_meeting_task, item_id=item_id)
|
||||||
|
if snap is None:
|
||||||
|
raise HTTPException(status_code=404, detail="업무 등록 줄을 찾을 수 없습니다.")
|
||||||
|
project = followers = fields = None
|
||||||
|
if snap["task_id"] is None:
|
||||||
|
if not (snap["title"] or "").strip():
|
||||||
|
raise HTTPException(status_code=400, detail="업무 제목을 쓰세요.")
|
||||||
|
if snap["project_id"] is None:
|
||||||
|
raise HTTPException(status_code=400, detail="프로젝트를 고르세요.")
|
||||||
|
parent_task_id = snap.get("parent_task_id")
|
||||||
|
rec = access.default_user_lookup(snap["assignee_email"]) if snap["assignee_email"] else None
|
||||||
|
# 작업 칸을 골랐으면 그 작업의 세부 작업(섹션 없음) — 확인은 작업 창과 같이 프로젝트 멤버, 같은 프로젝트는 DB 가 잠근 뒤
|
||||||
|
payload = {"title": snap["title"].strip(), "stage_id": None if parent_task_id else snap["stage_id"],
|
||||||
|
"assignee_email": snap["assignee_email"],
|
||||||
|
"assignee_name": (rec or {}).get("name") or (snap["assignee_email"].split("@")[0] if snap["assignee_email"] else ""),
|
||||||
|
"parent_task_id": parent_task_id}
|
||||||
|
pid = int(snap["project_id"])
|
||||||
|
project, followers = _task_create_checks(request, st, user, pid, payload)
|
||||||
|
fields = _task_create_fields(user, pid, payload)
|
||||||
|
row, made, task = _goal_call(st.apply_meeting_task, item_id=item_id, task_fields=fields, expect=snap)
|
||||||
|
if made and task is not None:
|
||||||
|
_task_created_effects(request, st, user, project, task, followers or [], bg) # 커밋 뒤에만
|
||||||
|
return JSONResponse({"task": _quick_view(st, user, [row])[0], "created": made}, status_code=201 if made else 200)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/goals/meeting-items/{item_id}/move-section")
|
||||||
|
def api_move_meeting_section(request: Request, item_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||||
|
"""구역(첫 열 "구분") 통째로 위/아래 {direction: -1|1} — item_id = 그 구역의 아무 줄. 줄 순서와 같은 권한(누구나,
|
||||||
|
회의 완료 전까지). 다음 회의록은 이 순서를 이어받는다."""
|
||||||
|
_require_user(request)
|
||||||
|
st = _db_or_503(request)
|
||||||
|
try:
|
||||||
|
direction = int(payload.get("direction") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=400, detail="direction 이 올바르지 않습니다.")
|
||||||
|
if direction not in (-1, 1):
|
||||||
|
raise HTTPException(status_code=400, detail="direction 은 -1(위) 또는 1(아래)입니다.")
|
||||||
|
_goal_call(st.move_meeting_section, item_id=item_id, direction=direction)
|
||||||
|
return JSONResponse({"ok": True})
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ ACTION_COMPLETED = "completed"
|
|||||||
ACTION_STAGE_CHANGED = "stage_changed"
|
ACTION_STAGE_CHANGED = "stage_changed"
|
||||||
ACTION_REOPENED = "reopened"
|
ACTION_REOPENED = "reopened"
|
||||||
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
|
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
|
||||||
|
ACTION_PROJECT_MOVED = "project_moved" # 업무를 다른 프로젝트로 옮김(왼쪽 프로젝트 목록으로 드래그)
|
||||||
|
|
||||||
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
||||||
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
||||||
@@ -283,9 +284,9 @@ def validate_project_name(name: Any) -> str:
|
|||||||
def validate_task_title(title: Any) -> str:
|
def validate_task_title(title: Any) -> str:
|
||||||
v = norm_str(title)
|
v = norm_str(title)
|
||||||
if not v:
|
if not v:
|
||||||
raise ValueError("작업 제목은 필수입니다.")
|
raise ValueError("업무 제목은 필수입니다.")
|
||||||
if len(v) > 300:
|
if len(v) > 300:
|
||||||
raise ValueError("작업 제목이 너무 깁니다(300자 이내).")
|
raise ValueError("업무 제목이 너무 깁니다(300자 이내).")
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
@@ -374,6 +375,47 @@ def validate_time(t: Any) -> str | None:
|
|||||||
return f"{hh:02d}:{mm:02d}"
|
return f"{hh:02d}:{mm:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
# Project 옵션 — 시스템 전체 설정(마이그레이션 029 project_options, 수퍼관리자·Admin 수정)
|
||||||
|
# 폰트 같은 "일반" 옵션은 브라우저별(localStorage)이라 여기 없다.
|
||||||
|
# ════════════════════════════════════════════════════════════
|
||||||
|
PROJECT_VIEWS: tuple[str, ...] = ("board", "list", "calendar", "timeline", "dashboard")
|
||||||
|
PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
|
||||||
|
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
|
||||||
|
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
|
"""DB 에서 읽은 값 → 화면용. 모르는 키는 버리고, 이상한 값·없는 키는 기본값(읽기는 실패하지 않는다)."""
|
||||||
|
out = dict(PROJECT_OPTION_DEFAULTS)
|
||||||
|
raw = raw or {}
|
||||||
|
if raw.get("default_view") in PROJECT_VIEWS:
|
||||||
|
out["default_view"] = raw["default_view"]
|
||||||
|
if isinstance(raw.get("board_cover"), bool):
|
||||||
|
out["board_cover"] = raw["board_cover"]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def validate_project_options(payload: Any) -> dict[str, Any]:
|
||||||
|
"""저장 요청 검사 — 보낸 키만 돌려준다(일부만 바꿀 수 있게). 모르는 키·잘못된 값·빈 요청은 ValueError."""
|
||||||
|
if not isinstance(payload, dict) or not payload:
|
||||||
|
raise ValueError("바꿀 옵션이 없습니다.")
|
||||||
|
unknown = set(payload) - set(PROJECT_OPTION_DEFAULTS)
|
||||||
|
if unknown:
|
||||||
|
raise ValueError("알 수 없는 옵션입니다: " + ", ".join(sorted(unknown)))
|
||||||
|
out: dict[str, Any] = {}
|
||||||
|
if "default_view" in payload:
|
||||||
|
if payload["default_view"] not in PROJECT_VIEWS:
|
||||||
|
raise ValueError("처음 여는 탭 값이 올바르지 않습니다.")
|
||||||
|
out["default_view"] = payload["default_view"]
|
||||||
|
if "board_cover" in payload:
|
||||||
|
if not isinstance(payload["board_cover"], bool):
|
||||||
|
raise ValueError("카드 표지 값이 올바르지 않습니다.")
|
||||||
|
out["board_cover"] = payload["board_cover"]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
# 연간 목표 (마이그레이션 013) — 사이드바 "목표" → 연도
|
||||||
# ════════════════════════════════════════════════════════════
|
# ════════════════════════════════════════════════════════════
|
||||||
@@ -431,6 +473,18 @@ class MeetingMigration022Needed(RuntimeError):
|
|||||||
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
|
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingMigration027Needed(RuntimeError):
|
||||||
|
"""같은 항목 칸 안 줄 추가·항목 칸 나누기(goal_meeting_items.label_cont)는 마이그레이션 027 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingTaskMigrationNeeded(RuntimeError):
|
||||||
|
"""회의록 작업 등록 표(서버 저장)는 마이그레이션 025 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
|
class MeetingParentTaskMigrationNeeded(RuntimeError):
|
||||||
|
"""작업 등록 표의 작업 칸(이미 있는 작업의 세부 작업으로)은 마이그레이션 026 뒤에만 된다."""
|
||||||
|
|
||||||
|
|
||||||
class MeetingMigration020Needed(RuntimeError):
|
class MeetingMigration020Needed(RuntimeError):
|
||||||
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
|
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
|
||||||
|
|
||||||
@@ -813,11 +867,11 @@ def sales_unit_multiplier(unit: str) -> int | None:
|
|||||||
|
|
||||||
|
|
||||||
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
def build_subject_assigned(*, project_name: str, task_title: str, assignee: str) -> str:
|
||||||
return f"[DBX 프로젝트] 작업 배정: {project_name} · {task_title} → {assignee}"
|
return f"[DBX 프로젝트] 업무 배정: {project_name} · {task_title} → {assignee}"
|
||||||
|
|
||||||
|
|
||||||
def build_subject_completed(*, project_name: str, task_title: str) -> str:
|
def build_subject_completed(*, project_name: str, task_title: str) -> str:
|
||||||
return f"[DBX 프로젝트] 작업 완료: {project_name} · {task_title}"
|
return f"[DBX 프로젝트] 업무 완료: {project_name} · {task_title}"
|
||||||
|
|
||||||
|
|
||||||
def build_subject_project_done(*, project_name: str) -> str:
|
def build_subject_project_done(*, project_name: str) -> str:
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{# 설명란 서식 도구(작업 창·긴급 공지 관리 공용). fmtbar_id·img_input_id 를 주면 그 id 로(기본 = 작업 창 id).
|
||||||
|
동작은 project.js createDescEditor — 버튼 data-cmd 를 그대로 쓴다. #}
|
||||||
|
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
||||||
|
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
||||||
|
<div class="pj-desc-fmtbar" id="{{ fmtbar_id or 'pj-desc-fmtbar' }}">
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
||||||
|
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
||||||
|
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
||||||
|
<span class="pj-desc-fmtsep"></span>
|
||||||
|
<label class="pj-desc-fmtbtn" id="{{ (fmtbar_id ~ '-imgbtn') if fmtbar_id else 'pj-desc-imgbtn' }}" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="{{ img_input_id or 'pj-desc-img-input' }}" accept="image/*" hidden /></label>
|
||||||
|
</div>
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>{{ page_title or '주간 회의록' }}</title>
|
<title>{{ page_title or '주간 회의록' }}</title>
|
||||||
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
||||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
<link rel="stylesheet" href="/static/erp-dialog.css?v=20261017a" />
|
||||||
{% block head_extra %}{% endblock %}
|
{% block head_extra %}{% endblock %}
|
||||||
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||||
<script>
|
<script>
|
||||||
@@ -17,6 +17,6 @@
|
|||||||
</head>
|
</head>
|
||||||
<body class="erp-body">
|
<body class="erp-body">
|
||||||
<main class="erp-page">{% block content %}{% endblock %}</main>
|
<main class="erp-page">{% block content %}{% endblock %}</main>
|
||||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
<script src="/static/erp-dialog.js?v=20261017a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
project.js initMemberTasks() 가 배선. project/mytasks/inbox 공용. #}
|
project.js initMemberTasks() 가 배선. project/mytasks/inbox 공용. #}
|
||||||
<div class="pj-modal" id="pj-modal-member-tasks" hidden>
|
<div class="pj-modal" id="pj-modal-member-tasks" hidden>
|
||||||
<div class="pj-modal-card pj-mt-card">
|
<div class="pj-modal-card pj-mt-card">
|
||||||
<h3 id="pj-mt-title">작업</h3>
|
<h3 id="pj-mt-title">업무</h3>
|
||||||
<p class="pj-modal-hint">더블클릭하면 작업 편집 창이 열립니다.</p>
|
<p class="pj-modal-hint">더블클릭하면 업무 편집 창이 열립니다.</p>
|
||||||
<div class="pj-mt-head" id="pj-mt-head">
|
<div class="pj-mt-head" id="pj-mt-head">
|
||||||
<span class="pj-mt-h" data-sort="project">프로젝트<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="project">프로젝트<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="stage">섹션<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="stage">섹션<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="title">작업<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="title">업무<span class="pj-mt-sort-icon"></span></span>
|
||||||
<span class="pj-mt-h" data-sort="due">마감일<span class="pj-mt-sort-icon"></span></span>
|
<span class="pj-mt-h" data-sort="due">마감일<span class="pj-mt-sort-icon"></span></span>
|
||||||
</div>
|
</div>
|
||||||
<ul class="pj-mt-list" id="pj-mt-list"></ul>
|
<ul class="pj-mt-list" id="pj-mt-list"></ul>
|
||||||
|
|||||||
@@ -1,24 +1,101 @@
|
|||||||
|
{# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다.
|
||||||
|
· 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원).
|
||||||
|
· 프로젝트 화면(처음 여는 탭)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
|
||||||
|
저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view·
|
||||||
|
data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영.
|
||||||
|
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
|
||||||
<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>
|
||||||
</button>
|
</button>
|
||||||
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
|
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
|
||||||
<form id="pj-options-form">
|
<form id="pj-options-form">
|
||||||
<h2 id="pj-options-title">Project 옵션</h2>
|
<header class="pj-options-head">
|
||||||
<label for="pj-options-font">폰트</label>
|
<h2 id="pj-options-title"><span class="material-symbols-outlined">tune</span> Project 옵션</h2>
|
||||||
<select id="pj-options-font" name="font">
|
<button type="button" class="pj-options-x" id="pj-options-x" aria-label="닫기" title="닫기">
|
||||||
<option value="system">기본 시스템 폰트</option>
|
<span class="material-symbols-outlined">close</span>
|
||||||
<option value="pretendard">프리텐다드</option>
|
</button>
|
||||||
<option value="nanum-square">나눔 스퀘어</option>
|
</header>
|
||||||
<option value="nanum-square-neo">나눔 스퀘어 네오</option>
|
<div class="pj-options-body">
|
||||||
<option value="nanum-square-round">나눔 스퀘어 라운드</option>
|
<nav class="pj-options-nav" role="tablist" aria-orientation="vertical" aria-label="옵션 분류">
|
||||||
</select>
|
<button type="button" role="tab" class="is-active" aria-selected="true" aria-controls="pj-opt-pane-general" id="pj-opt-tab-general" data-pane="general">
|
||||||
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
|
<span class="material-symbols-outlined">text_fields</span>일반</button>
|
||||||
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p>
|
{% if pj_admin %}
|
||||||
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-view" id="pj-opt-tab-view" data-pane="view" tabindex="-1">
|
||||||
<div class="pj-options-actions">
|
<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">
|
||||||
|
<span class="material-symbols-outlined">view_kanban</span>보드</button>
|
||||||
|
{% endif %}
|
||||||
|
{% 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">
|
||||||
|
<span class="material-symbols-outlined">admin_panel_settings</span>관리자</button>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="pj-options-panes">
|
||||||
|
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-general" aria-labelledby="pj-opt-tab-general" data-pane="general">
|
||||||
|
<h3>일반 <span class="pj-options-badge"><span class="material-symbols-outlined">computer</span>이 브라우저에만 적용</span></h3>
|
||||||
|
<div class="pj-options-group">
|
||||||
|
<div class="pj-options-row is-stack">
|
||||||
|
<label for="pj-options-font"><b>폰트</b><small>Project 화면 전체의 글꼴</small></label>
|
||||||
|
<select id="pj-options-font" name="font">
|
||||||
|
<option value="system">기본 시스템 폰트</option>
|
||||||
|
<option value="pretendard">프리텐다드</option>
|
||||||
|
<option value="nanum-square">나눔 스퀘어</option>
|
||||||
|
<option value="nanum-square-neo">나눔 스퀘어 네오</option>
|
||||||
|
<option value="nanum-square-round">나눔 스퀘어 라운드</option>
|
||||||
|
</select>
|
||||||
|
<div class="pj-options-preview" id="pj-options-preview">프로젝트와 목표를 한눈에<br><b>Project · 업무 이름 · 가나다 123</b></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% if pj_admin %}
|
||||||
|
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-view" aria-labelledby="pj-opt-tab-view" data-pane="view" 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-view-label"><b>처음 여는 탭</b><small>왼쪽에서 프로젝트를 고르면 바로 보이는 보기</small></span>
|
||||||
|
<div class="pj-options-views" role="radiogroup" aria-labelledby="pj-options-view-label">
|
||||||
|
<label><input type="radio" name="default_view" value="board"><span class="material-symbols-outlined">view_kanban</span>보드</label>
|
||||||
|
<label><input type="radio" name="default_view" value="list"><span class="material-symbols-outlined">format_list_bulleted</span>목록</label>
|
||||||
|
<label><input type="radio" name="default_view" value="calendar"><span class="material-symbols-outlined">calendar_month</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>
|
||||||
|
</div>
|
||||||
|
<small class="pj-options-note">왼쪽 "전체 보기"는 지금처럼 대시보드로 열립니다.</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-board" aria-labelledby="pj-opt-tab-board" data-pane="board" hidden>
|
||||||
|
<h3>보드 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
|
||||||
|
<div class="pj-options-group">
|
||||||
|
<label class="pj-options-row" for="pj-options-cover">
|
||||||
|
<span class="pj-options-label"><b>카드 표지 이미지</b><small>메인 업무 설명의 첫 이미지를 보드 카드 위에 보여 줍니다</small></span>
|
||||||
|
<span class="pj-switch"><input type="checkbox" role="switch" id="pj-options-cover" name="board_cover"><span aria-hidden="true"></span></span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
{% 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>
|
||||||
|
<h3>관리자</h3>
|
||||||
|
<div class="pj-options-group">
|
||||||
|
<div class="pj-options-row">
|
||||||
|
<span class="pj-options-label"><b>긴급 공지</b><small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></span>
|
||||||
|
<a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 만들기·관리</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<footer class="pj-options-foot">
|
||||||
|
<button type="button" class="pj-btn pj-options-reset" id="pj-options-reset" title="모든 옵션을 처음 값으로(저장해야 반영)">기본값으로</button>
|
||||||
|
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
||||||
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
|
<button type="button" class="pj-btn" id="pj-options-cancel">취소</button>
|
||||||
<button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
|
<button type="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
|
||||||
</div>
|
</footer>
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
<script>
|
<script>
|
||||||
@@ -28,4 +105,4 @@
|
|||||||
document.documentElement.dataset.pjFont = pf;
|
document.documentElement.dataset.pjFont = pf;
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
</script>
|
</script>
|
||||||
<script src="/static/project-options.js?v=20261002g" defer></script>
|
<script src="/static/project-options.js?v=20261016c" defer></script>
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
||||||
<div class="pj-side-search">
|
<div class="pj-side-search">
|
||||||
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
||||||
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="작업 전체 검색" />
|
<input type="search" id="pj-global-search" placeholder="전체 검색 ( / )" autocomplete="off" aria-label="업무 전체 검색" />
|
||||||
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
<div class="pj-search-results" id="pj-search-results" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
<!-- 아사나처럼 맨 위에 개인 메뉴(수신함 / 내 업무). 내 업무는 접었다 펴는
|
||||||
@@ -52,7 +52,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
||||||
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
||||||
<span class="pj-side-navtext">내 작업</span>
|
<span class="pj-side-navtext">내 업무</span>
|
||||||
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
||||||
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
||||||
</a>
|
</a>
|
||||||
@@ -98,6 +98,10 @@
|
|||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
{# 성공하기 — dbx.html(GET /project/dbx)을 닫기 버튼만 있는 별도 창으로(project.js initDbxButton). 프로젝트 목록 바로 위 #}
|
||||||
|
<button type="button" class="pj-btn pj-side-dbx" id="pj-dbx-open">
|
||||||
|
<span class="material-symbols-outlined">emoji_events</span>성공하기</button>
|
||||||
|
|
||||||
<div class="pj-side-block pj-tree-block">
|
<div class="pj-side-block pj-tree-block">
|
||||||
<div class="pj-side-head">
|
<div class="pj-side-head">
|
||||||
<span>프로젝트</span>
|
<span>프로젝트</span>
|
||||||
|
|||||||
@@ -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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -116,11 +116,14 @@
|
|||||||
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||||
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
|
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
|
||||||
</section>
|
</section>
|
||||||
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick">
|
{# 작업 등록 — 주차마다 한 표를 서버에(025, 모두가 같은 표 — project.js initMeetQuickTasks). 제목 = "N주차 작업 등록", 회의 완료면 읽기 전용 #}
|
||||||
<h3>작업 등록 <small>제목을 쓰고 담당자·프로젝트·섹션 칸을 눌러 고른 뒤 [적용]</small></h3>
|
{% set qw = weeks | selectattr("start", "equalto", week) | first %}
|
||||||
|
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick" data-week="{{ week }}"{% if qw and qw.now %} data-now="1"{% endif %}{% if meeting and meeting.completed %} data-locked="1"{% endif %}>
|
||||||
|
<h3>{% if week_n %}<span class="pj-meet-quick-week">{{ week_n }}주차</span> {% endif %}업무 등록
|
||||||
|
<button type="button" class="pj-btn pj-btn-sm pj-meet-quick-expand" data-quick="expand" title="넓은 창에서 업무·세부 업무 등록(같은 표)"><span class="material-symbols-outlined">open_in_full</span>크게 열기</button></h3>
|
||||||
<div class="pj-meet-area-body">
|
<div class="pj-meet-area-body">
|
||||||
<table class="pj-meet-quick-table">
|
<table class="pj-meet-quick-table">
|
||||||
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th></th></tr></thead>
|
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th title="고르면 그 업무의 세부 업무로 등록(비우면 섹션에 새 업무)">업무</th><th></th></tr></thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
|
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
|
||||||
@@ -224,21 +227,25 @@
|
|||||||
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
|
<tbody class="pj-meet-sec" data-section="{{ sec.name }}" style="--goal-bg: {{ sec.color or '#fff' }}">
|
||||||
{% for it in sec.rows %}
|
{% for it in sec.rows %}
|
||||||
{% set p = it.prev %}
|
{% set p = it.prev %}
|
||||||
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}" data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
<tr data-item="{{ it.id }}" data-section="{{ sec.name }}"{% if it.label_hidden %} data-label-cont="1"{% endif %} data-market="{{ it.marketplace_code }}" data-target-amount="{{ it.target_amount if it.target_amount is not none else '' }}"{% if p %} data-prev="{{ p.id }}" data-prev-target="{{ p.target_amount if p.target_amount is not none else '' }}"{% endif %}>
|
||||||
{% if loop.first %}
|
{% if loop.first %}
|
||||||
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
|
<th class="pj-meet-c-sec" rowspan="{{ sec.rows | length }}">{{ sec.name }}
|
||||||
{% if edit %}<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more pj-meet-sec-more" data-meet-act="sec-menu" title="구역 메뉴(위로·아래로) · 우클릭도 됩니다"><span class="material-symbols-outlined">more_horiz</span></button>
|
||||||
|
<button type="button" class="pj-meet-sec-add" data-meet-act="sec-add" title="{{ sec.name }} 구역 끝에 줄 추가">+</button>{% endif %}
|
||||||
</th>
|
</th>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<th class="pj-meet-c-label">
|
{# 항목 칸 — 같은 항목 칸 안에 이어 붙은 줄(027 label_cont)은 그리지 않고 묶음 첫 줄이 rowspan #}
|
||||||
|
{% if not it.label_hidden %}
|
||||||
|
<th class="pj-meet-c-label"{% if (it.label_span or 1) > 1 %} rowspan="{{ it.label_span }}"{% endif %}>
|
||||||
<span class="pj-meet-label-line">
|
<span class="pj-meet-label-line">
|
||||||
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||||
</span>
|
</span>
|
||||||
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
||||||
</th>
|
</th>
|
||||||
|
{% endif %}
|
||||||
{% if not it.content_hidden %}
|
{% if not it.content_hidden %}
|
||||||
<td class="pj-meet-c-text" rowspan="{{ it.content_span or 1 }}" data-meet-item="{{ it.id }}">
|
<td class="pj-meet-c-text" rowspan="{{ it.content_span or 1 }}" data-meet-item="{{ it.id }}">
|
||||||
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
||||||
{% else %}<div class="pj-meet-ro">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>{% endif %}
|
{% else %}<div class="pj-meet-ro">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -251,7 +258,7 @@
|
|||||||
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{% if p.content_html is defined %}{{ p.content_html | safe }}{% else %}{{ p.content }}{% endif %}</div></td>
|
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{% if p.content_html is defined %}{{ p.content_html | safe }}{% else %}{{ p.content }}{% endif %}</div></td>
|
||||||
{# 결과(글) — 지난 주차 줄의 result_note(020). 미적용이면 보기만 #}
|
{# 결과(글) — 지난 주차 줄의 result_note(020). 미적용이면 보기만 #}
|
||||||
<td class="pj-meet-c-text is-prev pj-meet-c-note">
|
<td class="pj-meet-c-text is-prev pj-meet-c-note">
|
||||||
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label_shown if it.label_shown is defined else it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
||||||
{% else %}<div class="pj-meet-ro">{{ p.result_note or '' }}</div>{% endif %}
|
{% else %}<div class="pj-meet-ro">{{ p.result_note or '' }}</div>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td class="pj-meet-c-amt is-prev">{{ p.target_text or won(p.target_amount) }}</td>
|
<td class="pj-meet-c-amt is-prev">{{ p.target_text or won(p.target_amount) }}</td>
|
||||||
@@ -290,6 +297,6 @@
|
|||||||
{% include "project/_member_tasks_modal.html" %}
|
{% include "project/_member_tasks_modal.html" %}
|
||||||
|
|
||||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||||
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
|
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||||
<script src="/static/project.js?v=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<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=20261003d" defer></script>
|
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||||
<script src="/static/project.js?v=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<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 %}
|
||||||
@@ -20,16 +20,16 @@
|
|||||||
<li><a href="#roles">누가 무엇을 할 수 있나요</a></li>
|
<li><a href="#roles">누가 무엇을 할 수 있나요</a></li>
|
||||||
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
||||||
<li><a href="#views">보기 전환과 필터</a></li>
|
<li><a href="#views">보기 전환과 필터</a></li>
|
||||||
<li><a href="#board">보드 — 섹션과 작업 카드</a></li>
|
<li><a href="#board">보드 — 섹션과 업무 카드</a></li>
|
||||||
<li><a href="#card-subtasks">카드에서 세부 작업 다루기</a></li>
|
<li><a href="#card-subtasks">카드에서 세부 업무 다루기</a></li>
|
||||||
<li><a href="#task">작업 편집 창</a></li>
|
<li><a href="#task">업무 편집 창</a></li>
|
||||||
<li><a href="#subtasks">작업 창의 세부 작업</a></li>
|
<li><a href="#subtasks">업무 창의 세부 업무</a></li>
|
||||||
<li><a href="#dates">날짜 고르기</a></li>
|
<li><a href="#dates">날짜 고르기</a></li>
|
||||||
<li><a href="#list">목록 보기</a></li>
|
<li><a href="#list">목록 보기</a></li>
|
||||||
<li><a href="#calendar">캘린더 보기</a></li>
|
<li><a href="#calendar">캘린더 보기</a></li>
|
||||||
<li><a href="#timeline">타임라인 보기</a></li>
|
<li><a href="#timeline">타임라인 보기</a></li>
|
||||||
<li><a href="#dashboard">대시보드</a></li>
|
<li><a href="#dashboard">대시보드</a></li>
|
||||||
<li><a href="#mytasks">내 작업</a></li>
|
<li><a href="#mytasks">내 업무</a></li>
|
||||||
<li><a href="#comments">댓글과 @태그</a></li>
|
<li><a href="#comments">댓글과 @태그</a></li>
|
||||||
<li><a href="#inbox">수신함과 알림</a></li>
|
<li><a href="#inbox">수신함과 알림</a></li>
|
||||||
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
||||||
@@ -59,11 +59,11 @@
|
|||||||
<header class="pjh-hero">
|
<header class="pjh-hero">
|
||||||
<h1>프로젝트 관리 도움말</h1>
|
<h1>프로젝트 관리 도움말</h1>
|
||||||
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
<p>프로젝트 관리는 <b>아사나(Asana) 방식</b>으로 팀의 일을 정리하는 도구입니다.
|
||||||
프로젝트 안에 할 일(작업)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
프로젝트 안에 할 일(업무)을 만들고, 담당자와 마감일을 정하고, 댓글로 이야기하며 끝까지 챙깁니다.
|
||||||
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
||||||
<div class="pjh-quick">
|
<div class="pjh-quick">
|
||||||
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
||||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 작업 추가</span>로 할 일을 만듭니다.</div>
|
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 업무 추가</span>로 할 일을 만듭니다.</div>
|
||||||
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
||||||
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
||||||
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
||||||
@@ -79,15 +79,15 @@
|
|||||||
<tr><th>용어</th><th>뜻</th></tr>
|
<tr><th>용어</th><th>뜻</th></tr>
|
||||||
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
||||||
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
|
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
|
||||||
<tr><td>작업</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 작업 하나입니다.</td></tr>
|
<tr><td>업무</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 업무 하나입니다.</td></tr>
|
||||||
<tr><td>세부 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
|
<tr><td>세부 업무</td><td>업무를 더 잘게 나눈 할 일입니다. 업무 안에 목록으로 붙습니다. 원래 업무는 <b>상위 업무</b>라고 부릅니다.</td></tr>
|
||||||
<tr><td>담당자</td><td>그 작업을 책임지고 하는 사람 한 명입니다.</td></tr>
|
<tr><td>담당자</td><td>그 업무를 책임지고 하는 사람 한 명입니다.</td></tr>
|
||||||
<tr><td>협업자</td><td>작업의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
<tr><td>협업자</td><td>업무의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
||||||
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
||||||
<tr><td>우선순위</td><td>높음 · 보통 · 낮음. 급한 일을 표시합니다.</td></tr>
|
<tr><td>우선순위</td><td>높음 · 보통 · 낮음. 급한 일을 표시합니다.</td></tr>
|
||||||
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 작업이 쌓입니다.</td></tr>
|
<tr><td>@태그</td><td>설명이나 댓글에서 <kbd>@</kbd>를 누르고 사람을 고르면, 그 사람의 수신함에 업무가 쌓입니다.</td></tr>
|
||||||
<tr><td>수신함</td><td>나를 태그한 작업과 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
<tr><td>수신함</td><td>나를 태그한 업무와 나에게 온 알림을 모아 보는 곳입니다.</td></tr>
|
||||||
<tr><td>내 작업</td><td>모든 프로젝트에서 내가 담당자인 작업만 모아 보는 곳입니다.</td></tr>
|
<tr><td>내 업무</td><td>모든 프로젝트에서 내가 담당자인 업무만 모아 보는 곳입니다.</td></tr>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -96,28 +96,33 @@
|
|||||||
<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>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<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>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 작업을 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 업무를 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
||||||
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
<li><b>수신함</b> — 나를 태그한 업무와 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
<li><b>내 업무</b> — 내가 담당자인 업무 모음. 숫자 배지는 아직 끝나지 않은 업무 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
<li><b>휴지통</b> — 지운 업무를 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||||
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
||||||
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
||||||
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
||||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||||
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 업무를 한눈에 봅니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>위쪽 바</h3>
|
<h3>위쪽 바</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">notifications</span></span> 종 아이콘 — 읽지 않은 알림 수가 표시되고, 누르면 수신함으로 갑니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">fit_screen</span></span> 화면 배율 — 누르면(파랗게 켜짐) 화면 전체를 75%로 줄입니다. 2880×1620 모니터를 Windows 배율 200%로 쓰면 화면이 꽉 차 보이는데, 이때 켜면 1920×1080 모니터와 같은 모습이 됩니다. 브라우저마다 기억합니다. 메뉴·말풍선 같은 작은 팝업은 원래 크기로 뜹니다.</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">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 폰트를 고르고 미리 본 뒤 <span class="pjh-ui">저장</span>을 누르면 Project 화면에 적용되고 창이 닫힙니다.
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
|
||||||
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
|
||||||
|
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
|
||||||
|
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
|
||||||
|
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
|
||||||
|
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
|
||||||
|
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>프로젝트 제목</h3>
|
<h3>프로젝트 제목</h3>
|
||||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
|
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
|
||||||
@@ -134,8 +139,8 @@
|
|||||||
<h3>프로젝트</h3>
|
<h3>프로젝트</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||||
<tr><td>프로젝트 보기, 작업·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
<tr><td>프로젝트 보기, 업무·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
<tr><td>작업 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
|
<tr><td>업무 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</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>O</td></tr>
|
<tr><td>서브프로젝트 만들기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
<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>
|
||||||
@@ -146,13 +151,13 @@
|
|||||||
<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>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>사이드바 “전체 멤버”</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>
|
||||||
</table>
|
</table>
|
||||||
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 작업은 원래 프로젝트 멤버가 아니면
|
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 업무는 원래 프로젝트 멤버가 아니면
|
||||||
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고,
|
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 업무는 내 업무·수신함·알림·검색에서 사라지고,
|
||||||
예전 링크로도 열리지 않습니다.</p>
|
예전 링크로도 열리지 않습니다.</p>
|
||||||
<h3>목표·주간 회의록</h3>
|
<h3>목표·주간 회의록</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
@@ -166,7 +171,7 @@
|
|||||||
<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>회의록 보드 열기·링크 복사</td><td>O</td><td>O</td><td>O</td></tr>
|
<tr><td>회의록 보드 열기·링크 복사</td><td>O</td><td>O</td><td>O</td></tr>
|
||||||
<tr><td>회의록 “작업 등록 표”로 작업 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
<tr><td>회의록 “업무 등록 표”로 업무 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -199,14 +204,14 @@
|
|||||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
||||||
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
||||||
<h3>프로젝트 삭제</h3>
|
<h3>프로젝트 삭제</h3>
|
||||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 업무도 모두 함께 지워집니다.</p>
|
||||||
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
||||||
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
||||||
<h3>멤버 배정 (Pro user 이상)</h3>
|
<h3>멤버 배정 (Pro user 이상)</h3>
|
||||||
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
|
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
|
||||||
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 작업 목록이 뜹니다.</li>
|
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 업무 목록이 뜹니다.</li>
|
||||||
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
@@ -215,7 +220,7 @@
|
|||||||
<section class="pjh-sec" id="views">
|
<section class="pjh-sec" id="views">
|
||||||
<h2><span class="pjh-num">5</span>보기 전환과 필터</h2>
|
<h2><span class="pjh-num">5</span>보기 전환과 필터</h2>
|
||||||
<h3>보기 탭</h3>
|
<h3>보기 탭</h3>
|
||||||
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 작업을 다른 모양으로 봅니다.</p>
|
<p>프로젝트 화면 맨 위 왼쪽의 탭으로 같은 업무를 다른 모양으로 봅니다.</p>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>탭</th><th>이럴 때 좋아요</th></tr>
|
<tr><th>탭</th><th>이럴 때 좋아요</th></tr>
|
||||||
<tr><td>보드</td><td>섹션(단계)별 카드로 흐름을 볼 때. 카드를 끌어 단계를 옮깁니다. (<a href="#board">6장</a>)</td></tr>
|
<tr><td>보드</td><td>섹션(단계)별 카드로 흐름을 볼 때. 카드를 끌어 단계를 옮깁니다. (<a href="#board">6장</a>)</td></tr>
|
||||||
@@ -225,12 +230,12 @@
|
|||||||
<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>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
|
||||||
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.
|
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
|
||||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 작업</b>도 한 번씩 함께 보입니다.</p>
|
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
|
||||||
<h3>필터 바</h3>
|
<h3>필터 바</h3>
|
||||||
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
<p>탭 아래 한 줄로 업무를 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>찾기</b> — 제목·설명·담당자에 들어간 글자로 거릅니다.</li>
|
<li><b>찾기</b> — 제목·설명·담당자에 들어간 글자로 거릅니다.</li>
|
||||||
<li><b>상태</b> — 전체 / 미완료 / 완료</li>
|
<li><b>상태</b> — 전체 / 미완료 / 완료</li>
|
||||||
@@ -246,64 +251,66 @@
|
|||||||
|
|
||||||
<!-- 6. 보드 -->
|
<!-- 6. 보드 -->
|
||||||
<section class="pjh-sec" id="board">
|
<section class="pjh-sec" id="board">
|
||||||
<h2><span class="pjh-num">6</span>보드 — 섹션과 작업 카드</h2>
|
<h2><span class="pjh-num">6</span>보드 — 섹션과 업무 카드</h2>
|
||||||
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
<p class="pjh-lead">보드는 섹션(세로 칸)이 옆으로 늘어선 화면입니다. 섹션이 많으면 가로로 스크롤되고, 한 섹션에 카드가 많으면 그 섹션 안에서만 세로로 스크롤됩니다.</p>
|
||||||
<h3>섹션 다루기</h3>
|
<h3>섹션 다루기</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·작업 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
<li><b>그룹 축소</b> — 섹션 머리의 왼쪽 화살표를 누르면 카드가 숨겨지고 제목·업무 수가 세로로 표시됩니다. 반대 방향 화살표를 누르면 펼쳐집니다. 축소 상태는 내 브라우저에 기억됩니다.</li>
|
||||||
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
<li><b>섹션 추가</b> — 마지막 섹션 바로 오른쪽의 <span class="pjh-ui">+ 섹션 추가</span>.</li>
|
||||||
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
<li><b>이름 바꾸기</b> — 섹션 이름을 누르면 그 자리에서 고칩니다. <kbd>Enter</kbd> 저장, <kbd>Esc</kbd> 취소.</li>
|
||||||
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
||||||
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="pjh-ui">메인 작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
<li><span class="pjh-ui">메인 업무 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||||
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
||||||
<li><span class="pjh-ui">섹션 작업 모두 완료</span> — 그 섹션의 미완료 작업을 한 번에 완료합니다.</li>
|
<li><span class="pjh-ui">섹션 업무 모두 완료</span> — 그 섹션의 미완료 업무를 한 번에 완료합니다.</li>
|
||||||
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
||||||
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 작업은 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
<li><span class="pjh-ui">삭제</span> — 섹션을 만든 사람만. 안의 업무는 지워지지 않고 “미지정” 칸으로 모입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 업무를 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||||
<h3>작업 카드 다루기</h3>
|
<h3>업무 카드 다루기</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>상단 메인 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
<li><b>상단 메인 업무 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 업무 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||||
<li><b>하단 메인 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
<li><b>하단 메인 업무 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 업무 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>업무 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 업무를 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
<li><b>열기</b> — 카드를 누르면 오른쪽에 업무 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||||
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 작업은 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 작업은 상태만 표시합니다.</li>
|
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 업무는 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 업무는 상태만 표시합니다.</li>
|
||||||
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
||||||
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.</li>
|
<li><b>파일 첨부</b> — 컴퓨터의 파일을 카드 위로 끌어 오면 카드에 점선과 <span class="pjh-ui">놓으면 이 업무에 첨부</span>가 보이고, 놓으면 그 업무의 첨부 파일로 올라갑니다(여러 개 가능).</li>
|
||||||
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 작업 링크 복사 · 완료로 표시 · 삭제</span></li>
|
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.
|
||||||
|
끄는 동안 카드는 살짝 기울어진 모양으로 마우스를 따라오고, 카드 사이를 지나는 순간 <b>점선 자리</b>가 그 사이로 옮겨 가며 다른 카드가 미끄러지듯 비켜납니다 — 놓으면 그 자리에 그대로 들어갑니다(다른 섹션도 같음). 섹션 밖에 놓으면 원래 자리로 돌아갑니다.</li>
|
||||||
|
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 업무 링크 복사 · 완료로 표시 · 삭제</span></li>
|
||||||
<li><b>댓글</b> — 카드의 <span class="pjh-ui">💬 N</span>을 한 번 누르면 댓글 대화창이 열립니다. (<a href="#comments">16장</a>)</li>
|
<li><b>댓글</b> — 카드의 <span class="pjh-ui">💬 N</span>을 한 번 누르면 댓글 대화창이 열립니다. (<a href="#comments">16장</a>)</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>마감일 색의 의미</h3>
|
<h3>마감일 색의 의미</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>표시</th><th>뜻</th></tr>
|
<tr><th>표시</th><th>뜻</th></tr>
|
||||||
<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>
|
||||||
</table>
|
</table>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 7. 카드의 세부 작업 -->
|
<!-- 7. 카드의 세부 작업 -->
|
||||||
<section class="pjh-sec" id="card-subtasks">
|
<section class="pjh-sec" id="card-subtasks">
|
||||||
<h2><span class="pjh-num">7</span>카드에서 세부 작업 다루기</h2>
|
<h2><span class="pjh-num">7</span>카드에서 세부 업무 다루기</h2>
|
||||||
<p class="pjh-lead">세부 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 작업 목록이 펼쳐집니다.</p>
|
<p class="pjh-lead">세부 업무가 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 업무 목록이 펼쳐집니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
||||||
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
||||||
<li><b>열기</b> — 줄을 누르면 그 세부 작업이 작업처럼 편집 창으로 열립니다.</li>
|
<li><b>열기</b> — 줄을 누르면 그 세부 업무가 업무처럼 편집 창으로 열립니다.</li>
|
||||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 세부 작업 삭제</span></li>
|
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 업무 열기 · 완료로 표시 · 세부 업무 삭제</span></li>
|
||||||
<li><b>순서 바꾸기</b> — 펼친 세부 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
<li><b>순서 바꾸기</b> — 펼친 세부 업무 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||||
<li><b>다른 작업으로 옮기기</b> — 세부 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 세부 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
<li><b>다른 업무로 옮기기</b> — 세부 업무 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 업무의 세부 업무가 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>+ 세부 작업 추가</h3>
|
<h3>+ 세부 업무 추가</h3>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 작업 추가</span>를 누릅니다.</li>
|
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 업무 추가</span>를 누릅니다.</li>
|
||||||
<li>새 줄의 “작업 이름 입력” 칸에 이름을 씁니다.</li>
|
<li>새 줄의 “업무 이름 입력” 칸에 이름을 씁니다.</li>
|
||||||
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
||||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 작업을 이어서 쓸 수 있습니다.</li>
|
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 업무를 이어서 쓸 수 있습니다.</li>
|
||||||
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
||||||
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
@@ -311,23 +318,23 @@
|
|||||||
|
|
||||||
<!-- 8. 작업 편집 창 -->
|
<!-- 8. 작업 편집 창 -->
|
||||||
<section class="pjh-sec" id="task">
|
<section class="pjh-sec" id="task">
|
||||||
<h2><span class="pjh-num">8</span>작업 편집 창</h2>
|
<h2><span class="pjh-num">8</span>업무 편집 창</h2>
|
||||||
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 작업 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
<p class="pjh-lead">카드·목록 줄·캘린더 막대를 누르면 화면 오른쪽에 업무 편집 창이 열립니다. 창의 왼쪽 가장자리를 끌면 너비를 넓히거나 좁힐 수 있습니다.</p>
|
||||||
<h3>맨 위 버튼</h3>
|
<h3>맨 위 버튼</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>버튼</th><th>하는 일</th></tr>
|
<tr><th>버튼</th><th>하는 일</th></tr>
|
||||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
|
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 업무의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 업무를 엽니다.</td></tr>
|
||||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>업무를 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||||
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 세부 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
|
<tr><td><span class="pjh-ui">삭제</span></td><td>업무를 지웁니다(만든 사람만). 세부 업무가 있으면 함께 지울지 한 번 더 묻습니다. 지운 업무는 휴지통에 3개월 보관됩니다.</td></tr>
|
||||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 업무를 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||||
</table>
|
</table>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 업무는 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 업무 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||||
<h3>제목과 기본 정보</h3>
|
<h3>제목과 기본 정보</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
||||||
<li><b>담당자</b> — 사진+이름을 누르면 “아이콘 + 이름” 목록에서 고릅니다. <span class="pjh-ui">담당자 없음</span>도 있습니다.</li>
|
<li><b>담당자</b> — 사진+이름을 누르면 “아이콘 + 이름” 목록에서 고릅니다. <span class="pjh-ui">담당자 없음</span>도 있습니다.</li>
|
||||||
<li><b>섹션</b> — 이 작업이 들어갈 섹션을 고릅니다.</li>
|
<li><b>섹션</b> — 이 업무가 들어갈 섹션을 고릅니다.</li>
|
||||||
<li><b>우선순위</b> — 높음 · 보통 · 낮음</li>
|
<li><b>우선순위</b> — 높음 · 보통 · 낮음</li>
|
||||||
<li><b>마감일</b> — 달력 아이콘을 누르면 날짜 창이 열립니다. (<a href="#dates">10장</a>)</li>
|
<li><b>마감일</b> — 달력 아이콘을 누르면 날짜 창이 열립니다. (<a href="#dates">10장</a>)</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -336,47 +343,49 @@
|
|||||||
<li>협업자는 사진+이름으로 보입니다. 사람에 마우스를 올리면 <span class="pjh-ui">×</span>가 나와 뺄 수 있습니다.</li>
|
<li>협업자는 사진+이름으로 보입니다. 사람에 마우스를 올리면 <span class="pjh-ui">×</span>가 나와 뺄 수 있습니다.</li>
|
||||||
<li>협업자가 없으면 점선 원 <span class="pjh-ui">협업자 없음</span>을 눌러 추가하고, 있으면 옆 <span class="pjh-ui">+</span>로 추가합니다.</li>
|
<li>협업자가 없으면 점선 원 <span class="pjh-ui">협업자 없음</span>을 눌러 추가하고, 있으면 옆 <span class="pjh-ui">+</span>로 추가합니다.</li>
|
||||||
<li>오른쪽 <span class="pjh-ui">협업자로 참여</span> / <span class="pjh-ui">협업자에서 나가기</span>로 나 자신을 넣고 뺍니다.</li>
|
<li>오른쪽 <span class="pjh-ui">협업자로 참여</span> / <span class="pjh-ui">협업자에서 나가기</span>로 나 자신을 넣고 뺍니다.</li>
|
||||||
<li>협업자에게는 작업 완료와 새 댓글 알림이 갑니다.</li>
|
<li>협업자에게는 업무 완료와 새 댓글 알림이 갑니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>설명</h3>
|
<h3>설명</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>서식 도구(왼쪽부터): <span class="pjh-ui"><span class="material-symbols-outlined">format_bold</span></span> 굵게 · <span class="pjh-ui"><span class="material-symbols-outlined">format_italic</span></span> 기울임 · <span class="pjh-ui"><span class="material-symbols-outlined">format_underlined</span></span> 밑줄 · <span class="pjh-ui"><span class="material-symbols-outlined">format_strikethrough</span></span> 취소선(<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>) · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_bulleted</span></span> 글머리 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_numbered</span></span> 번호 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span> 체크박스 · <span class="pjh-ui"><span class="material-symbols-outlined">format_quote</span></span> 인용 · <span class="pjh-ui"><span class="material-symbols-outlined">link</span></span> 링크 · <span class="pjh-ui"><span class="material-symbols-outlined">format_clear</span></span> 서식 지우기 · <span class="pjh-ui"><span class="material-symbols-outlined">image</span></span> 이미지 넣기. 아이콘에 마우스를 올리면 이름이 나옵니다.</li>
|
<li>서식 도구(왼쪽부터): <span class="pjh-ui"><span class="material-symbols-outlined">format_bold</span></span> 굵게 · <span class="pjh-ui"><span class="material-symbols-outlined">format_italic</span></span> 기울임 · <span class="pjh-ui"><span class="material-symbols-outlined">format_underlined</span></span> 밑줄 · <span class="pjh-ui"><span class="material-symbols-outlined">format_strikethrough</span></span> 취소선(<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd>) · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_bulleted</span></span> 글머리 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">format_list_numbered</span></span> 번호 목록 · <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span> 체크박스 · <span class="pjh-ui"><span class="material-symbols-outlined">format_quote</span></span> 인용 · <span class="pjh-ui"><span class="material-symbols-outlined">link</span></span> 링크 · <span class="pjh-ui"><span class="material-symbols-outlined">format_clear</span></span> 서식 지우기 · <span class="pjh-ui"><span class="material-symbols-outlined">image</span></span> 이미지 넣기. 아이콘에 마우스를 올리면 이름이 나옵니다.</li>
|
||||||
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
<li><b>체크박스(체크리스트)</b> — 글머리 목록처럼 씁니다. <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 지금 줄(또는 고른 줄들)이 체크리스트가 되어 줄마다 체크박스가 붙습니다. <kbd>Enter</kbd>로 새 줄을 만들면 체크박스도 함께 생기고, 빈 줄에서 <kbd>Enter</kbd>를 누르면 목록이 끝납니다. 체크박스를 누르면 체크되고 그 줄은 흐리게 취소선이 그어집니다. 다시 <span class="pjh-ui"><span class="material-symbols-outlined">check_box</span></span>를 누르면 평범한 글로, 글머리·번호 버튼을 누르면 그 목록으로 바뀝니다. 체크 상태도 바로 저장됩니다.</li>
|
||||||
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.</li>
|
<li><b>이미지</b> — 캡처한 그림을 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 바로 붙여 넣을 수 있습니다. 그림을 누르면 모서리를 끌어 크기를 바꾸거나 지울 수 있습니다.
|
||||||
|
그림을 누른 채 <kbd>Ctrl</kbd>+<kbd>C</kbd>를 누르면 그림이 복사되어 카카오톡·한글·그림판 등에 그대로 붙습니다. 그림을 더블클릭해 연 창에서는 아래 <span class="pjh-ui">복사</span> 버튼이나 <kbd>Ctrl</kbd>+<kbd>C</kbd>로 복사합니다(마우스 오른쪽 메뉴의 "이미지 복사"는 일부 프로그램에서 빈칸으로 붙을 수 있습니다).</li>
|
||||||
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
<li><b>링크</b> — 웹 주소를 붙여 넣으면 자동으로 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 작업이 쌓입니다.</li>
|
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 업무가 쌓입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>첨부 파일</h3>
|
<h3>첨부 파일</h3>
|
||||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||||
|
<p><b>끌어 놓기</b> — 컴퓨터의 파일을 업무 창 <b>아무 곳에나</b> 끌어 오면 창 전체에 점선 안내가 뜨고, 놓으면 첨부 파일로 올라갑니다(여러 개 한꺼번에, 설명칸에 놓아도 첨부). 아직 제목을 쓰지 않은 새 업무·읽기 전용 업무에는 첨부되지 않습니다. 보드의 메인 업무 카드에 파일을 놓아도 그 업무에 첨부됩니다.</p>
|
||||||
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
||||||
<p>작업 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 작업을 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
<p>업무 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 업무를 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
||||||
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
||||||
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
<li><span class="pjh-ui">다른 프로젝트에 추가</span>를 누릅니다. 빼려면 이름 옆 <span class="pjh-ui">×</span>(연결 해제).</li>
|
||||||
</ol>
|
</ol>
|
||||||
<p>작업은 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 작업의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
<p>업무는 하나라서 원래 프로젝트에서 고친 내용이 연결된 보드에도 반영됩니다. 원래 프로젝트의 멤버가 아니면 연결된 업무의 내용·댓글·첨부는 읽기만 할 수 있습니다. 연결된 보드 안에서 섹션을 옮기는 것은 가능합니다.</p>
|
||||||
<h3>댓글</h3>
|
<h3>댓글</h3>
|
||||||
<p>작업 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
<p>업무 창 맨 아래에 항상 고정된 댓글 칸에 쓰고 <kbd>Enter</kbd>(스크롤해도 그 자리에 있습니다). 칸 오른쪽 <span class="pjh-ui">☺</span>는 이모티콘, <span class="pjh-ui">@</span>는 멤버 태그입니다. 답글은 원 댓글 아래 들여 쓰여 <span class="pjh-ui">↳</span> 표시와 함께 보입니다. 내가 쓴 댓글은 <span class="pjh-ui">✎</span>로 고치고 <span class="pjh-ui">×</span>로 지웁니다. 댓글 속 웹 주소는 링크가 됩니다. 댓글에 붙인 파일은 그 댓글 아래에 보이고(파일만 보낸 댓글도), 첨부 파일 목록에는 <span class="pjh-ui">댓글</span> 표시가 붙습니다.</p>
|
||||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 업무를 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 9. 작업 창의 세부 작업 -->
|
<!-- 9. 작업 창의 세부 작업 -->
|
||||||
<section class="pjh-sec" id="subtasks">
|
<section class="pjh-sec" id="subtasks">
|
||||||
<h2><span class="pjh-num">9</span>작업 창의 세부 작업</h2>
|
<h2><span class="pjh-num">9</span>업무 창의 세부 업무</h2>
|
||||||
<p class="pjh-lead">작업 편집 창 가운데 “세부 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
<p class="pjh-lead">업무 편집 창 가운데 “세부 업무” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
||||||
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
||||||
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
||||||
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
||||||
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
||||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 작업이 편집 창으로 열립니다.</li>
|
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 업무가 편집 창으로 열립니다.</li>
|
||||||
<li><b>세부 작업의 세부 작업</b> — 그 세부 작업 안에도 세부 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
<li><b>세부 업무의 세부 업무</b> — 그 세부 업무 안에도 세부 업무가 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 작업 삭제</span>.</li>
|
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 업무 삭제</span>.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>세부 작업을 열었을 때</h3>
|
<h3>세부 업무를 열었을 때</h3>
|
||||||
<p>세부 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 세부 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
<p>세부 업무도 업무와 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 업무 이름</span>이 보이고, 누르면 상위 업무로 돌아갑니다. 세부 업무에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 10. 날짜 -->
|
<!-- 10. 날짜 -->
|
||||||
@@ -391,7 +400,7 @@
|
|||||||
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div>보드 카드와 세부 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
<div>보드 카드와 세부 업무 줄에서는 날짜를 누르는 즉시 저장됩니다. 업무 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 11. 목록 -->
|
<!-- 11. 목록 -->
|
||||||
@@ -399,9 +408,9 @@
|
|||||||
<h2><span class="pjh-num">11</span>목록 보기</h2>
|
<h2><span class="pjh-num">11</span>목록 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>이 프로젝트</b> 범위에서는 섹션별로 묶여 보이고, <b>전체 프로젝트</b>에서는 프로젝트·섹션이 칸으로 나오는 표가 됩니다.</li>
|
<li><b>이 프로젝트</b> 범위에서는 섹션별로 묶여 보이고, <b>전체 프로젝트</b>에서는 프로젝트·섹션이 칸으로 나오는 표가 됩니다.</li>
|
||||||
<li>칸 제목(작업 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
<li>칸 제목(업무 · 담당자 · 섹션 · 우선순위 · 시작 · 마감)을 누르면 그 기준으로 정렬하고, 한 번 더 누르면 반대로 정렬합니다.</li>
|
||||||
<li>칸 제목 사이 경계를 끌면 칸 너비가 바뀝니다.</li>
|
<li>칸 제목 사이 경계를 끌면 칸 너비가 바뀝니다.</li>
|
||||||
<li>줄을 누르면 작업 편집 창, 우클릭하면 작업 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
<li>줄을 누르면 업무 편집 창, 우클릭하면 업무 메뉴, <span class="pjh-ui">💬</span>를 누르면 댓글 대화창이 열립니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -409,11 +418,11 @@
|
|||||||
<section class="pjh-sec" id="calendar">
|
<section class="pjh-sec" id="calendar">
|
||||||
<h2><span class="pjh-num">12</span>캘린더 보기</h2>
|
<h2><span class="pjh-num">12</span>캘린더 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>한 달 달력에 작업이 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
<li>한 달 달력에 업무가 <b>시작일~마감일</b> 막대로 표시됩니다(시작일이 없으면 마감일 하루). 공휴일은 빨간색입니다.</li>
|
||||||
<li><span class="pjh-ui">‹</span> <span class="pjh-ui">›</span>로 지난달·다음 달로 갑니다.</li>
|
<li><span class="pjh-ui">‹</span> <span class="pjh-ui">›</span>로 지난달·다음 달로 갑니다.</li>
|
||||||
<li>막대를 <b>누르면</b> 작업 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
<li>막대를 <b>누르면</b> 업무 편집 창이 열리고, <b>끌어서 다른 날에 놓으면</b> 날짜가 옮겨집니다.</li>
|
||||||
<li>하루에 작업이 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 작업 목록이 뜹니다.</li>
|
<li>하루에 업무가 많으면 <span class="pjh-ui">+N</span>이 나옵니다. 누르면 그날 업무 목록이 뜹니다.</li>
|
||||||
<li>막대 우클릭 → 작업 메뉴(열기 · 작업 링크 복사 · 완료로 표시 · 삭제).</li>
|
<li>막대 우클릭 → 업무 메뉴(열기 · 업무 링크 복사 · 완료로 표시 · 삭제).</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -421,14 +430,14 @@
|
|||||||
<section class="pjh-sec" id="timeline">
|
<section class="pjh-sec" id="timeline">
|
||||||
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>기간이 있는(시작일 또는 마감일이 있는) 작업이 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
<li>기간이 있는(시작일 또는 마감일이 있는) 업무가 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
||||||
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
|
<li>업무는 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 업무는 기간만큼 막대로 늘어납니다.</li>
|
||||||
<li>카드에 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 작업은 작업 편집 창에서 봅니다.</li>
|
<li>카드에 세부 업무가 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 업무 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 업무는 업무 편집 창에서 봅니다.</li>
|
||||||
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
|
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
|
||||||
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 작업은 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 업무는 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
||||||
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
||||||
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
||||||
<li>카드의 <b>작업 이름을 누르면</b> 오른쪽에 작업 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 작업 메뉴. 마우스를 올리면 작업 정보가 보입니다.</li>
|
<li>카드의 <b>업무 이름을 누르면</b> 오른쪽에 업무 편집 창이 열립니다(더블클릭도 같음). <b>우클릭</b> → 업무 메뉴. 마우스를 올리면 업무 정보가 보입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -436,24 +445,24 @@
|
|||||||
<section class="pjh-sec" id="dashboard">
|
<section class="pjh-sec" id="dashboard">
|
||||||
<h2><span class="pjh-num">14</span>대시보드</h2>
|
<h2><span class="pjh-num">14</span>대시보드</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>위쪽 숫자 카드 4개: <b>완료된 작업 합계 · 미완료 작업 합계 · 마감일이 지난 작업 합계 · 작업 합계</b></li>
|
<li>위쪽 숫자 카드 4개: <b>완료된 업무 합계 · 미완료 업무 합계 · 마감일이 지난 업무 합계 · 업무 합계</b></li>
|
||||||
<li><b>미완료 작업 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
<li><b>미완료 업무 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
||||||
<li><b>작업 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
<li><b>업무 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
||||||
<li><b>담당자별 작업 합계(메인·세부 작업, 완료)</b> — 이 범위에서 사람별로 배정된 작업 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 작업·세부 작업 세로 막대</b>로 보여 줍니다(막대 하나 = 그 작업 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 작업 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 작업은 세부 작업에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
<li><b>담당자별 업무 합계(메인·세부 업무, 완료)</b> — 이 범위에서 사람별로 배정된 업무 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 업무·세부 업무 세로 막대</b>로 보여 줍니다(막대 하나 = 그 업무 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 업무 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 업무는 세부 업무에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
||||||
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 15. 내 작업 -->
|
<!-- 15. 내 작업 -->
|
||||||
<section class="pjh-sec" id="mytasks">
|
<section class="pjh-sec" id="mytasks">
|
||||||
<h2><span class="pjh-num">15</span>내 작업</h2>
|
<h2><span class="pjh-num">15</span>내 업무</h2>
|
||||||
<p class="pjh-lead">왼쪽 사이드바 <b>내 작업</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 작업만 한 표로 보여줍니다.</p>
|
<p class="pjh-lead">왼쪽 사이드바 <b>내 업무</b>(프로젝트 관리 첫 화면)은 모든 프로젝트에서 내가 담당자인 업무만 한 표로 보여줍니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>위쪽 탭 <span class="pjh-ui">진행 중 · 완료 · 전체</span>로 고릅니다. 옆에 전체 개수와 지연(마감 지남) 개수가 나옵니다.</li>
|
<li>위쪽 탭 <span class="pjh-ui">진행 중 · 완료 · 전체</span>로 고릅니다. 옆에 전체 개수와 지연(마감 지남) 개수가 나옵니다.</li>
|
||||||
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
||||||
<li>칸 제목을 누르면 정렬합니다.</li>
|
<li>칸 제목을 누르면 정렬합니다.</li>
|
||||||
<li>줄을 누르면 그 작업의 프로젝트 화면으로 가서 작업 편집 창이 바로 열립니다. 우클릭하면 작업 메뉴가 나옵니다.</li>
|
<li>줄을 누르면 그 업무의 프로젝트 화면으로 가서 업무 편집 창이 바로 열립니다. 우클릭하면 업무 메뉴가 나옵니다.</li>
|
||||||
<li>내가 담당자인 세부 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
<li>내가 담당자인 세부 업무는 상위 업무 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -461,26 +470,26 @@
|
|||||||
<section class="pjh-sec" id="comments">
|
<section class="pjh-sec" id="comments">
|
||||||
<h2><span class="pjh-num">16</span>댓글과 @태그</h2>
|
<h2><span class="pjh-num">16</span>댓글과 @태그</h2>
|
||||||
<h3>댓글 대화창</h3>
|
<h3>댓글 대화창</h3>
|
||||||
<p>카드·목록·캘린더·내 작업에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
<p>카드·목록·캘린더·내 업무에 보이는 <span class="pjh-ui">💬 N</span>을 <b>한 번 누르면</b> 메신저처럼 생긴 댓글 대화창이 열립니다.</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>. <kbd>Shift</kbd>+<kbd>Enter</kbd>로 줄바꿈합니다. 입력칸은 높이 70px로 고정되며 긴 글은 칸 안에서 스크롤됩니다.</li>
|
<li>입력칸에 쓰고 <span class="pjh-ui">전송</span> 또는 <kbd>Enter</kbd>. <kbd>Shift</kbd>+<kbd>Enter</kbd>로 줄바꿈합니다. 입력칸은 높이 70px로 고정되며 긴 글은 칸 안에서 스크롤됩니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">attach_file</span></span>로 파일을 붙이거나, 캡처한 이미지를 <kbd>Ctrl</kbd>+<kbd>V</kbd>로 붙여 넣습니다. 이미지는 작은 그림으로 보입니다.</li>
|
||||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 작업 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
<li><span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>를 누르면 이모티콘 창이 열립니다. 종류별 탭으로 넘기거나 <b>검색</b>(예: 축하, 감사, 완료)으로 찾고, 누르면 커서 자리에 들어갑니다. 자주 쓴 이모티콘은 맨 위에 모입니다. 업무 팝업 아래 댓글 입력칸에도 같은 버튼이 있습니다.</li>
|
||||||
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
<li>웹 주소를 붙여 넣으면 링크가 되고, 누르면 새 탭에서 열립니다.</li>
|
||||||
<li>아직 읽지 않은 새 댓글이 있으면 말풍선이 깜빡이고 숫자가 빨간색으로 바뀝니다.</li>
|
<li>아직 읽지 않은 새 댓글이 있으면 말풍선이 깜빡이고 숫자가 빨간색으로 바뀝니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>반응 · 답글 · 완료 표시 (아사나식)</h3>
|
<h3>반응 · 답글 · 완료 표시 (아사나식)</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>반응</b> — 댓글에 마우스를 올리면 오른쪽 위에 👍 👀 🙌 ✅ 와 <span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>가 뜹니다. 누르면 댓글 아래에 반응이 붙고(누른 사람 수), 내가 누른 반응은 파랗게 보입니다. 다시 누르면 취소됩니다. 반응에 마우스를 올리면 누가 눌렀는지 보입니다.</li>
|
<li><b>반응</b> — 댓글에 마우스를 올리면 오른쪽 위에 👍 👀 🙌 ✅ 와 <span class="pjh-ui"><span class="material-symbols-outlined">add_reaction</span></span>가 뜹니다. 누르면 댓글 아래에 반응이 붙고(누른 사람 수), 내가 누른 반응은 파랗게 보입니다. 다시 누르면 취소됩니다. 반응에 마우스를 올리면 누가 눌렀는지 보입니다.</li>
|
||||||
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 작업 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
<li><b>답글</b> — 같은 도구 모음의 <span class="pjh-ui"><span class="material-symbols-outlined">reply</span></span>. 업무 창에서는 원 댓글 아래 들여쓰기로 달리고, 댓글 대화창에서는 입력칸 위에 “OO 님에게 답글”이 뜬 뒤 보내면 말풍선 위에 원 댓글이 인용됩니다. 원 댓글을 지우면 답글도 함께 지워집니다.</li>
|
||||||
<li><b>작업 완료</b> — 작업을 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 작업을 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
<li><b>업무 완료</b> — 업무를 완료하면 댓글 사이에 <span class="pjh-ui">✔ OO 님이 이 업무를 완료했습니다</span> 줄이 자동으로 생깁니다(댓글 수에는 세지 않습니다). 완료를 취소하면 이 줄도 사라지고, 다시 완료하면 마지막 완료 한 줄만 보입니다.</li>
|
||||||
<li><b>@태그 표시</b> — 댓글 속 <kbd>@아이디</kbd>는 프로필 아이콘 + 이름 칩으로 보입니다.</li>
|
<li><b>@태그 표시</b> — 댓글 속 <kbd>@아이디</kbd>는 프로필 아이콘 + 이름 칩으로 보입니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>@태그로 동료 부르기</h3>
|
<h3>@태그로 동료 부르기</h3>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li>설명이나 댓글에서 <kbd>@</kbd>를 누릅니다.</li>
|
<li>설명이나 댓글에서 <kbd>@</kbd>를 누릅니다.</li>
|
||||||
<li>이름 몇 글자를 치면 목록이 좁혀집니다. 방향키와 <kbd>Enter</kbd> 또는 마우스로 고릅니다.</li>
|
<li>이름 몇 글자를 치면 목록이 좁혀집니다. 방향키와 <kbd>Enter</kbd> 또는 마우스로 고릅니다.</li>
|
||||||
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 작업</b>에 이 작업이 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
<li>저장(설명) 또는 전송(댓글)하면, 태그된 사람의 <b>수신함 → 나를 태그한 업무</b>에 이 업무가 올라가고 그 사람은 자동으로 협업자가 됩니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -489,22 +498,24 @@
|
|||||||
<h2><span class="pjh-num">17</span>수신함과 알림</h2>
|
<h2><span class="pjh-num">17</span>수신함과 알림</h2>
|
||||||
<h3>수신함 화면</h3>
|
<h3>수신함 화면</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
<li><b>나를 태그한 업무</b> — 누가 나를 @태그했는지와 함께 보입니다. 오른쪽 위 <span class="pjh-ui">✔✔ 태그 모두 확인</span> 아이콘으로 한 번에 확인 처리합니다.</li>
|
||||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
<li><b>알림</b> — 업무 배정 · 업무 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 업무 창</b>이 열리고(나를 태그한 업무도 같음), 업무 창이 열린 채 다른 줄을 누르면 업무 창이 그 업무로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 업무의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 업무가 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||||
작업 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(작업 창을 직접 닫을 때와 같음).
|
업무 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(업무 창을 직접 닫을 때와 같음).
|
||||||
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
||||||
다른 프로젝트에서 연결돼 와 읽기만 되는 작업의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
다른 프로젝트에서 연결돼 와 읽기만 되는 업무의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||||
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
<li>오른쪽 위 <span class="pjh-ui">알림 모두 읽음</span> 아이콘(보라색 버튼)으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||||
|
<li><span class="pjh-ui">PC 알림 프로그램 설치</span> — 브라우저가 뒤에 있어도 PC 화면에 알림을 띄우는 프로그램을 내려받고 연결합니다.</li>
|
||||||
|
<li>왼쪽 메뉴 프로젝트 목록 위 <span class="pjh-ui">성공하기</span> — DBX 이야기를 별도 창으로 엽니다(어느 Project 화면에서나)(창 위 <span class="pjh-ui">닫기</span>로 닫음).</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>알림</th><th>받는 사람</th></tr>
|
<tr><th>알림</th><th>받는 사람</th></tr>
|
||||||
<tr><td>작업 배정</td><td>새로 담당자가 된 사람</td></tr>
|
<tr><td>업무 배정</td><td>새로 담당자가 된 사람</td></tr>
|
||||||
<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>
|
||||||
</table>
|
</table>
|
||||||
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 작업 배정·완료는 관리자 메일로도 갑니다.</p>
|
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 18. 검색과 공유 -->
|
<!-- 18. 검색과 공유 -->
|
||||||
@@ -513,14 +524,14 @@
|
|||||||
<h3>전체 검색</h3>
|
<h3>전체 검색</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
||||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(세부 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 업무(세부 업무 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||||
<li>결과를 누르면 그 작업이 열립니다.</li>
|
<li>결과를 누르면 그 업무가 열립니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<h3>공유 링크</h3>
|
<h3>공유 링크</h3>
|
||||||
<ul>
|
<ul>
|
||||||
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
|
<li>업무 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">업무 링크 복사</span>로 주소를 복사합니다.</li>
|
||||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 세부 작업 링크는 세부 작업 자체가 열립니다.</li>
|
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 업무가 바로 열립니다. 세부 업무 링크는 세부 업무 자체가 열립니다.</li>
|
||||||
<li>현재 그 작업을 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
<li>현재 그 업무를 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -528,13 +539,13 @@
|
|||||||
<section class="pjh-sec" id="trash">
|
<section class="pjh-sec" id="trash">
|
||||||
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
|
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
|
||||||
<ul>
|
<ul>
|
||||||
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
<li>지운 업무는 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 업무 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||||
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 작업만 보입니다.</li>
|
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 업무 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 업무만 보입니다.</li>
|
||||||
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
||||||
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||||
<div>세부 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
<div>세부 업무만 따로 지웠는데 상위 업무도 지워진 상태라면, 상위 업무를 먼저 복구해야 합니다.</div></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- 20. 연간 목표 -->
|
<!-- 20. 연간 목표 -->
|
||||||
@@ -595,7 +606,7 @@
|
|||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
||||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
|
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 업무를 멈춥니다.</p>
|
||||||
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
||||||
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
@@ -633,13 +644,15 @@
|
|||||||
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
||||||
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||||
|
|
||||||
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 작업 등록</h3>
|
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 업무 등록</h3>
|
||||||
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>작업 등록</b> 표입니다.</p>
|
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>업무 등록</b> 표입니다.</p>
|
||||||
<ol class="pjh-steps">
|
<ol class="pjh-steps">
|
||||||
<li><b>작업 등록</b> — 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다.</li>
|
<li><b>업무 등록</b>(제목에 <b>N주차 업무 등록</b>) — 주차마다 한 표를 <b>모두가 같이</b> 봅니다(다른 사람이 적거나 등록한 줄도 보임, 30초마다·창을 다시 볼 때 새로 읽음). 내가 멤버가 아닌 프로젝트를 고른 남의 줄은 프로젝트 이름을 가립니다. 회의 완료면 읽기 전용입니다.
|
||||||
|
<b>업무</b> 칸 — 비워 두면 고른 섹션에 새 업무로, 업무를 고르면 <b>그 업무의 세부 업무</b>로 등록합니다(목록 = 그 섹션의 진행 중인 메인 업무, 고르면 섹션 칸은 —). 등록된 줄의 <b>제목을 누르면 오른쪽에 업무 창</b>이 열려 바로 편집할 수 있습니다(업무 창에서 저장이 끝나야 닫히거나 다른 업무로 바뀝니다).
|
||||||
|
<span class="pjh-ui">크게 열기</span> — 같은 표를 넓은 창으로 열어 씁니다(줄·저장은 그대로, <kbd>Esc</kbd>·×로 닫기). 제목 칸에 업무 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다(완료 프로젝트·완료 섹션은 목록에 나오지 않습니다). 목록 맨 위 <span class="pjh-ui">새 프로젝트</span>(Pro user 이상)·<span class="pjh-ui">새 섹션</span>(그 프로젝트 멤버)을 누르면 이름만 적어 바로 만들고 그 칸에 골라집니다. 새 프로젝트는 섹션 없이 시작하니 섹션 칸에서 <span class="pjh-ui">새 섹션</span>을 만들어 고르세요.</li>
|
||||||
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
|
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
|
||||||
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 <b>등록됨</b> 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 업무가 만들어지고, 줄 오른쪽에 <b>체크 표시</b>(누르면 새 탭에서 업무 열기)가 생기고, 제목을 누르면 오른쪽에 업무 창이 열립니다. 줄은 서버에 저장돼 같은 주차를 보는 모두에게 보입니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
||||||
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 작업도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 작업 삭제는 만든 사람만 할 수 있습니다.</li>
|
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 업무도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 업무 삭제는 만든 사람만 할 수 있습니다.</li>
|
||||||
</ol>
|
</ol>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
||||||
@@ -697,11 +710,14 @@
|
|||||||
<ul>
|
<ul>
|
||||||
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
||||||
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
|
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
|
||||||
|
<li><b>끌어서 순서 바꾸기</b> — <b>항목</b> 칸을 잡고 위아래로 끌면 그 줄(항목 칸으로 묶인 줄·세로 병합 포함)이 마우스를 따라 다른 항목 사이로 바로 옮겨 가고, 놓으면 저장됩니다. 같은 구역 안에서만 움직이며 <kbd>Esc</kbd>는 취소. 살짝 누르기만 하면 예전처럼 이름 수정입니다.</li>
|
||||||
|
<li><b>주요 업무</b> 칸을 우클릭해 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가</span>를 하면 <b>항목 칸은 그대로</b> 두고 그 항목 안에 줄이 늘어납니다(줄마다 주요 업무·정량 목표는 따로). 같은 메뉴의 <span class="pjh-ui">줄 삭제</span>는 그 한 줄만 지웁니다. 묶인 항목 칸은 항목 칸 메뉴의 <span class="pjh-ui">항목 칸 나누기</span>로 다시 나눕니다. 줄을 추가·삭제하면 새로고침 없이 표가 그 자리에서 움직이며 바뀝니다.</li>
|
||||||
|
<li><b>구역 순서</b> — 첫 열 <b>구분</b> 칸을 우클릭하거나 마우스를 올려 나오는 <span class="pjh-ui">⋯</span>를 누르면 <span class="pjh-ui">구역 위로 · 구역 아래로 · 구역 끝에 줄 추가</span>가 나옵니다. 구역 안의 줄 순서·병합은 그대로 함께 옮겨지고, 다음에 만드는 회의록도 바뀐 순서를 이어받습니다(회의 완료 전까지, 누구나).</li>
|
||||||
<li>줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
<li>줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
||||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 업무에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||||
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
||||||
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||||
</section>
|
</section>
|
||||||
@@ -712,20 +728,20 @@
|
|||||||
<h3>단축키</h3>
|
<h3>단축키</h3>
|
||||||
<table class="pjh-table">
|
<table class="pjh-table">
|
||||||
<tr><th>키</th><th>하는 일</th></tr>
|
<tr><th>키</th><th>하는 일</th></tr>
|
||||||
<tr><td><kbd>/</kbd></td><td>작업 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
<tr><td><kbd>/</kbd></td><td>업무 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||||
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
<tr><td><kbd>Esc</kbd></td><td>업무 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||||
<tr><td><kbd>Enter</kbd></td><td>세부 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
<tr><td><kbd>Enter</kbd></td><td>세부 업무 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||||
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
||||||
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 세부 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
<tr><td>마우스 오른쪽 버튼</td><td>업무 · 세부 업무 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||||
</table>
|
</table>
|
||||||
<h3>자주 묻는 질문</h3>
|
<h3>자주 묻는 질문</h3>
|
||||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 작업은 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 업무는 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||||
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
<p><b>Q. 업무를 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
||||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||||
<p><b>Q. 세부 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>세부 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
<p><b>Q. 세부 업무를 다른 프로젝트 업무로 옮길 수 있나요?</b><br>세부 업무는 같은 프로젝트 안의 업무로만 옮길 수 있습니다.</p>
|
||||||
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
<p><b>Q. 업무를 두 프로젝트에 같이 두고 싶어요.</b><br>업무 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||||
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
||||||
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||||
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
||||||
|
|||||||
@@ -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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -16,13 +16,17 @@
|
|||||||
|
|
||||||
<section class="pj-main">
|
<section class="pj-main">
|
||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>수신함</h2>
|
<div class="pj-inbox-titlebar">
|
||||||
<div style="display:flex; gap:8px;">
|
<h2>수신함</h2>
|
||||||
|
</div>
|
||||||
|
<div class="pj-inbox-actions">
|
||||||
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
|
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
|
||||||
<a class="pj-btn pj-inbox-notifier" href="/project/notifier" title="브라우저가 뒤에 있어도 PC 화면에 알림 띄우기">
|
<a class="pj-btn pj-inbox-notifier" href="/project/notifier" title="브라우저가 뒤에 있어도 PC 화면에 알림 띄우기">
|
||||||
<span class="material-symbols-outlined">desktop_windows</span>PC 알림</a>
|
<span class="material-symbols-outlined">desktop_windows</span>PC 알림 프로그램 설치</a>
|
||||||
<button type="button" class="pj-btn" id="pj-mentions-readall">태그 모두 확인</button>
|
<button type="button" class="pj-btn pj-inbox-iconbtn" id="pj-mentions-readall" title="태그 모두 확인" aria-label="태그 모두 확인">
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-readall">알림 모두 읽음</button>
|
<span class="material-symbols-outlined">done_all</span></button>
|
||||||
|
<button type="button" class="pj-btn pj-btn-primary pj-inbox-iconbtn" id="pj-readall" title="알림 모두 읽음" aria-label="알림 모두 읽음">
|
||||||
|
<span class="material-symbols-outlined">mark_email_read</span></button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-view pj-inbox-pane">
|
<div class="pj-view pj-inbox-pane">
|
||||||
@@ -32,18 +36,18 @@
|
|||||||
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
|
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
|
||||||
<div class="pj-inbox-section">
|
<div class="pj-inbox-section">
|
||||||
<h3 class="pj-inbox-h3">
|
<h3 class="pj-inbox-h3">
|
||||||
나를 태그한 작업
|
나를 태그한 업무
|
||||||
<span class="pj-inbox-count" id="pj-mention-unread"
|
<span class="pj-inbox-count" id="pj-mention-unread"
|
||||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||||
</h3>
|
</h3>
|
||||||
{% if not mentioned_tasks %}
|
{% if not mentioned_tasks %}
|
||||||
<div class="pj-empty">태그된 작업이 없습니다.</div>
|
<div class="pj-empty">태그된 업무가 없습니다.</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
||||||
{% for t in mentioned_tasks %}
|
{% for t in mentioned_tasks %}
|
||||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
||||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
||||||
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 작업 창">
|
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 업무 창">
|
||||||
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
||||||
<div class="pj-inbox-body">
|
<div class="pj-inbox-body">
|
||||||
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
||||||
@@ -76,6 +80,7 @@
|
|||||||
{% elif n.type == 'completed' %}task_alt
|
{% elif n.type == 'completed' %}task_alt
|
||||||
{% elif n.type == 'comment' %}chat_bubble
|
{% elif n.type == 'comment' %}chat_bubble
|
||||||
{% elif n.type == 'mention' %}alternate_email
|
{% elif n.type == 'mention' %}alternate_email
|
||||||
|
{% elif n.type == 'reaction' %}add_reaction
|
||||||
{% elif n.type == 'due_soon' %}schedule
|
{% elif n.type == 'due_soon' %}schedule
|
||||||
{% elif n.type == 'due_today' %}today
|
{% elif n.type == 'due_today' %}today
|
||||||
{% elif n.type == 'overdue' %}alarm
|
{% elif n.type == 'overdue' %}alarm
|
||||||
@@ -101,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=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -31,7 +31,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="pj-title-wrap">
|
<div class="pj-title-wrap">
|
||||||
<h1 class="pj-project-title">
|
<h1 class="pj-project-title">
|
||||||
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 작업</span>
|
<span class="pj-project-title-pill" style="--pj-color: #7b68ee">내 업무</span>
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
<div class="pj-mytasks-summary" id="pj-mytasks-summary"></div>
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
<div class="pj-filterbar" id="pj-mt-filterbar">
|
<div class="pj-filterbar" id="pj-mt-filterbar">
|
||||||
<label class="pj-fb-search">
|
<label class="pj-fb-search">
|
||||||
<span class="material-symbols-outlined">filter_list</span>
|
<span class="material-symbols-outlined">filter_list</span>
|
||||||
<input type="search" id="pj-mt-q" placeholder="내 작업에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
<input type="search" id="pj-mt-q" placeholder="내 업무에서 찾기 (제목·설명·프로젝트)" autocomplete="off" />
|
||||||
</label>
|
</label>
|
||||||
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
<select id="pj-mt-due" class="pj-fb-select" title="마감일">
|
||||||
<option value="all">마감: 전체</option>
|
<option value="all">마감: 전체</option>
|
||||||
@@ -62,7 +62,7 @@
|
|||||||
<thead></thead>
|
<thead></thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 작업이 없습니다.</div>
|
<div class="pj-empty" id="pj-mytasks-empty" hidden>표시할 업무가 없습니다.</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
@@ -100,5 +100,5 @@
|
|||||||
"today": {{ today | tojson }}
|
"today": {{ today | tojson }}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<script src="/static/project.js?v=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@
|
|||||||
<h3>이 PC 를 내 알림에 연결할까요?</h3>
|
<h3>이 PC 를 내 알림에 연결할까요?</h3>
|
||||||
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
|
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
|
||||||
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
|
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
|
||||||
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
|
<b>{{ user.name or user.email }}</b> 님의 태그·업무 배정 알림이 뜹니다.</p>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
|
||||||
{% elif link %}
|
{% elif link %}
|
||||||
<h3>이미 연결을 승인했습니다</h3>
|
<h3>이미 연결을 승인했습니다</h3>
|
||||||
@@ -48,8 +48,8 @@
|
|||||||
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
|
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
|
||||||
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
|
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
|
||||||
</ol>
|
</ol>
|
||||||
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
<p class="pj-notifier-note">나를 태그하거나 업무가 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
||||||
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
|
[열기]를 누르면 브라우저에서 그 업무가 열립니다.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pj-notifier-card">
|
<div class="pj-notifier-card">
|
||||||
@@ -108,5 +108,5 @@
|
|||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<script src="/static/project.js?v=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — 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 -->
|
||||||
@@ -29,6 +29,8 @@
|
|||||||
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-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-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}"
|
||||||
data-me="{{ user.email }}">
|
data-me="{{ user.email }}">
|
||||||
|
|
||||||
<div class="pj-layout">
|
<div class="pj-layout">
|
||||||
@@ -191,7 +193,7 @@
|
|||||||
<div class="pj-view" data-view="list" hidden>
|
<div class="pj-view" data-view="list" hidden>
|
||||||
<table class="pj-table" id="pj-list">
|
<table class="pj-table" id="pj-list">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>작업</th><th>담당자</th><th>섹션</th><th>우선순위</th><th>시작</th><th>마감</th></tr>
|
<tr><th>업무</th><th>담당자</th><th>섹션</th><th>우선순위</th><th>시작</th><th>마감</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -216,7 +218,7 @@
|
|||||||
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
||||||
<div class="pj-field-label">기본 담당자
|
<div class="pj-field-label">기본 담당자
|
||||||
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
||||||
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 작업을 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 작업만 이 사람에게 자동 배정됩니다.</span>
|
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 업무를 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 업무만 이 사람에게 자동 배정됩니다.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-modal-actions">
|
<div class="pj-modal-actions">
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
@@ -237,13 +239,13 @@
|
|||||||
<div class="pj-modal-actions pj-modal-actions-top">
|
<div class="pj-modal-actions pj-modal-actions-top">
|
||||||
<!-- 공유 — 이 업무의 퍼머링크(/project/t/{id})를 클립보드에 복사.
|
<!-- 공유 — 이 업무의 퍼머링크(/project/t/{id})를 클립보드에 복사.
|
||||||
받은 사람이 열면 로그인 후 이 업무 팝업이 바로 뜬다(멤버만). -->
|
받은 사람이 열면 로그인 후 이 업무 팝업이 바로 뜬다(멤버만). -->
|
||||||
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 작업 링크 복사">
|
<button type="button" class="pj-btn pj-btn-share" id="pj-share-task" hidden title="이 업무 링크 복사">
|
||||||
<span class="material-symbols-outlined">link</span> 공유
|
<span class="material-symbols-outlined">link</span> 공유
|
||||||
</button>
|
</button>
|
||||||
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
<button type="button" class="pj-btn pj-btn-complete" id="pj-toggle-complete" hidden>✓ 완료로 표시</button>
|
||||||
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
<button type="button" class="pj-btn pj-btn-danger" id="pj-delete-task" hidden>삭제</button>
|
||||||
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
<!-- 수신함 오른쪽 패널(?embed=1)에서만 보인다 — 이 작업이 있는 프로젝트 화면으로 이동. -->
|
||||||
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 작업이 있는 프로젝트 화면으로 이동">
|
<button type="button" class="pj-btn pj-btn-goto-project" id="pj-goto-project" title="이 업무가 있는 프로젝트 화면으로 이동">
|
||||||
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
<span class="material-symbols-outlined">open_in_new</span> 프로젝트로 이동
|
||||||
</button>
|
</button>
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
@@ -258,15 +260,15 @@
|
|||||||
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
||||||
<input type="hidden" id="pj-t-id" />
|
<input type="hidden" id="pj-t-id" />
|
||||||
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
||||||
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 작업 열기">
|
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 업무 열기">
|
||||||
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
||||||
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
||||||
</button>
|
</button>
|
||||||
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="작업 제목"></textarea>
|
<textarea id="pj-t-title" class="pj-t-title-input" rows="1" placeholder="업무 제목"></textarea>
|
||||||
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
<!-- 다른 프로젝트에서 연결돼 온 작업을 원 소속 권한 없이 열었을 때 — 보기만 된다(서버도 변경 거절). -->
|
||||||
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
<div class="pj-readonly-note" id="pj-t-readonly" hidden>
|
||||||
<span class="material-symbols-outlined">visibility</span>
|
<span class="material-symbols-outlined">visibility</span>
|
||||||
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 작업이라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
<span>다른 프로젝트(<b id="pj-t-readonly-home"></b>)에서 연결된 업무라 읽기만 할 수 있습니다. 변경은 원 소속 프로젝트 멤버만 할 수 있습니다.</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pj-modal-body">
|
<div class="pj-modal-body">
|
||||||
@@ -349,27 +351,7 @@
|
|||||||
<span class="pj-extra-label">설명</span>
|
<span class="pj-extra-label">설명</span>
|
||||||
<span class="pj-muted-sm" id="pj-desc-hint"></span>
|
<span class="pj-muted-sm" id="pj-desc-hint"></span>
|
||||||
</div>
|
</div>
|
||||||
{# 서식 도구 — 모든 버튼을 같은 아이콘 글꼴(Material Symbols)·같은 크기로 그려
|
{% include "project/_desc_fmtbar.html" %}
|
||||||
한 줄에 딱 맞춰 선다(예전엔 글자·이모지가 섞여 높이가 들쭉날쭉했다). #}
|
|
||||||
<div class="pj-desc-fmtbar" id="pj-desc-fmtbar">
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="bold" title="굵게 (Ctrl+B)"><span class="material-symbols-outlined">format_bold</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
|
||||||
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertCheckbox" title="체크박스 넣기"><span class="material-symbols-outlined">check_box</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="formatBlock" data-arg="blockquote" title="인용구"><span class="material-symbols-outlined">format_quote</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="createLink" title="링크 삽입"><span class="material-symbols-outlined">link</span></button>
|
|
||||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="removeFormat" title="서식 지우기"><span class="material-symbols-outlined">format_clear</span></button>
|
|
||||||
<span class="pj-desc-fmtsep"></span>
|
|
||||||
<label class="pj-desc-fmtbtn" id="pj-desc-imgbtn" title="이미지 추가"><span class="material-symbols-outlined">image</span><input type="file" id="pj-desc-img-input" accept="image/*" hidden /></label>
|
|
||||||
</div>
|
|
||||||
<div class="pj-desc-wrap">
|
<div class="pj-desc-wrap">
|
||||||
<div class="pj-desc-editor" id="pj-t-desc" contenteditable="true" data-placeholder="설명을 입력하세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
<div class="pj-desc-editor" id="pj-t-desc" contenteditable="true" data-placeholder="설명을 입력하세요… (이미지는 붙여넣기 또는 위 버튼으로 추가)"></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -379,13 +361,15 @@
|
|||||||
기존 업무 편집 시에만. -->
|
기존 업무 편집 시에만. -->
|
||||||
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
||||||
<div class="pj-extra-head">
|
<div class="pj-extra-head">
|
||||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 작업
|
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 업무
|
||||||
</div>
|
</div>
|
||||||
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
||||||
<div class="pj-subtask-form">
|
<div class="pj-subtask-form">
|
||||||
<input type="text" id="pj-subtask-input" placeholder="세부 작업 제목…" autocomplete="off" />
|
<input type="text" id="pj-subtask-input" placeholder="세부 업무 제목…" autocomplete="off" />
|
||||||
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
{# 아이콘 순서는 보드 카드 새 줄과 같게 — 마감일 · 담당자 · 협업자 #}
|
||||||
<input type="date" id="pj-subtask-add-due" />
|
<input type="date" id="pj-subtask-add-due" />
|
||||||
|
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
||||||
|
<button type="button" class="pj-assignee-btn is-empty pj-subtask-add-fol" id="pj-subtask-add-followers" title="협업자 지정">협업자 없음</button>
|
||||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -395,7 +379,7 @@
|
|||||||
<div class="pj-extra-head">
|
<div class="pj-extra-head">
|
||||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
||||||
<label class="pj-upload-btn">
|
<label class="pj-upload-btn">
|
||||||
파일 추가<input type="file" id="pj-attach-input" hidden />
|
파일 추가<input type="file" id="pj-attach-input" multiple hidden />
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
||||||
@@ -488,5 +472,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=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" 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=20261012a" />
|
<link rel="stylesheet" href="/static/project.css?v=20261019d" />
|
||||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
<section class="pj-main">
|
<section class="pj-main">
|
||||||
<div class="pj-section-head">
|
<div class="pj-section-head">
|
||||||
<h2>휴지통</h2>
|
<h2>휴지통</h2>
|
||||||
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
<span class="pj-trash-note">삭제한 업무는 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="pj-view pj-inbox-pane">
|
<div class="pj-view pj-inbox-pane">
|
||||||
{% if not trash_enabled %}
|
{% if not trash_enabled %}
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
<table class="pj-table pj-trash-table" id="pj-trash-table">
|
<table class="pj-table pj-trash-table" id="pj-trash-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>작업</th>
|
<th>업무</th>
|
||||||
<th>프로젝트</th>
|
<th>프로젝트</th>
|
||||||
<th>포함</th>
|
<th>포함</th>
|
||||||
<th>삭제한 사람</th>
|
<th>삭제한 사람</th>
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
<td class="pj-trash-title">{{ it.title }}</td>
|
<td class="pj-trash-title">{{ it.title }}</td>
|
||||||
<td>{{ it.project_name or '-' }}</td>
|
<td>{{ it.project_name or '-' }}</td>
|
||||||
<td class="pj-trash-meta">
|
<td class="pj-trash-meta">
|
||||||
{% if it.task_count > 1 %}세부 작업 {{ it.task_count - 1 }}{% endif %}
|
{% if it.task_count > 1 %}세부 업무 {{ it.task_count - 1 }}{% endif %}
|
||||||
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
||||||
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
||||||
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
||||||
@@ -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=20261012b" defer></script>
|
<script src="/static/project.js?v=20261019d" defer></script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# [휴가] 휴가 관리 모듈 — `app/modules/vacation/`, `vacation_db`
|
||||||
|
|
||||||
|
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||||
|
> 정적 파일: `app/static/vacation.css`, `app/static/vacation.js`. 템플릿: `templates/`.
|
||||||
|
|
||||||
|
- 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 공휴일·연차 설정.
|
||||||
|
- 권한키 `vacation`(사용)·`vacation_approver`(승인).
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user