Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -144,6 +144,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# CAFE24_MOBILE_DETAIL_FTP_PATH=/sde_design/mobile11/product/detail.html
|
||||
# CAFE24_PC_DETAIL_FTP_PATH=/sde_design/skin11/product/detail.html
|
||||
|
||||
# ─── 입출고 관리 모듈 (inout_db) — app/modules/inout ───
|
||||
# 본사 → 공장 발주, 물류 입고, 미입고 관리. 미설정 시 "설정 필요" 안내만.
|
||||
# 초기화: scripts/sql/inout_db_init.sql (docs/INOUT_MODULE.md). 제품(단품)은 아래 ITEMCODE_DB_URL 재사용.
|
||||
# INOUT_DB_URL=postgresql://inout_app:replace-me@postgres-db:5432/inout_db
|
||||
|
||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||
|
||||
+20
@@ -24,6 +24,8 @@ from .modules.dispatch import build_dispatch_store
|
||||
from .modules.dispatch import router as dispatch_router
|
||||
from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.inout import build_inout_items, build_inout_store
|
||||
from .modules.inout import router as inout_router
|
||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||
from .modules.malaysia import router as malaysia_router
|
||||
from .modules.notice import build_notice_store
|
||||
@@ -59,6 +61,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"cafe24": "카페24 상품관리",
|
||||
"performance": "실적",
|
||||
"asset": "자산관리",
|
||||
"inout": "입출고 관리",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -153,6 +156,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "performance" / "templates",
|
||||
BASE_DIR / "modules" / "asset" / "templates",
|
||||
BASE_DIR / "modules" / "notice" / "templates",
|
||||
BASE_DIR / "modules" / "inout" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -218,6 +222,10 @@ app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_UR
|
||||
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)
|
||||
@@ -230,6 +238,7 @@ app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
app.include_router(asset_router)
|
||||
app.include_router(notice_router)
|
||||
app.include_router(inout_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -422,6 +431,16 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "관리",
|
||||
},
|
||||
{
|
||||
"key": "inout",
|
||||
"title": "입출고 관리",
|
||||
"subtitle": "Inbound",
|
||||
"description": "본사에서 공장으로 넣은 제작 발주와 물류 입고 수량을 맞춰 보고, 미입고·초과 입고를 관리합니다.",
|
||||
"url": "/inout/",
|
||||
"health_url": "/inout/health",
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
@@ -437,6 +456,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
def _icon_svg(name: str) -> str:
|
||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||
paths = {
|
||||
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||
|
||||
@@ -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).
|
||||
@@ -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`.
|
||||
@@ -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,48 @@
|
||||
# [입출고] 입출고 관리 모듈 — `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`·저장 때 서버 재확인.
|
||||
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||
- 미입고 현황(제품별 합계·발주별·지연).
|
||||
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||
- 잔량 종결·취소(취소는 입고 없을 때만).
|
||||
- 상태는 저장하지 않고 누적 입고로 계산(`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`).
|
||||
- 보낸 기록·재발송 확인.
|
||||
|
||||
## 입고증 사진 (003)
|
||||
|
||||
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||
|
||||
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||
|
||||
- 테이블 `inout_products`·`inout_products_excluded`.
|
||||
- [단품 불러오기] = 코드표 단품 → 목록(값을 넣은 상품은 그대로·지운 단품은 다음에도 빠짐, 제외 목록에서 되살리기).
|
||||
- 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력(은 g = 무게 × % 자동).
|
||||
- 한 번 불러오면 발주서 제품은 이 목록에서. 발주 품목에 그때 값 사본(`unit_price`·`weight_g`·`silver_pct`).
|
||||
- 발주서·메일에 금액(수량 × 단가)·PP·은 함유량과 합계.
|
||||
|
||||
## 시각 / 날짜
|
||||
|
||||
- 시각은 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,607 @@
|
||||
"""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 = [], []
|
||||
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"]), []),
|
||||
"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()
|
||||
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]))
|
||||
|
||||
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,186 @@
|
||||
"""발주 메일 — 발주 담당자 본인 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) -> bytes:
|
||||
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")
|
||||
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,91 @@
|
||||
"""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 _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()
|
||||
@@ -0,0 +1,895 @@
|
||||
"""입출고 관리 모듈 라우터 — 본사 → 공장 발주, 물류 입고(분할), 발주 대비 미입고·초과.
|
||||
|
||||
GET /inout/ 발주 목록(상태·공장·기간·검색)
|
||||
GET /inout/pending 미입고 현황(품목별 합계 + 발주별) · 초과 입고
|
||||
GET|POST /inout/orders/new 발주서 작성(발주 담당)
|
||||
GET /inout/orders/{id} 발주서 — 품목별 발주·입고·미입고, 입고 기록, 입고 입력(입고 담당)
|
||||
GET|POST /inout/orders/{id}/edit 발주서 고치기(발주 담당)
|
||||
POST /inout/orders/{id}/close|reopen|cancel 종결·종결 풀기·취소(발주 담당)
|
||||
POST /inout/orders/{id}/receipts 입고 저장(입고 담당) — 발주 초과면 확인 화면, confirm_over=1 로 다시 보내야 저장
|
||||
POST /inout/orders/{id}/receipts/{rid}/delete 잘못 넣은 입고 지우기(입고 담당)
|
||||
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
||||
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
||||
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
|
||||
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
||||
GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만)
|
||||
GET /inout/api/items?q= 코드표 단품 검색(JSON)
|
||||
|
||||
권한: 모듈 권한키 `inout`(조회). 발주 담당·입고 담당은 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import store
|
||||
from .db import OverReceipt
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/inout", tags=["inout"])
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 공용 헬퍼
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _store(request: Request) -> Any:
|
||||
return getattr(request.app.state, "inout_store", None)
|
||||
|
||||
|
||||
def _items(request: Request) -> Any:
|
||||
return getattr(request.app.state, "inout_items", None)
|
||||
|
||||
|
||||
def _user(request: Request) -> dict[str, Any]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
if not has_module(user, "inout"):
|
||||
raise HTTPException(status_code=403, detail="입출고 관리 모듈 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _page_user(request: Request) -> Any:
|
||||
"""화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다."""
|
||||
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 _user(request)
|
||||
|
||||
|
||||
def _is_admin(user: dict[str, Any]) -> bool:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
return is_admin(user)
|
||||
|
||||
|
||||
def _perms(st: Any, user: dict[str, Any]) -> dict[str, bool]:
|
||||
"""발주 담당·입고 담당 — 옵션(inout_roles), ERP 관리자는 둘 다."""
|
||||
admin = _is_admin(user)
|
||||
roles = set() if admin else st.roles_of(user.get("email", ""))
|
||||
return {"admin": admin, "can_order": admin or store.ROLE_ORDER in roles,
|
||||
"can_receive": admin or store.ROLE_RECEIVE in roles,
|
||||
"super": bool(user.get("is_super_admin"))} # 발주 삭제(2026-10-17) — 수퍼관리자 한 명만
|
||||
|
||||
|
||||
def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]:
|
||||
p = _perms(st, user)
|
||||
if what == "order" and not p["can_order"]:
|
||||
raise HTTPException(status_code=403, detail="발주 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).")
|
||||
if what == "receive" and not p["can_receive"]:
|
||||
raise HTTPException(status_code=403, detail="입고 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).")
|
||||
if what == "admin" and not p["admin"]:
|
||||
raise HTTPException(status_code=403, detail="옵션은 ERP 관리자만 바꿀 수 있습니다.")
|
||||
if what == "super" and not p["super"]:
|
||||
raise HTTPException(status_code=403, detail="발주 삭제는 수퍼관리자만 할 수 있습니다.")
|
||||
return p
|
||||
|
||||
|
||||
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any], status_code: int = 200) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
|
||||
st = _store(request)
|
||||
perms = _perms(st, user) if st is not None else {"admin": _is_admin(user), "can_order": False, "can_receive": False}
|
||||
return render_template(request, name, {
|
||||
"user": user, "is_admin": perms["admin"], "perms": perms,
|
||||
"nav_items": build_erp_nav(user, active="inout"),
|
||||
"msg": request.query_params.get("msg", ""), "today": today_kst(),
|
||||
"open_options": request.query_params.get("options") == "1" and perms["admin"], # 톱니 팝업 바로 열기
|
||||
**ctx,
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
def _config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
|
||||
return render_template(request, "denied.html", {
|
||||
"reason": "입출고 관리 모듈이 아직 설정되지 않았습니다. scripts/sql/inout_db_init.sql 로 inout_db 를 만들고 "
|
||||
"INOUT_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요.",
|
||||
"user": user, "is_admin": _is_admin(user), "nav_items": build_erp_nav(user, active="inout"),
|
||||
}, status_code=503)
|
||||
|
||||
|
||||
def _ctx(request: Request) -> Any:
|
||||
"""화면 공통 — (st, user) 또는 응답(로그인·설정 필요)."""
|
||||
user = _page_user(request)
|
||||
if not isinstance(user, dict):
|
||||
return user
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return _config_needed(request, user)
|
||||
return st, user
|
||||
|
||||
|
||||
def _redirect(url: str, msg: str = "") -> RedirectResponse:
|
||||
return RedirectResponse(url=url + (("&" if "?" in url else "?") + urlencode({"msg": msg}) if msg else ""), status_code=303)
|
||||
|
||||
|
||||
def _order_or_404(st: Any, order_id: int) -> dict[str, Any]:
|
||||
order = st.get_order(order_id)
|
||||
if order is None:
|
||||
raise HTTPException(status_code=404, detail="발주서를 찾을 수 없습니다.")
|
||||
return order
|
||||
|
||||
|
||||
def _opt_int(v: Any) -> int | None:
|
||||
try:
|
||||
n = int(str(v or "").strip())
|
||||
except ValueError:
|
||||
return None
|
||||
return n if n > 0 else None
|
||||
|
||||
|
||||
def _opt_date(v: Any) -> date | None:
|
||||
try:
|
||||
return date.fromisoformat(str(v or "").strip())
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 발주 목록 · 미입고 현황
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def index(request: Request, status: str = "active", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
|
||||
date_to: str = Query("", alias="to")) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
status = status if status in store.STATUS_FILTERS else "active"
|
||||
orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from),
|
||||
date_to=_opt_date(date_to))
|
||||
return _render(request, "inout/index.html", user, {
|
||||
"tab": "orders", "orders": orders, "factories": st.list_factories(include_inactive=True),
|
||||
"filters": {"status": status, "factory": _opt_int(factory), "q": q, "from": date_from, "to": date_to},
|
||||
"status_filters": store.STATUS_FILTERS,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/pending", response_class=HTMLResponse)
|
||||
def pending(request: Request, factory: str = "", q: str = "") -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
data = st.outstanding(factory_id=_opt_int(factory), q=q)
|
||||
by_item: dict[str, dict[str, Any]] = {}
|
||||
for r in data["pending"]:
|
||||
it = by_item.setdefault(r["item_code"], {"item_code": r["item_code"], "item_name": r["item_name"],
|
||||
"remaining": 0, "orders": 0, "earliest_due": None})
|
||||
it["remaining"] += r["remaining"]
|
||||
it["orders"] += 1
|
||||
if r["due_date"] and (it["earliest_due"] is None or r["due_date"] < it["earliest_due"]):
|
||||
it["earliest_due"] = r["due_date"]
|
||||
items = sorted(by_item.values(), key=lambda x: (-x["remaining"], x["item_code"]))
|
||||
return _render(request, "inout/pending.html", user, {
|
||||
"tab": "pending", "rows": data["pending"], "over": data["over"], "items": items,
|
||||
"factories": st.list_factories(include_inactive=True), "filters": {"factory": _opt_int(factory), "q": q},
|
||||
"total_remaining": sum(r["remaining"] for r in data["pending"]),
|
||||
})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 발주서 작성·수정
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _form_values(form: Any) -> dict[str, Any]:
|
||||
return {"factory_id": form.get("factory_id", ""), "order_date": form.get("order_date", ""),
|
||||
"due_date": form.get("due_date", ""), "memo": form.get("memo", ""),
|
||||
"codes": form.getlist("item_code"), "names": form.getlist("item_name"),
|
||||
"quantities": form.getlist("qty"), "line_memos": form.getlist("line_memo")}
|
||||
|
||||
|
||||
def _validated(request: Request, st: Any, vals: dict[str, Any], *,
|
||||
keep_codes: set[str]) -> tuple[dict[str, Any], dict[str, str], dict[str, dict[str, Any]]]:
|
||||
"""폼 검사 + 제품 확인 → (값, {코드: 이름}, {코드: 상품 정보 행}). keep_codes = 이미 발주서에 있던 코드(그대로 둔다).
|
||||
옵션 → 상품 정보에 불러온 단품이 있으면 그 목록에서만(지운 단품은 안 됨, 단가 등 사본은 여기서), 없으면 코드표(004 이전과 같게)."""
|
||||
data = store.validate_order(factory_id=vals["factory_id"], order_date=vals["order_date"], due_date=vals["due_date"],
|
||||
memo=vals["memo"], codes=vals["codes"], quantities=vals["quantities"],
|
||||
line_memos=vals["line_memos"])
|
||||
new_codes = [ln["item_code"] for ln in data["lines"] if ln["item_code"] not in keep_codes]
|
||||
names: dict[str, str] = {}
|
||||
if new_codes and st.catalog_count() > 0:
|
||||
found_rows = st.catalog_lookup(new_codes)
|
||||
missing = [c for c in new_codes if c not in found_rows]
|
||||
if missing:
|
||||
raise ValueError("상품 정보에 없는 단품입니다(옵션 → 상품 정보에서 불러오거나 되살리세요): " + ", ".join(missing))
|
||||
return data, {c: found_rows[c]["item_name"] for c in new_codes}, found_rows
|
||||
if new_codes:
|
||||
reader = _items(request)
|
||||
found = reader.lookup(new_codes) if reader is not None else None
|
||||
if found is None:
|
||||
raise ValueError("코드표 DB(itemcode_db)에 연결할 수 없어 제품을 확인하지 못했습니다 — 잠시 뒤 다시 저장하세요"
|
||||
+ ("" if reader is None or reader.enabled else " (ITEMCODE_DB_URL 미설정)") + ".")
|
||||
missing = [c for c in new_codes if c not in found]
|
||||
if missing:
|
||||
raise ValueError("코드표 단품에 없는 제품입니다: " + ", ".join(missing))
|
||||
names = {c: found[c] for c in new_codes}
|
||||
return data, names, {}
|
||||
|
||||
|
||||
def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[str, Any] | None, vals: dict[str, Any],
|
||||
error: str = "", status_code: int = 200) -> HTMLResponse:
|
||||
lines = [{"code": (c or "").strip().upper(), "name": vals["names"][i] if i < len(vals["names"]) else "",
|
||||
"qty": vals["quantities"][i] if i < len(vals["quantities"]) else "",
|
||||
"memo": vals["line_memos"][i] if i < len(vals["line_memos"]) else ""}
|
||||
for i, c in enumerate(vals["codes"]) if (c or "").strip() or (i < len(vals["quantities"]) and vals["quantities"][i])]
|
||||
# 단가 — 이미 있던 품목은 발주 당시 값(사본), 새 품목은 지금 상품 정보 값(004). 금액은 화면이 수량 × 단가로 계산.
|
||||
snap = {x["item_code"]: x.get("unit_price") for x in (order["lines"] if order else [])}
|
||||
catalog = st.catalog_lookup([ln["code"] for ln in lines if ln["code"] and ln["code"] not in snap])
|
||||
for ln in lines:
|
||||
price = snap[ln["code"]] if ln["code"] in snap else (catalog.get(ln["code"]) or {}).get("unit_price")
|
||||
ln["price"] = float(price) if price is not None else None
|
||||
ln["price_label"] = store.fmt_num(price) if price is not None else ""
|
||||
reader = _items(request)
|
||||
catalog_n = st.catalog_count()
|
||||
return _render(request, "inout/order_form.html", user, {
|
||||
"tab": "orders", "order": order, "vals": vals, "lines": lines, "error": error,
|
||||
"factories": [f for f in st.list_factories(include_inactive=True)
|
||||
if f["is_active"] or (order and f["id"] == order["factory_id"])],
|
||||
"items_enabled": bool(reader is not None and reader.enabled) or catalog_n > 0, "from_catalog": catalog_n > 0,
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@router.get("/orders/new", response_class=HTMLResponse)
|
||||
def order_new(request: Request) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
vals = {"factory_id": "", "order_date": today_kst().isoformat(), "due_date": "", "memo": "",
|
||||
"codes": [], "names": [], "quantities": [], "line_memos": []}
|
||||
return _form_page(request, user, st, order=None, vals=vals)
|
||||
|
||||
|
||||
@router.post("/orders/new", response_class=HTMLResponse)
|
||||
async def order_create(request: Request) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
vals = _form_values(await request.form())
|
||||
try:
|
||||
data, names, specs = _validated(request, st, vals, keep_codes=set())
|
||||
res = st.create_order(data, names, by=user.get("email", ""), specs=specs)
|
||||
except ValueError as exc:
|
||||
return _form_page(request, user, st, order=None, vals=vals, error=str(exc), status_code=400)
|
||||
return _redirect(f"/inout/orders/{res['id']}?mail=1", f"발주서 {res['order_no']} 을(를) 만들었습니다.") # 메일 미리보기 바로
|
||||
|
||||
|
||||
@router.get("/orders/{order_id}/edit", response_class=HTMLResponse)
|
||||
def order_edit(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
order = _order_or_404(st, order_id)
|
||||
vals = {"factory_id": str(order["factory_id"]), "order_date": order["order_date"].isoformat(),
|
||||
"due_date": order["due_date"].isoformat() if order["due_date"] else "", "memo": order["memo"],
|
||||
"codes": [x["item_code"] for x in order["lines"]], "names": [x["item_name"] for x in order["lines"]],
|
||||
"quantities": [str(x["qty"]) for x in order["lines"]], "line_memos": [x["memo"] for x in order["lines"]]}
|
||||
return _form_page(request, user, st, order=order, vals=vals)
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/edit", response_class=HTMLResponse)
|
||||
async def order_update(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
order = _order_or_404(st, order_id)
|
||||
vals = _form_values(await request.form())
|
||||
try:
|
||||
data, names, specs = _validated(request, st, vals, keep_codes={x["item_code"] for x in order["lines"]})
|
||||
st.update_order(order_id, data, names, by=user.get("email", ""), specs=specs)
|
||||
except ValueError as exc:
|
||||
return _form_page(request, user, st, order=order, vals=vals, error=str(exc), status_code=400)
|
||||
return _redirect(f"/inout/orders/{order_id}", "발주서를 고쳤습니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 발주서 화면 · 종결 · 취소
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, Any], *, receipt_form: dict[str, Any] | None = None,
|
||||
error: str = "", over: list[dict[str, Any]] | None = None, photos_lost: bool = False,
|
||||
status_code: int = 200) -> HTMLResponse:
|
||||
perms = _perms(st, user)
|
||||
return _render(request, "inout/order_detail.html", user, {
|
||||
"tab": "orders", "order": order, "error": error, "over": over or [], "photos_lost": photos_lost,
|
||||
"open_mail": request.query_params.get("mail") == "1" and perms["can_order"] and not order["cancelled_at"],
|
||||
# 입고 담당(발주 담당 아님)은 품목을 이름·발주 수량(+ 이번 입고 칸)만 — 2026-10-16 사용자 요청
|
||||
"items_limited": perms["can_receive"] and not perms["can_order"],
|
||||
"show_prices": perms["can_order"], "totals": store.order_totals(order["lines"]),
|
||||
"fmt_num": store.fmt_num, "line_amount": store.line_amount, "silver_g": store.silver_g,
|
||||
"max_photos": store.MAX_PHOTOS,
|
||||
"receipt_form": receipt_form or {"receipt_date": today_kst().isoformat(), "memo": "", "qty": {}},
|
||||
"can_receive_now": order["status"] in (store.ST_OPEN, store.ST_PARTIAL, store.ST_DONE, store.ST_OVER),
|
||||
}, status_code=status_code)
|
||||
|
||||
|
||||
@router.get("/orders/{order_id}", response_class=HTMLResponse)
|
||||
def order_detail(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
return _detail(request, user, st, _order_or_404(st, order_id))
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/close")
|
||||
async def order_close(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
form = await request.form()
|
||||
try:
|
||||
st.set_closed(order_id, closed=True, reason=str(form.get("reason") or ""), by=user.get("email", ""))
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", "종결했습니다 — 남은 미입고는 미입고 현황에서 빠집니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/reopen")
|
||||
def order_reopen(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
try:
|
||||
st.set_closed(order_id, closed=False, by=user.get("email", ""))
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", "종결을 풀었습니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/cancel")
|
||||
def order_cancel(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
try:
|
||||
st.cancel_order(order_id, by=user.get("email", ""))
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", "발주서를 취소했습니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/delete")
|
||||
async def order_delete(request: Request, order_id: int) -> Any:
|
||||
"""발주 목록 🗑 — 수퍼관리자만. 품목·입고 기록·입고증 사진·메일 기록까지 완전히 지운다(되돌릴 수 없음)."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "super")
|
||||
form = await request.form()
|
||||
back = str(form.get("back") or "")
|
||||
back = back if back.startswith("/inout/") and "//" not in back else "/inout/" # 보던 목록(거르기)으로 — 다른 사이트로는 안 보냄
|
||||
try:
|
||||
r = st.delete_order(order_id)
|
||||
except LookupError as exc:
|
||||
return _redirect(back, str(exc))
|
||||
_log.warning("inout order deleted: %s (receipts=%d) by %s", r["order_no"], r["receipts"], user.get("email", ""))
|
||||
return _redirect(back, f"발주서 {r['order_no']}를 삭제했습니다" + (f"(입고 기록 {r['receipts']}건 포함)." if r["receipts"] else "."))
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 입고
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.post("/orders/{order_id}/receipts", response_class=HTMLResponse)
|
||||
async def receipt_add(request: Request, order_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
form = await request.form()
|
||||
qty: dict[int, str] = {}
|
||||
for k, v in form.items():
|
||||
if k.startswith("qty_") and k[4:].isdigit():
|
||||
qty[int(k[4:])] = str(v)
|
||||
rf = {"receipt_date": str(form.get("receipt_date") or ""), "memo": str(form.get("memo") or ""), "qty": qty}
|
||||
had_photos = False
|
||||
try:
|
||||
raw_photos = await _read_photos(form)
|
||||
had_photos = any(data for _n, data in raw_photos)
|
||||
photos = store.validate_photos(raw_photos)
|
||||
res = st.add_receipt(order_id, qty, receipt_date=rf["receipt_date"], memo=rf["memo"],
|
||||
confirm_over="1" in form.getlist("confirm_over"), by=user.get("email", ""), photos=photos)
|
||||
except OverReceipt as exc:
|
||||
# 화면이 다시 그려지면 고른 파일은 사라진다 — 사진을 골랐었다면 다시 첨부하라고 알린다
|
||||
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, over=exc.over,
|
||||
photos_lost=had_photos, status_code=409)
|
||||
except LookupError:
|
||||
raise HTTPException(status_code=404, detail="발주서를 찾을 수 없습니다.") from None
|
||||
except ValueError as exc:
|
||||
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, error=str(exc),
|
||||
photos_lost=had_photos, status_code=400)
|
||||
note = (f"입고 {res['total']:,}개를 저장했습니다." + (" (초과 입고 포함)" if res["over"] else "")
|
||||
+ (f" 입고증 사진 {res['photos']}장." if res.get("photos") else ""))
|
||||
return _redirect(f"/inout/orders/{order_id}", note)
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/receipts/{receipt_id}/delete")
|
||||
def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
try:
|
||||
st.delete_receipt(order_id, receipt_id, by=user.get("email", ""))
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", "입고 기록을 지웠습니다 — 그만큼 다시 미입고로 잡힙니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 입고증 사진(003) — 입고와 함께 / 나중에 더하기 / 지우기 / 보기
|
||||
# ────────────────────────────────────────────────────────────
|
||||
_PHOTO_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
||||
"Cache-Control": "private, max-age=86400",
|
||||
}
|
||||
|
||||
|
||||
async def _read_photos(form: Any) -> list[tuple[str, bytes]]:
|
||||
"""폼의 photos 파일들 → [(이름, 내용)]. 한 장은 한도 + 1바이트까지만 읽는다(너무 크면 검사에서 거절)."""
|
||||
out: list[tuple[str, bytes]] = []
|
||||
for f in form.getlist("photos"):
|
||||
if not hasattr(f, "read"):
|
||||
continue
|
||||
if len(out) > store.MAX_PHOTOS:
|
||||
raise ValueError(f"입고 한 건에 사진은 {store.MAX_PHOTOS}장까지입니다.")
|
||||
out.append((str(getattr(f, "filename", "") or ""), await f.read(store.MAX_PHOTO_BYTES + 1)))
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/receipts/{receipt_id}/photos")
|
||||
async def receipt_photos_add(request: Request, order_id: int, receipt_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
try:
|
||||
n = st.add_receipt_photos(order_id, receipt_id, await _read_photos(await request.form()), by=user.get("email", ""))
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", f"입고증 사진 {n}장을 더했습니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/photos/{photo_id}/delete")
|
||||
def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
try:
|
||||
st.delete_receipt_photo(order_id, photo_id)
|
||||
except (ValueError, LookupError) as exc:
|
||||
return _redirect(f"/inout/orders/{order_id}", str(exc))
|
||||
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
|
||||
|
||||
|
||||
@router.get("/photos/{photo_id}")
|
||||
def photo_view(request: Request, photo_id: int) -> Response:
|
||||
_user(request)
|
||||
st = _store(request)
|
||||
row = st.get_photo(photo_id) if st is not None else None
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
name = quote(str(row["filename"] or f"photo-{photo_id}"))
|
||||
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
|
||||
return Response(content=bytes(row["data"]), media_type=row["content_type"],
|
||||
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 발주 메일 — 발주 담당 본인 Gmail(003). 연결은 사람마다 한 번, 보내기는 [메일 발송]을 눌렀을 때만.
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _callback_url(request: Request) -> str:
|
||||
from app.main import public_url_for # noqa: WPS433
|
||||
|
||||
return public_url_for(request, "inout_gmail_callback")
|
||||
|
||||
|
||||
def _safe_next(nxt: Any) -> str:
|
||||
s = str(nxt or "")
|
||||
return s if s.startswith("/inout/") and "//" not in s and "\\" not in s else "/inout/"
|
||||
|
||||
|
||||
@router.get("/gmail/connect")
|
||||
async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa: A002 — 쿼리 이름
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
|
||||
|
||||
from . import gmail # noqa: WPS433
|
||||
|
||||
try:
|
||||
client = gmail.oauth_client()
|
||||
except gmail.GmailError as exc:
|
||||
return _redirect(_safe_next(next), str(exc))
|
||||
request.session["_inout_gmail_next"] = _safe_next(next)
|
||||
return await client.authorize_redirect(
|
||||
request, public_url_for(request, "inout_gmail_callback"),
|
||||
access_type="offline", prompt="consent", include_granted_scopes="true",
|
||||
login_hint=user.get("email", ""), hd=ALLOWED_DOMAIN)
|
||||
|
||||
|
||||
@router.get("/gmail/callback", name="inout_gmail_callback")
|
||||
async def gmail_callback(request: Request) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "order")
|
||||
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
|
||||
|
||||
from . import gmail # noqa: WPS433
|
||||
|
||||
nxt = _safe_next(request.session.pop("_inout_gmail_next", "/inout/"))
|
||||
email = user.get("email", "")
|
||||
try:
|
||||
token = await gmail.oauth_client().authorize_access_token(request)
|
||||
refresh, scopes = gmail.check_grant(token, expected_email=email)
|
||||
st.save_gmail_token(email, refresh_token_enc=gmail.encrypt_token(email, refresh), scopes=scopes)
|
||||
except OAuthError as exc:
|
||||
msg = "Gmail 연결을 취소했습니다." if exc.error == "access_denied" else f"Gmail 연결 실패({exc.error})"
|
||||
return _redirect(nxt, msg)
|
||||
except (gmail.GmailError, ValueError) as exc:
|
||||
return _redirect(nxt, str(exc))
|
||||
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.")
|
||||
|
||||
|
||||
@router.post("/gmail/disconnect")
|
||||
def gmail_disconnect(request: Request) -> JSONResponse:
|
||||
user = _user(request)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail="입출고 관리 모듈이 설정되지 않았습니다.")
|
||||
from . import gmail # noqa: WPS433
|
||||
|
||||
row = st.gmail_token(user.get("email", ""))
|
||||
if row:
|
||||
try:
|
||||
gmail.revoke(gmail.decrypt_token(user.get("email", ""), row["refresh_token_enc"]))
|
||||
except (gmail.GmailError, gmail.GmailNotConnected):
|
||||
pass
|
||||
st.delete_gmail_token(user.get("email", ""))
|
||||
return JSONResponse({"ok": True, "message": "Gmail 연결을 끊었습니다."})
|
||||
|
||||
|
||||
def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], dict[str, Any]]:
|
||||
user = _user(request)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail="입출고 관리 모듈이 설정되지 않았습니다.")
|
||||
_require(st, user, "order")
|
||||
order = _order_or_404(st, order_id)
|
||||
if order["cancelled_at"]:
|
||||
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
|
||||
return st, user, order
|
||||
|
||||
|
||||
@router.get("/orders/{order_id}/mail")
|
||||
def mail_preview(request: Request, order_id: int) -> JSONResponse:
|
||||
"""메일 미리보기 — 받는 사람(공장 이메일)·제목·본문, Gmail 연결 여부, 보낸 기록."""
|
||||
st, user, order = _mail_order(request, order_id)
|
||||
from . import gmail # noqa: WPS433
|
||||
|
||||
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=user.get("email", ""))
|
||||
tok = st.gmail_token(user.get("email", ""))
|
||||
return JSONResponse({
|
||||
"connected": tok is not None, "configured": gmail.configured(),
|
||||
"connect_url": f"/inout/gmail/connect?{urlencode({'next': f'/inout/orders/{order_id}?mail=1'})}",
|
||||
"callback_url": _callback_url(request), # 구글 클라우드 승인된 리디렉션 URI 에 등록해야 하는 주소(안내용)
|
||||
"from": user.get("email", ""), "to": order.get("factory_email") or "", "factory": order["factory_name"],
|
||||
"subject": mail["subject"], "html": mail["html"],
|
||||
"sent": [{"at": store.fmt_datetime(m["sent_at"]), "by": m["sent_by"], "to": m["to_addrs"]} for m in order["mails"]],
|
||||
})
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/mail")
|
||||
def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""[메일 발송] — 사람이 누를 때만. 이미 보낸 발주서는 resend=true 를 함께 보내야(실수로 두 번 보내지 않게)."""
|
||||
st, user, order = _mail_order(request, order_id)
|
||||
from . import gmail # noqa: WPS433
|
||||
|
||||
email = user.get("email", "")
|
||||
try:
|
||||
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
|
||||
cc = store.parse_emails(payload.get("cc"), label="참조")
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
if order["mails"] and not payload.get("resend"):
|
||||
return JSONResponse({"ok": False, "resend_needed": True,
|
||||
"message": f"이미 {len(order['mails'])}번 보낸 발주서입니다. 다시 보낼까요?"}, status_code=409)
|
||||
row = st.gmail_token(email)
|
||||
if row is None:
|
||||
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
|
||||
status_code=409)
|
||||
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
|
||||
try:
|
||||
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
|
||||
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
|
||||
subject=mail["subject"], text=mail["text"], html=mail["html"])
|
||||
gid = gmail.send(refresh, raw)
|
||||
except gmail.GmailNotConnected as exc:
|
||||
st.delete_gmail_token(email)
|
||||
return JSONResponse({"ok": False, "reconnect": True, "message": str(exc)}, status_code=409)
|
||||
except gmail.GmailError as exc:
|
||||
st.mark_gmail(email, error=str(exc))
|
||||
return JSONResponse({"ok": False, "message": str(exc)}, status_code=502)
|
||||
st.add_order_mail(order_id, sent_by=email, to=to, cc=cc, subject=mail["subject"], gmail_id=gid)
|
||||
st.mark_gmail(email)
|
||||
return JSONResponse({"ok": True, "message": f"메일을 보냈습니다 → {', '.join(to)}"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 옵션 — 공장·발주 담당·입고 담당(ERP 관리자)
|
||||
# ────────────────────────────────────────────────────────────
|
||||
def _candidates() -> list[dict[str, str]]:
|
||||
"""담당자 후보 — 입출고 모듈 권한이 있는 등록 사용자."""
|
||||
from app.main import user_store # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
out = []
|
||||
for u in user_store.list_all():
|
||||
if has_module(u, "inout"):
|
||||
out.append({"email": str(u.get("email") or "").lower(), "name": str(u.get("name") or "")})
|
||||
return sorted(out, key=lambda x: x["email"])
|
||||
|
||||
|
||||
def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
||||
roles = st.list_roles()
|
||||
cands = _candidates()
|
||||
known = {c["email"] for c in cands}
|
||||
for emails in roles.values(): # 권한이 빠졌어도 담당으로 남아 있는 사람은 보여 줘야 뺄 수 있다
|
||||
for e in emails:
|
||||
if e not in known:
|
||||
cands.append({"email": e, "name": "(입출고 모듈 권한 없음)"})
|
||||
known.add(e)
|
||||
reader = _items(request)
|
||||
products = st.list_products()
|
||||
for pr in products:
|
||||
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
||||
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
||||
"fmt_num": store.fmt_num,
|
||||
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
|
||||
"candidates": cands,
|
||||
"items_status": "연결됨" if reader is not None and reader.enabled else (reader.reason if reader else "없음")}
|
||||
|
||||
|
||||
def _is_popup(request: Request) -> bool:
|
||||
"""옵션 팝업(inout.js)이 보낸 요청 — 이동 대신 JSON 으로 답하고 팝업이 제자리에서 다시 그린다."""
|
||||
return request.headers.get("x-inout-options") == "1"
|
||||
|
||||
|
||||
def _options_done(request: Request, message: str, *, ok: bool = True) -> Any:
|
||||
if _is_popup(request):
|
||||
return JSONResponse({"ok": ok, "message": message}, status_code=200 if ok else 400)
|
||||
return _redirect("/inout/?options=1", message)
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings(request: Request, panel: int = 0) -> Any:
|
||||
"""옵션 — 팝업(톱니)으로 연다. panel=1 = 팝업 안 내용만, 그 밖엔 발주 목록으로 가서 팝업을 띄운다(예전 주소 호환)."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
if not panel:
|
||||
return RedirectResponse(url="/inout/?options=1", status_code=303)
|
||||
from app.main import render_template # noqa: WPS433
|
||||
|
||||
return render_template(request, "inout/_options_panel.html", _options_ctx(request, st))
|
||||
|
||||
|
||||
@router.post("/settings/factories")
|
||||
async def settings_factory_save(request: Request) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
form = await request.form()
|
||||
try:
|
||||
st.save_factory(factory_id=_opt_int(form.get("id")), name=str(form.get("name") or ""),
|
||||
manager=str(form.get("manager") or ""), contact=str(form.get("contact") or ""),
|
||||
email=str(form.get("email") or ""),
|
||||
memo=str(form.get("memo") or ""), is_active=form.get("is_active") == "1",
|
||||
sort_order=_opt_int(form.get("sort_order")) or 0)
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, "공장을 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/factories/{factory_id}/delete")
|
||||
def settings_factory_delete(request: Request, factory_id: int) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
st.delete_factory(factory_id)
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, "공장을 지웠습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/roles")
|
||||
async def settings_roles(request: Request) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
form = await request.form()
|
||||
for role in store.ROLES:
|
||||
st.set_role_members(role, [str(e) for e in form.getlist(f"{role}_email")], by=user.get("email", ""))
|
||||
return _options_done(request, "담당자를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/products/import")
|
||||
def settings_products_import(request: Request) -> Any:
|
||||
"""[단품 불러오기] — 코드표 단품 전체 → 상품 정보. 값을 넣은 상품·제외한 단품은 그대로."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
reader = _items(request)
|
||||
items = reader.list_all() if reader is not None else None
|
||||
if items is None:
|
||||
return _options_done(request, "코드표 DB(itemcode_db)에 연결할 수 없어 단품을 불러오지 못했습니다"
|
||||
+ ("" if reader is None or reader.enabled else " (ITEMCODE_DB_URL 미설정)") + ".", ok=False)
|
||||
try:
|
||||
r = st.import_products(items, by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
parts = [f"새 단품 {r['added']}개"]
|
||||
if r["renamed"]:
|
||||
parts.append(f"이름 바뀐 {r['renamed']}개")
|
||||
if r["kept"]:
|
||||
parts.append(f"값을 넣은 {r['kept']}개는 그대로")
|
||||
if r["excluded"]:
|
||||
parts.append(f"지운 {r['excluded']}개는 건너뜀")
|
||||
return _options_done(request, "단품을 불러왔습니다 — " + ", ".join(parts) + ".")
|
||||
|
||||
|
||||
@router.post("/settings/products/save")
|
||||
def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)) -> Any:
|
||||
"""단가·무게·은 함유량 저장 — rows = [{code, unit_price, weight_g, silver_pct}](바뀐 줄만). 하나라도 틀리면 아무것도 저장 안 함."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
rows, errors = [], []
|
||||
for r in (payload.get("rows") or [])[:5000]:
|
||||
code = str((r or {}).get("code") or "").strip().upper()
|
||||
try:
|
||||
rows.append({"code": code, **store.validate_product_values(r)})
|
||||
except ValueError as exc:
|
||||
errors.append(f"{code}: {exc}")
|
||||
if errors:
|
||||
return _options_done(request, "저장하지 못했습니다 — " + " / ".join(errors[:5]) + (" …" if len(errors) > 5 else ""), ok=False)
|
||||
if not rows:
|
||||
return _options_done(request, "바뀐 값이 없습니다.", ok=False)
|
||||
try:
|
||||
n = st.save_products(rows, by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"상품 정보 {n}개를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/products/{code}/exclude")
|
||||
def settings_product_exclude(request: Request, code: str) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
st.exclude_product(code.strip().upper(), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"{code} 를 지웠습니다 — 다음 불러오기에서도 빠집니다(제외 목록에서 되살릴 수 있음).")
|
||||
|
||||
|
||||
@router.post("/settings/products/{code}/restore")
|
||||
def settings_product_restore(request: Request, code: str) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "admin")
|
||||
try:
|
||||
st.restore_product(code.strip().upper(), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _options_done(request, str(exc), ok=False)
|
||||
return _options_done(request, f"{code} 를 되살렸습니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# API · 상태
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/api/items")
|
||||
def api_items(request: Request, q: str = "") -> JSONResponse:
|
||||
"""발주서 제품 고르기 — 옵션 → 상품 정보(불러온 단품, 지운 것 제외)가 있으면 거기서, 없으면 코드표 단품."""
|
||||
_user(request)
|
||||
st = _store(request)
|
||||
if st is not None and st.catalog_count() > 0:
|
||||
rows = st.catalog_search(q, limit=30)
|
||||
return JSONResponse({"enabled": True, "source": "products", "items": [
|
||||
{"code": r["item_code"], "name": r["item_name"],
|
||||
"unit_price": store.fmt_num(r["unit_price"]) if r["unit_price"] is not None else "",
|
||||
"price": float(r["unit_price"]) if r["unit_price"] is not None else None,
|
||||
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else ""} for r in rows]})
|
||||
reader = _items(request)
|
||||
if reader is None or not reader.enabled:
|
||||
return JSONResponse({"items": [], "enabled": False,
|
||||
"message": "코드표 DB(ITEMCODE_DB_URL)가 연결되지 않았습니다."})
|
||||
return JSONResponse({"items": reader.search(q, limit=30), "enabled": True})
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> dict[str, str]:
|
||||
return {"status": "ok" if _store(request) is not None else "not_configured"}
|
||||
@@ -0,0 +1,451 @@
|
||||
"""입출고 관리 — 상수·검사·상태 계산(순수 함수, 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 결과.
|
||||
품목마다 단가·금액(수량 × 단가)·PP량(개당 g = 무게)·은 함유량(%·개당 g) — 발주 품목에 남긴 그때 값(004). 없으면 '-'."""
|
||||
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}"))
|
||||
if money["pp_kg"] is not None:
|
||||
facts.append(("PP 총량", f"{fmt_num(money['pp_kg'], 2)} kg"))
|
||||
if money["silver_g"] is not None:
|
||||
facts.append(("은(Ag) 총량", f"{fmt_num(money['silver_g'], 2)} g"))
|
||||
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"))
|
||||
amt = line_amount(int(x["qty"]), price)
|
||||
ag = silver_g(w, pct)
|
||||
return {"price": fmt_num(price) if price is not None else "-", "amount": fmt_num(amt) if amt is not None else "-",
|
||||
"pp": fmt_num(w) if w is not None else "-",
|
||||
"ag": (f"{fmt_num(pct, 4)}%" + (f" ({fmt_num(ag, 4)}g)" if ag is not None else "")) if pct is not None else "-"}
|
||||
|
||||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||
text += [f"- {k}: {v}" for k, v in facts]
|
||||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · PP(g/개) · 은 함유량"]
|
||||
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" · PP {c['pp'] + 'g' if c['pp'] != '-' 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;"
|
||||
fact_rows = "".join(f'<tr><th style="{td}background:#f6f7f9;text-align:left;white-space:nowrap">{e(k)}</th>'
|
||||
f'<td style="{td}">{e(str(v))}</td></tr>' for k, v in facts)
|
||||
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["pp"])}</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 = f'{fmt_num(money["pp_kg"], 2)} kg' if money["pp_kg"] is not None else ""
|
||||
foot_ag = f'{fmt_num(money["silver_g"], 2)} g' if money["silver_g"] 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 style="border-collapse:collapse;margin:8px 0 16px">{fact_rows}</table>'
|
||||
'<table style="border-collapse:collapse;min-width:640px">'
|
||||
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||
f'<th style="{td}">PP(g/개)</th><th style="{td}">은(Ag) 함유량</th><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_ag)}</th><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)."""
|
||||
amount = pp = ag = 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
|
||||
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag}
|
||||
|
||||
|
||||
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
|
||||
@@ -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,129 @@
|
||||
{% 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>
|
||||
</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>
|
||||
{% 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>
|
||||
|
||||
<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=20261017c" />{% 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=20261017a" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,227 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
{% set receiving = perms.can_receive and can_receive_now %}
|
||||
{% 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">입고 저장</button>{% endif %}
|
||||
<input type="hidden" name="confirm_over" value="" id="io-confirm-over" />
|
||||
<div class="erp-card-block-head">
|
||||
<h2>품목</h2>
|
||||
{% if 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 }} 이번 입고 수량" /></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">
|
||||
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required /></label>
|
||||
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등" /></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 }}" />
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
|
||||
사진 고르기·찍기
|
||||
</label>
|
||||
</div>
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="io-fill-remaining">남은 수량 모두 채우기</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">입고 저장 <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>{% 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>
|
||||
{% 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) #}
|
||||
<dialog class="io-dlg io-mail-dlg" id="io-mail" aria-labelledby="io-mail-title" tabindex="-1">
|
||||
<header class="io-dlg-head">
|
||||
<h2 id="io-mail-title">발주 메일 보내기 · {{ order.order_no }}</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-mail-body"><p class="erp-muted">불러오는 중…</p></div>
|
||||
<footer class="io-dlg-footbar" id="io-mail-foot" hidden>
|
||||
<button type="button" class="io-link-btn" id="io-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" id="io-mail-send">메일 발송</button>
|
||||
</footer>
|
||||
</dialog>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
|
||||
@@ -0,0 +1,83 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017c" />{% 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=20261017a" 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=20261017c" />{% 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=20261017a" 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 알림 프로그램은 아직 미지원.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
{% block head_extra %}
|
||||
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261013i" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
{% endblock %}
|
||||
@@ -64,7 +64,7 @@
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# [실적] 실적 모듈 — `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` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
||||
|
||||
## 광고비 (`/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 중앙은행 고시 환율 종합, 키 없음). 상세보기 [합계 | 계정별] 탭, [메타 광고 불러오기]·자동 업데이트 회차.
|
||||
@@ -16,6 +16,12 @@ 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), 나머지 항목은 화면 이름 그대로."""
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -4,8 +4,9 @@ from __future__ import annotations
|
||||
|
||||
from .base import AdSource
|
||||
from .google_ads import GoogleAdsSource
|
||||
from .meta_ads import MetaAdsSource
|
||||
|
||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(),)
|
||||
_SOURCES: tuple[AdSource, ...] = (GoogleAdsSource(), MetaAdsSource())
|
||||
_BY_CODE = {s.code: s for s in _SOURCES}
|
||||
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ 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).
|
||||
@@ -341,8 +342,8 @@ def merge_results(parsed: list[tuple[str, float, ParseResult]]) -> tuple[ParseRe
|
||||
return merged, sorted(overlap)
|
||||
|
||||
|
||||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글은 광고 API 로 가져온 항목(2026-10-15)
|
||||
DETAIL_CHANNELS = frozenset({"naver", "google"})
|
||||
# 머리글을 누르면 일자별 상세 표가 열리는 채널(보고서 항목을 보관하는 채널) — 구글(2026-10-15)·메타(2026-10-16)는 광고 API 로 가져온 항목
|
||||
DETAIL_CHANNELS = frozenset({"naver", "google", "meta"})
|
||||
|
||||
|
||||
def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
@@ -351,11 +352,13 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
cols: list[str] = []
|
||||
for r in rows:
|
||||
for k in (r.get("metrics") or {}):
|
||||
if k not in cols:
|
||||
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()}
|
||||
@@ -367,12 +370,46 @@ def detail_table(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
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": r.get("metrics") or {}} for r in rows]
|
||||
"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}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 화면 데이터
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -22,6 +22,7 @@ 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()
|
||||
|
||||
@@ -57,7 +58,8 @@ class AdSyncService:
|
||||
@staticmethod
|
||||
def _message(exc: Exception, ctx: AdapterContext) -> str:
|
||||
known = getattr(ctx.credentials, "known_secrets", lambda: [])()
|
||||
return redact_text(str(getattr(exc, "message", "") or exc), known)
|
||||
# 광고 연동 오류는 고칠 곳 안내·진단이 붙어 길다 — 기본 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]:
|
||||
|
||||
@@ -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()
|
||||
@@ -17,8 +17,8 @@ JSON API — 모듈 권한
|
||||
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일 넘으면 관리자
|
||||
GET /performance/api/ad-spend/{channel}/details?from=&to= 일자별 보고서 항목(네이버·구글·메타 머리글 클릭)
|
||||
POST /performance/api/ad-sources/{code}/sync 광고 API(구글·메타 광고) 가져오기 — 보는 기간(오늘까지), 92일 넘으면 관리자
|
||||
JSON API — 관리자
|
||||
GET|PUT /performance/api/ad-sources/{code}/credentials 광고 API 인증정보(마이그레이션 007, 암호화 저장·비밀 원문 없음)
|
||||
POST /performance/api/ad-sources/{code}/test 광고 API 연결 테스트(저장값 또는 새 입력값)
|
||||
@@ -490,7 +490,7 @@ def api_ad_spend_details(request: Request, channel: str, from_: str = Query(...,
|
||||
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)})
|
||||
"to": end.isoformat(), **ad_spend.detail_table(rows), **ad_spend.detail_tabs(rows)})
|
||||
|
||||
|
||||
@router.post("/api/ad-spend/upload")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -89,7 +89,7 @@
|
||||
<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(전환 가치 ÷ 비용){% 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 %}
|
||||
{% 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>
|
||||
@@ -119,10 +119,10 @@
|
||||
</div>
|
||||
{% if period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 ROAS 를 계산하지 않고,
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글 머리글을 누르면 일자별 보고서 항목.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출). 메타는 메타 광고 API 의 구매 ROAS(구매 전환값 ÷ 지출 금액),
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
|
||||
구글은 [구글 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -200,8 +200,8 @@
|
||||
</div>
|
||||
|
||||
<p class="perf-foot perf-muted">
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함).
|
||||
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(메타는 계산 안 함, 네이버·구글은 광고 쪽 값).
|
||||
광고비 기준: 쿠팡(윙)·쿠팡(로켓)은 광고 보고서의 청구금액(+부가가치세), 구글은 구글 광고 비용 + 부가세 10%(부가세 포함), 메타는 지출 금액 그대로(이미 부가세 포함).
|
||||
ROAS = 그 쇼핑몰 매출 ÷ 광고비 × 100(네이버·구글·메타는 광고 쪽 값).
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
메타는 지금은 직접 입력합니다.
|
||||
</p>
|
||||
@@ -224,4 +224,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -255,4 +255,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261015a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261016a" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -103,13 +103,13 @@
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
{# 광고 API 연동(2026-10-15, 마이그레이션 007) — 구글 광고 등. 인증정보는 쇼핑몰과 같은 마스터 키로 암호화 저장.
|
||||
{# 광고 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>
|
||||
설정이 끝나면 광고비 탭 [구글 광고 불러오기]·[메타 광고 불러오기]와 매출 자동 업데이트(30분마다 최근 며칠) 때 함께 가져옵니다.</span>
|
||||
</div>
|
||||
{% if not ad_api_ready %}
|
||||
<div class="perf-notice is-warn">광고 API 인증정보 저장 표가 아직 없습니다. performance_db 마이그레이션 007
|
||||
@@ -142,7 +142,8 @@
|
||||
</table>
|
||||
</div>
|
||||
<p class="perf-foot perf-muted">
|
||||
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.
|
||||
구글 광고: 광고비 = 구글 광고 화면의 "비용" + 부가세 10%(부가세 포함), ROAS = 전환 가치 ÷ 비용(구글 화면 값 그대로). 날짜는 광고 계정 시간대 기준이며 원화(KRW) 계정만 가져옵니다.<br>
|
||||
메타 광고: 광고비 = 광고 관리자의 "지출 금액" 그대로(메타 금액은 이미 부가세 포함), ROAS = 구매 전환값 ÷ 지출 금액(광고 관리자 "구매 ROAS"). 광고 계정이 여러 개면 날짜별로 합칩니다. 날짜는 광고 계정 시간대 기준이며, 달러 등 외화 계정은 그날 환율로 원화로 바꿔 넣습니다(중앙은행 고시 환율 종합, 그날 값이 없으면 직전 값).
|
||||
가져온 날은 직접 입력·업로드 값보다 우선해 덮어씁니다.
|
||||
</p>
|
||||
</div>
|
||||
@@ -248,4 +249,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261015b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261016a" defer></script>{% endblock %}
|
||||
|
||||
@@ -126,7 +126,7 @@ def test_ad_dashboard_month():
|
||||
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", "naver"] # 구글 = 광고 API 로 가져온 항목(2026-10-15)
|
||||
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
|
||||
|
||||
@@ -306,7 +306,9 @@ def test_sync_endpoint(monkeypatch):
|
||||
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/meta/sync", json={}).status_code == 404
|
||||
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"]
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,123 @@
|
||||
# [프로젝트] 프로젝트 관리 모듈(아사나식) — `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`, 기본 대시보드)·내 작업(접이식)·목표.
|
||||
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
||||
- 사이드바 전체 검색(`/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`, 새 작업은 제목이 생기는 순간 생성).
|
||||
- 설명란 서식 도구에 글자 색·크기(서버는 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`).
|
||||
@@ -1842,6 +1842,30 @@ class ProjectStore:
|
||||
return False
|
||||
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:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
|
||||
@@ -899,6 +899,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
|
||||
{
|
||||
"user": user,
|
||||
**_role_ctx(user),
|
||||
"pj_options": _project_options(st),
|
||||
"can_manage": can_manage,
|
||||
"nav_items": build_erp_nav(user, active="project"),
|
||||
"page_title": project["name"],
|
||||
@@ -967,6 +968,43 @@ def _db_or_503(request: Request) -> Any:
|
||||
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")
|
||||
def api_list_projects(request: Request) -> JSONResponse:
|
||||
user = _require_user(request)
|
||||
|
||||
@@ -375,6 +375,47 @@ def validate_time(t: Any) -> str | None:
|
||||
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) — 사이드바 "목표" → 연도
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{{ page_title or '주간 회의록' }}</title>
|
||||
<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 %}
|
||||
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||
<script>
|
||||
@@ -17,6 +17,6 @@
|
||||
</head>
|
||||
<body class="erp-body">
|
||||
<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>
|
||||
</html>
|
||||
|
||||
@@ -1,25 +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 옵션">
|
||||
<span class="material-symbols-outlined">settings</span>
|
||||
</button>
|
||||
<dialog class="pj-options-dialog" id="pj-options-dialog" aria-labelledby="pj-options-title">
|
||||
<form id="pj-options-form">
|
||||
<h2 id="pj-options-title">Project 옵션</h2>
|
||||
<label for="pj-options-font">폰트</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>
|
||||
<p>이 브라우저의 모든 Project 화면에 적용됩니다.</p>
|
||||
{% if user and user.is_super_admin %}<p class="pj-options-notice"><a class="pj-btn" href="/notice/"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">campaign</span> 긴급 공지 만들기·관리</a> <small>ERP 전체 화면 가운데에 띄우는 공지(수퍼관리자)</small></p>{% endif %}
|
||||
<p class="pj-options-error" id="pj-options-error" role="alert" hidden></p>
|
||||
<div class="pj-options-actions">
|
||||
<header class="pj-options-head">
|
||||
<h2 id="pj-options-title"><span class="material-symbols-outlined">tune</span> Project 옵션</h2>
|
||||
<button type="button" class="pj-options-x" id="pj-options-x" aria-label="닫기" title="닫기">
|
||||
<span class="material-symbols-outlined">close</span>
|
||||
</button>
|
||||
</header>
|
||||
<div class="pj-options-body">
|
||||
<nav class="pj-options-nav" role="tablist" aria-orientation="vertical" aria-label="옵션 분류">
|
||||
<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">
|
||||
<span class="material-symbols-outlined">text_fields</span>일반</button>
|
||||
{% if pj_admin %}
|
||||
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-view" id="pj-opt-tab-view" data-pane="view" tabindex="-1">
|
||||
<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="submit" class="pj-btn pj-btn-primary" id="pj-options-save">저장</button>
|
||||
</div>
|
||||
</footer>
|
||||
</form>
|
||||
</dialog>
|
||||
<script>
|
||||
@@ -29,4 +105,4 @@
|
||||
document.documentElement.dataset.pjFont = pf;
|
||||
} catch (_) {}
|
||||
</script>
|
||||
<script src="/static/project-options.js?v=20261002g" defer></script>
|
||||
<script src="/static/project-options.js?v=20261016c" defer></script>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -298,5 +298,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -116,8 +116,13 @@
|
||||
<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">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 폰트를 고르고 미리 본 뒤 <span class="pjh-ui">저장</span>을 누르면 Project 화면에 적용되고 창이 닫힙니다.
|
||||
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
|
||||
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
|
||||
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
|
||||
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
|
||||
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
|
||||
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
|
||||
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||
</ul>
|
||||
<h3>프로젝트 제목</h3>
|
||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -29,6 +29,8 @@
|
||||
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-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 }}">
|
||||
|
||||
<div class="pj-layout">
|
||||
@@ -470,5 +472,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261015e" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261016b" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261015c" defer></script>
|
||||
<script src="/static/project.js?v=20261016d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# [휴가] 휴가 관리 모듈 — `app/modules/vacation/`, `vacation_db`
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `app/static/vacation.css`, `app/static/vacation.js`. 템플릿: `templates/`.
|
||||
|
||||
- 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 공휴일·연차 설정.
|
||||
- 권한키 `vacation`(사용)·`vacation_approver`(승인).
|
||||
@@ -4,6 +4,22 @@
|
||||
없다. 화면 정중앙에 같은 모양으로 띄우기 위해 직접 그린다(erp-dialog.js).
|
||||
════════════════════════════════════════════════════ */
|
||||
|
||||
/* 모달 <dialog> 위에 띄울 때 감싸는 껍데기(erp-dialog.js) — 모양은 안쪽 .erp-dialog-backdrop 그대로, 껍데기는 보이지 않게 */
|
||||
.erp-dialog-host {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
overflow: visible;
|
||||
}
|
||||
.erp-dialog-host::backdrop { background: transparent; }
|
||||
|
||||
.erp-dialog-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
|
||||
@@ -116,11 +116,23 @@
|
||||
var previous = document.activeElement;
|
||||
var closed = false;
|
||||
|
||||
// 모달 <dialog>(showModal — 브라우저 맨 위 층)가 열려 있으면 body 에 붙인 창은 그 뒤에 깔려 안 보이고 눌리지도 않는다
|
||||
// (예: 입출고 옵션 팝업 안 [지우기] 확인). 그때만 이 창도 모달 <dialog> 로 감싸 그 위에 띄운다. 평소엔 예전 그대로.
|
||||
var host = null;
|
||||
try {
|
||||
if (document.querySelector("dialog[open]:modal")) {
|
||||
host = document.createElement("dialog");
|
||||
host.className = "erp-dialog-host";
|
||||
host.addEventListener("cancel", function (e) { e.preventDefault(); close(false); }); // Esc = 취소
|
||||
}
|
||||
} catch (_) { host = null; } // :modal 을 모르는 아주 옛 브라우저
|
||||
|
||||
function close(result) {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
el.backdrop.remove();
|
||||
if (host) { if (host.open) host.close(); host.remove(); }
|
||||
if (previous && typeof previous.focus === "function") previous.focus();
|
||||
// 입력창이면 확인 = 입력한 글자, 취소 = null
|
||||
if (el.input) resolve(result ? el.input.value : null);
|
||||
@@ -154,7 +166,13 @@
|
||||
});
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
|
||||
document.body.appendChild(el.backdrop);
|
||||
if (host) {
|
||||
host.appendChild(el.backdrop);
|
||||
document.body.appendChild(host);
|
||||
host.showModal();
|
||||
} else {
|
||||
document.body.appendChild(el.backdrop);
|
||||
}
|
||||
if (el.input) { el.input.focus(); el.input.select(); }
|
||||
else el.ok.focus();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
/* 입출고 관리(inout) — ERP 공용(erp.css·erp-shell.css) 위에 이 화면만의 것 */
|
||||
/* 공용 .erp-page 는 width:100% + 안쪽 여백(content-box)이라 표가 넓으면 48px 넘친다 — 이 화면에서만 테두리 기준으로 */
|
||||
.erp-page:has(> .io) { box-sizing: border-box; }
|
||||
.io { display: flex; flex-direction: column; gap: 14px; min-width: 0; } /* 넓은 표는 안에서 가로 스크롤(페이지가 화면보다 넓어지지 않게) */
|
||||
.io-nav { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.io-nav-gap { flex: 1 1 auto; }
|
||||
.io-roles { display: inline-flex; gap: 4px; align-items: center; }
|
||||
.io-flash { margin: 0; padding: 10px 14px; border-radius: 8px; background: #eef6ff; color: #0b4a8b; font-size: 13px; border: 1px solid #cfe3fb; }
|
||||
.io-error { margin: 12px 20px 0; padding: 10px 14px; border-radius: 8px; background: #fbe9e6; color: #a1261b; border: 1px solid #efc6bf; font-size: 13px; }
|
||||
.io > .io-error { margin: 0; }
|
||||
.io-hint { color: #a1261b; font-size: 12px; }
|
||||
.io-help { margin: 0; padding: 12px 20px 0; font-size: 12.5px; color: var(--color-midtone-gray); line-height: 1.6; }
|
||||
.io-foot { margin: 0; }
|
||||
|
||||
/* 거르기 줄 */
|
||||
.io-filter { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.io-filter .erp-select { width: auto; }
|
||||
.io-search { width: 260px; }
|
||||
.io-filter input[type="date"] { width: 150px; }
|
||||
.io-date { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--color-midtone-gray); }
|
||||
.io-seg { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash); border-radius: 10px; background: #fff; }
|
||||
.io-seg-btn { padding: 5px 12px; border-radius: 8px; font-size: 12.5px; color: var(--color-rich-black); text-decoration: none; white-space: nowrap; }
|
||||
.io-seg-btn:hover { background: var(--color-ghost-gray); }
|
||||
.io-seg-btn.is-active, .io-seg-btn.is-active:hover { background: var(--color-deep-black); color: #fff; }
|
||||
|
||||
/* 표 */
|
||||
.io-table td, .io-table th { white-space: nowrap; }
|
||||
.io-table td.io-items { white-space: normal; min-width: 160px; }
|
||||
.io-num { text-align: right !important; font-variant-numeric: tabular-nums; }
|
||||
.io-code { font-family: ui-monospace, Consolas, monospace; font-size: 12px; }
|
||||
.io-order-no { font-weight: 600; color: var(--color-rich-black); text-decoration: none; font-family: ui-monospace, Consolas, monospace; }
|
||||
.io-order-no:hover { text-decoration: underline; }
|
||||
.io-row-link { cursor: pointer; }
|
||||
.io-row-link.is-late td:first-child { box-shadow: inset 3px 0 0 #d93025; }
|
||||
.io-remaining { color: #b45309; font-weight: 600; }
|
||||
.io-over, .io-over-sub { color: #d93025; font-weight: 600; }
|
||||
.io-over-sub { font-size: 11px; }
|
||||
.io-late { color: #d93025; font-weight: 600; font-size: 12px; }
|
||||
.io-block { overflow: visible; }
|
||||
|
||||
/* 상태 배지 */
|
||||
.io-badge { display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 600; white-space: nowrap; border: 1px solid transparent; }
|
||||
.io-st-open, .io-st-none { background: #eef0f2; color: #3d4148; }
|
||||
.io-st-partial { background: #fff4e0; color: #9a5b00; border-color: #f6dcae; }
|
||||
.io-st-done { background: #e6f8e9; color: #1e7a34; border-color: #c2efc8; }
|
||||
.io-st-over { background: #fbe9e6; color: #b3261e; border-color: #efc6bf; }
|
||||
.io-st-closed { background: #f4f4f5; color: #6b6f76; border-color: #dcdde0; }
|
||||
.io-st-cancelled { background: #fff; color: #9aa0a6; border-color: #dcdde0; text-decoration: line-through; }
|
||||
|
||||
/* 진행률 */
|
||||
.io-progress { display: inline-block; width: 80px; height: 6px; border-radius: 999px; background: #eceef1; overflow: hidden; vertical-align: middle; }
|
||||
.io-progress-bar { display: block; height: 100%; background: #1e8e3e; border-radius: inherit; }
|
||||
.io-progress-bar.is-over { background: #d93025; }
|
||||
.io-progress-pct { margin-left: 6px; font-size: 12px; color: var(--color-midtone-gray); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* 요약 숫자 */
|
||||
.io-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px; }
|
||||
.io-kpi-remaining .erp-summary-value { color: #b45309; }
|
||||
.io-kpi-over .erp-summary-value { color: #d93025; }
|
||||
|
||||
/* 발주서 머리 */
|
||||
.io-head { padding: 16px 20px; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px 20px; overflow: visible; }
|
||||
.io-head-title { display: flex; align-items: center; gap: 10px; }
|
||||
.io-head-title h2 { margin: 0; font-size: 18px; font-family: ui-monospace, Consolas, monospace; }
|
||||
.io-head-meta { display: flex; flex-wrap: wrap; gap: 8px 24px; margin: 12px 0 0; }
|
||||
.io-head-meta dt { font-size: 11.5px; color: var(--color-midtone-gray); }
|
||||
.io-head-meta dd { margin: 2px 0 0; font-size: 13.5px; }
|
||||
.io-head-meta .io-wide { flex-basis: 100%; }
|
||||
.io-kpis-head { grid-template-columns: repeat(auto-fit, minmax(96px, 1fr)); align-self: start; min-width: 320px; }
|
||||
.io-head-actions { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding-top: 12px; border-top: 1px solid var(--color-subtle-ash); }
|
||||
.io-head-actions form { display: inline-flex; gap: 6px; align-items: center; margin: 0; }
|
||||
.io-close-reason { width: 220px; }
|
||||
|
||||
/* 입고 입력 */
|
||||
.io-col-no { width: 36px; color: var(--color-midtone-gray); }
|
||||
.io-col-recv { width: 130px; background: #f6fbf7; }
|
||||
.io-table thead th.io-col-recv { background: #eaf6ee; color: #1e7a34; font-weight: 600; }
|
||||
.io-qty { width: 110px; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.io-receipt-bar { display: flex; align-items: flex-end; gap: 10px; flex-wrap: wrap; padding: 14px 20px; border-top: 1px solid var(--color-subtle-ash); background: #fafbfc; }
|
||||
.io-receipt-bar .erp-field input { min-width: 150px; }
|
||||
.io-grow { flex: 1 1 260px; }
|
||||
.io-default-submit { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; }
|
||||
.io-over-box { margin: 12px 20px 0; padding: 12px 16px; border-radius: 8px; background: #fbe9e6; border: 1px solid #efc6bf; color: #7a1d14; font-size: 13px; }
|
||||
.io-over-box ul { margin: 6px 0 10px; padding-left: 18px; }
|
||||
/* [초과 입고로 저장] — 분홍 안내 상자 위에서도 또렷하게: 진한 빨강 바탕 + 흰 글씨(공용 erp-btn-danger 는 연해서 안 보였다) */
|
||||
.io-btn-over { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border: 1px solid #b3261e; border-radius: 8px;
|
||||
background: #c5221f; color: #fff; font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; box-shadow: 0 1px 2px rgba(0, 0, 0, .15); }
|
||||
.io-btn-over:hover { background: #a50e0e; border-color: #8c0b0b; }
|
||||
.io-btn-over:focus-visible { outline: 2px solid #7a1d14; outline-offset: 2px; }
|
||||
.io-chip { display: inline-block; margin: 2px 6px 2px 0; padding: 1px 8px; border-radius: 6px; background: var(--color-ghost-gray); font-size: 12px; white-space: nowrap; }
|
||||
|
||||
/* 발주서 폼 */
|
||||
.io-order-form { overflow: visible; }
|
||||
.io-lines .io-col-qty { width: 130px; }
|
||||
.io-lines .erp-input { width: 100%; }
|
||||
.io-lines .io-col-del { width: 48px; text-align: center; }
|
||||
.io-lines tfoot td { padding: 10px 16px; border-top: 1px solid var(--color-subtle-ash); }
|
||||
.io-item-cell { position: relative; min-width: 320px; }
|
||||
.io-item-search { width: 100%; }
|
||||
.io-item-search.is-invalid { border-color: #d93025; box-shadow: 0 0 0 3px rgba(217, 48, 37, .12); }
|
||||
.io-item-search[readonly] { background: var(--color-ghost-gray); }
|
||||
.io-total { margin-left: 12px; }
|
||||
.io-form-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 14px 20px; border-top: 1px solid var(--color-subtle-ash); }
|
||||
/* 검색 드롭다운 — 표 가로 스크롤 상자에 잘리지 않게 화면 기준(fixed), 위치는 inout.js 가 입력칸에 맞춤 */
|
||||
.io-suggest { position: fixed; z-index: 1000; max-height: 280px; overflow-y: auto;
|
||||
background: #fff; border: 1px solid var(--color-subtle-ash); border-radius: 8px; box-shadow: 0 8px 24px rgba(0, 0, 0, .12); }
|
||||
.io-suggest-item { padding: 7px 12px; font-size: 13px; cursor: pointer; white-space: normal; }
|
||||
.io-suggest-item:hover, .io-suggest-item.is-active { background: #eef6ff; }
|
||||
.io-suggest-empty { padding: 10px 12px; font-size: 12.5px; color: var(--color-midtone-gray); white-space: normal; }
|
||||
|
||||
/* ── 공용 ERP 스타일과 겹치는 부분(2026-10-16 옵션 화면 겹침) ──
|
||||
· .erp-input 은 min-width 240px + content-box 라 좁은 칸에서 옆 칸을 덮는다 → 이 모듈 안에서는 테두리 기준·최소폭 없음
|
||||
· .erp-table-wrap 은 카드 모양(그림자·둥근 모서리)이라 카드 안에 넣으면 상자가 겹쳐 보인다 → 카드 안에서는 평평하게 */
|
||||
.io *, .io *::before, .io *::after, .io-dlg *, .io-dlg *::before, .io-dlg *::after { box-sizing: border-box; }
|
||||
/* hidden 속성은 늘 숨김 — display 를 준 요소(예: 메일 창 아래 줄 flex)가 hidden 을 덮어써 보이던 문제(2026-10-16) */
|
||||
.io [hidden], .io-dlg [hidden], .io-viewer [hidden] { display: none !important; }
|
||||
.io .erp-input { min-width: 0; }
|
||||
.io .erp-card-block .erp-table-wrap { border-radius: 0; box-shadow: none; background: transparent; }
|
||||
|
||||
/* 옵션 톱니(관리자) — 실적 설정 톱니처럼 둥근 아이콘 단추 */
|
||||
.io-gear { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; padding: 0;
|
||||
border: 1px solid var(--color-subtle-ash); border-radius: 50%; background: #fff; color: #525860; cursor: pointer;
|
||||
transition: background .12s, color .12s, border-color .12s; }
|
||||
.io-gear:hover { background: var(--color-ghost-gray); color: var(--color-rich-black); border-color: #c9ccd1; }
|
||||
.io-gear:focus-visible { outline: 2px solid var(--color-rich-black); outline-offset: 2px; }
|
||||
.io-factory-who { display: block; font-size: 12px; color: var(--color-midtone-gray); margin-top: 2px; }
|
||||
|
||||
/* 옵션 팝업 */
|
||||
.io-dlg { width: min(1180px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
|
||||
border-radius: 12px; box-shadow: 0 12px 40px rgba(0, 0, 0, .2); color: var(--color-rich-black); overflow: hidden; }
|
||||
.io-dlg[open] { display: flex; flex-direction: column; }
|
||||
.io-dlg:focus { outline: none; }
|
||||
.io-dlg-tabs button:focus-visible { outline: 2px solid var(--color-rich-black); outline-offset: -4px; border-radius: 6px; }
|
||||
.io-dlg::backdrop { background: rgba(0, 0, 0, .35); }
|
||||
.io-dlg-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 14px 22px; border-bottom: 1px solid var(--color-subtle-ash); }
|
||||
.io-dlg-head h2 { margin: 0; font-size: 17px; font-weight: 600; }
|
||||
.io-dlg-x { display: inline-flex; padding: 6px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; }
|
||||
.io-dlg-x:hover { background: var(--color-ghost-gray); color: var(--color-rich-black); }
|
||||
.io-dlg-msg { margin: 12px 22px 0; padding: 9px 12px; border-radius: 8px; background: #e6f8e9; color: #1e7a34; border: 1px solid #c2efc8; font-size: 13px; }
|
||||
.io-dlg-msg.is-bad { background: #fbe9e6; color: #a1261b; border-color: #efc6bf; }
|
||||
.io-dlg-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; padding: 14px 22px 18px; }
|
||||
.io-dlg-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--color-subtle-ash); margin-bottom: 14px; }
|
||||
.io-dlg-tabs button { padding: 8px 14px; border: 0; border-bottom: 2px solid transparent; margin-bottom: -1px; background: none;
|
||||
font: inherit; font-size: 14px; color: var(--color-midtone-gray); cursor: pointer; }
|
||||
.io-dlg-tabs button:hover { color: var(--color-rich-black); }
|
||||
.io-dlg-tabs button.is-active { color: var(--color-rich-black); font-weight: 600; border-bottom-color: var(--color-rich-black); }
|
||||
.io-dlg-count { display: inline-block; min-width: 18px; padding: 0 5px; margin-left: 4px; border-radius: 999px; background: var(--color-ghost-gray); font-size: 11px; text-align: center; }
|
||||
.io-dlg-body .io-help { padding: 0 0 12px; }
|
||||
.io-dlg-form { margin: 0; }
|
||||
.io-dlg-table { width: 100%; border-collapse: collapse; font-size: 13px; table-layout: fixed; }
|
||||
.io-dlg-table th { text-align: left; font-weight: 500; font-size: 12px; color: var(--color-midtone-gray); padding: 8px 6px; border-bottom: 1px solid var(--color-subtle-ash); white-space: nowrap; }
|
||||
.io-dlg-table td { padding: 7px 6px; border-bottom: 1px solid var(--color-subtle-ash); vertical-align: middle; }
|
||||
.io-dlg-table tbody tr:last-child td { border-bottom: 0; }
|
||||
.io-dlg-table .io-c { text-align: center; }
|
||||
.io-dlg-table td.io-c input[type="checkbox"] { width: 16px; height: 16px; }
|
||||
.io-user { display: block; font-weight: 500; }
|
||||
.io-sub { font-size: 12px; color: var(--color-midtone-gray); }
|
||||
.io-empty { text-align: center; padding: 18px; color: var(--color-midtone-gray); }
|
||||
.io-in { width: 100%; min-width: 0; padding: 6px 9px; border: 1px solid var(--color-subtle-ash); border-radius: 6px; font: inherit; font-size: 13px;
|
||||
color: var(--color-rich-black); background: #fff; }
|
||||
.io-in:focus { outline: none; border-color: var(--color-rich-black); box-shadow: 0 0 0 3px rgba(0, 0, 0, .06); }
|
||||
.io-in-num { text-align: right; }
|
||||
.io-factory-table col.w-name { width: 15%; }
|
||||
.io-factory-table col.w-man { width: 10%; }
|
||||
.io-factory-table col.w-tel { width: 14%; }
|
||||
.io-factory-table col.w-memo { width: auto; }
|
||||
.io-factory-table col.w-sort { width: 64px; }
|
||||
.io-factory-table col.w-use { width: 48px; }
|
||||
.io-factory-table col.w-cnt { width: 52px; }
|
||||
.io-factory-table col.w-btn { width: 128px; }
|
||||
.io-factory-table tr.is-inactive .io-in { background: var(--color-ghost-gray); color: var(--color-midtone-gray); }
|
||||
.io-factory-table .io-new-row td { background: #fafbfc; border-top: 1px solid var(--color-subtle-ash); }
|
||||
.io-btns { text-align: right; white-space: nowrap; } /* td 에 flex 를 주면 표 칸이 깨진다(줄 선·배경 어긋남) */
|
||||
.io-btns .erp-btn + .erp-btn { margin-left: 4px; }
|
||||
.io-dlg-actions { display: flex; justify-content: flex-end; padding-top: 12px; }
|
||||
.io-dlg-foot { margin: 14px 0 0; font-size: 12px; color: var(--color-midtone-gray); }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.io-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.io-head { grid-template-columns: 1fr; }
|
||||
.io-kpis-head { min-width: 0; }
|
||||
.io-dlg-body { overflow-x: auto; }
|
||||
.io-factory-table { min-width: 860px; }
|
||||
}
|
||||
|
||||
/* ── 발주 메일(003) ── */
|
||||
.io-mail-btn { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.io-mail-sent { color: #1e7a34; font-weight: 600; }
|
||||
.io-mail-dlg { width: min(860px, calc(100vw - 40px)); }
|
||||
.io-mail-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 14px; margin-bottom: 12px; }
|
||||
.io-mail-fields label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--color-midtone-gray); }
|
||||
.io-mail-fields input[readonly] { background: var(--color-ghost-gray); color: #3d3f42; }
|
||||
.io-mail-sentlist { margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: #f3fbf5; border: 1px solid #cdeed6; font-size: 12.5px; }
|
||||
.io-mail-sentlist ul { margin: 4px 0 0; padding-left: 18px; }
|
||||
.io-mail-preview { width: 100%; height: 380px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; }
|
||||
.io-mail-connect { padding: 8px 2px 4px; font-size: 13.5px; line-height: 1.7; }
|
||||
.io-mail-connect .erp-btn { margin-top: 6px; }
|
||||
.io-mail-admin { margin-top: 14px; padding: 10px 12px; border-radius: 8px; background: var(--color-ghost-gray); font-size: 12px; color: #3d3f42; }
|
||||
.io-mail-admin code { display: inline-block; margin-top: 4px; padding: 2px 6px; border-radius: 4px; background: #fff; border: 1px solid var(--color-subtle-ash); font-size: 12px; user-select: all; word-break: break-all; }
|
||||
.io-hint { margin: -4px 0 12px; font-size: 12.5px; color: #9a5b00; }
|
||||
.io-dlg-footbar { display: flex; align-items: center; gap: 8px; padding: 12px 22px; border-top: 1px solid var(--color-subtle-ash); background: #fafbfc; }
|
||||
.io-link-btn { border: 0; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--color-midtone-gray); text-decoration: underline; cursor: pointer; }
|
||||
.io-link-btn:hover { color: var(--color-rich-black); }
|
||||
|
||||
/* ── 입고증 사진(003) ── */
|
||||
.io-photo-field { min-width: 180px; }
|
||||
.io-photo-pick { position: relative; display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border: 1px dashed #b7bcc4;
|
||||
border-radius: 8px; background: #fff; color: var(--color-rich-black); font-size: 13px; cursor: pointer; white-space: nowrap; }
|
||||
.io-photo-pick:hover { border-color: var(--color-rich-black); background: var(--color-ghost-gray); }
|
||||
.io-photo-pick:focus-within { outline: 2px solid var(--color-rich-black); outline-offset: 2px; }
|
||||
.io-photo-input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
|
||||
.io-photo-previews { flex-basis: 100%; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.io-photo-previews:empty { display: none; }
|
||||
.io-photo-chip { display: inline-flex; align-items: center; gap: 8px; padding: 4px 6px 4px 4px; border: 1px solid var(--color-subtle-ash);
|
||||
border-radius: 8px; background: #fff; font-size: 12px; color: #3d3f42; max-width: 280px; }
|
||||
.io-photo-chip img { width: 40px; height: 40px; object-fit: cover; border-radius: 6px; background: var(--color-ghost-gray); }
|
||||
.io-photo-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.io-photo-chip button { border: 0; background: none; color: #6d6e6f; cursor: pointer; font-size: 13px; padding: 2px 4px; border-radius: 4px; }
|
||||
.io-photo-chip button:hover { background: var(--color-ghost-gray); color: #c5221f; }
|
||||
.io-photo-lost { margin: 0 0 8px; font-size: 12.5px; color: #7a1d14; font-weight: 600; }
|
||||
.io-photos-cell { white-space: normal !important; min-width: 120px; }
|
||||
.io-photos-cell .io-add-photo-form { display: inline-block; margin: 0; vertical-align: middle; }
|
||||
.io-thumb { position: relative; display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; margin: 2px 4px 2px 0;
|
||||
padding: 0; overflow: hidden; border: 1px solid var(--color-subtle-ash); border-radius: 6px; background: var(--color-ghost-gray); cursor: zoom-in; vertical-align: middle; }
|
||||
.io-thumb img { width: 100%; height: 100%; object-fit: cover; }
|
||||
.io-thumb:hover { border-color: var(--color-rich-black); }
|
||||
.io-thumb-heic { font-size: 10px; font-weight: 700; color: #6d6e6f; }
|
||||
.io-thumb-add { cursor: pointer; border-style: dashed; background: #fff; color: #6d6e6f; font-size: 20px; }
|
||||
.io-thumb-add:hover { color: var(--color-rich-black); }
|
||||
.io-viewer { width: min(1100px, calc(100vw - 40px)); height: min(860px, calc(100vh - 40px)); padding: 0; border: 0; border-radius: 12px;
|
||||
background: #111; color: #fff; overflow: hidden; }
|
||||
.io-viewer[open] { display: flex; align-items: center; justify-content: center; }
|
||||
.io-viewer:focus { outline: none; }
|
||||
.io-viewer::backdrop { background: rgba(0, 0, 0, .7); }
|
||||
.io-viewer-bar { position: absolute; top: 0; left: 0; right: 0; display: flex; align-items: center; gap: 8px; padding: 10px 14px;
|
||||
background: linear-gradient(rgba(0, 0, 0, .6), rgba(0, 0, 0, 0)); z-index: 1; }
|
||||
.io-viewer-bar form { margin: 0; }
|
||||
.io-viewer-title { flex: 1 1 auto; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.io-viewer-btn { padding: 5px 12px; border: 1px solid rgba(255, 255, 255, .35); border-radius: 6px; background: rgba(0, 0, 0, .35); color: #fff;
|
||||
font: inherit; font-size: 12.5px; text-decoration: none; cursor: pointer; }
|
||||
.io-viewer-btn:hover { background: rgba(255, 255, 255, .15); }
|
||||
.io-viewer-img { max-width: 100%; max-height: 100%; object-fit: contain; }
|
||||
.io-viewer-heic { padding: 24px; text-align: center; }
|
||||
.io-viewer-nav { position: absolute; top: 50%; transform: translateY(-50%); width: 44px; height: 64px; border: 0; border-radius: 8px;
|
||||
background: rgba(0, 0, 0, .45); color: #fff; font-size: 30px; cursor: pointer; z-index: 1; }
|
||||
.io-viewer-nav:hover { background: rgba(255, 255, 255, .2); }
|
||||
.io-viewer-nav.is-prev { left: 10px; }
|
||||
.io-viewer-nav.is-next { right: 10px; }
|
||||
.io-factory-table col.w-mail { width: 17%; }
|
||||
@media (max-width: 900px) {
|
||||
.io-mail-fields { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* ── 상품 정보 탭(004) — 단가·무게(PP)·은 함유량 ── */
|
||||
.io-prod-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||
.io-prod-search { width: 220px; }
|
||||
.io-prod-scroll { max-height: min(440px, calc(100vh - 340px)); overflow-y: auto; border: 1px solid var(--color-subtle-ash); border-radius: 8px; }
|
||||
.io-prod-table thead th { position: sticky; top: 0; z-index: 1; background: #fafbfc; }
|
||||
.io-prod-table col.w-code { width: 128px; }
|
||||
.io-prod-table col.w-num { width: 120px; }
|
||||
.io-prod-table col.w-ag { width: 92px; }
|
||||
.io-prod-table col.w-del { width: 44px; }
|
||||
.io-prod-table th.io-r, .io-r { text-align: right; }
|
||||
.io-prod-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.io-ag { color: var(--color-midtone-gray); font-variant-numeric: tabular-nums; }
|
||||
.io-prod-table tr.is-dirty td { background: #fff8e1; }
|
||||
.io-icon-btn { width: 26px; height: 26px; padding: 0; border: 0; border-radius: 6px; background: none; color: #8a8b8c; font-size: 13px; cursor: pointer; }
|
||||
.io-icon-btn:hover { background: #fbe9e6; color: #a1261b; }
|
||||
.io-excluded { margin-top: 12px; font-size: 13px; }
|
||||
.io-excluded summary { cursor: pointer; color: var(--color-midtone-gray); }
|
||||
.io-excluded ul { margin: 8px 0 0; padding: 0; list-style: none; }
|
||||
.io-excluded li { display: flex; align-items: center; gap: 8px; padding: 5px 0; border-bottom: 1px solid var(--color-subtle-ash); }
|
||||
.io-excluded li .io-link-btn { margin-left: auto; }
|
||||
/* 발주서 단가·금액 칸 */
|
||||
.io-col-money { width: 110px; text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.io-col-spec { width: 96px; white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.io-table tfoot .io-total-row td { padding: 10px var(--sp-16, 16px); vertical-align: middle; background: #fafbfc; font-weight: 500; border-top: 1px solid var(--color-subtle-ash); }
|
||||
.io-suggest-price { float: right; margin-left: 12px; color: var(--color-midtone-gray); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.io-table th.io-col-money, .io-table th.io-col-spec { text-align: right; }
|
||||
/* 전체 입고 완료(모든 품목 입고완료·초과입고) — 2026-10-17 */
|
||||
.io-st-all { gap: 3px; }
|
||||
.io-badge-note { margin-left: 4px; font-size: 11px; font-weight: 600; color: #b3261e; white-space: nowrap; }
|
||||
.io-status-cell { white-space: nowrap; }
|
||||
/* 발주 삭제(수퍼관리자, 2026-10-17) */
|
||||
.io-table .io-col-trash { width: 44px; padding-left: 0; padding-right: 8px; text-align: center; }
|
||||
.io-table .io-col-trash form { margin: 0; display: inline-flex; }
|
||||
.io-del-btn { display: inline-flex; align-items: center; justify-content: center; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
@@ -0,0 +1,645 @@
|
||||
/* 입출고 관리(inout) 화면 스크립트 — 화면 전환·저장은 서버(폼)가 하고, 여기는 입력을 돕기만 한다.
|
||||
· 목록 줄 누르기 = 발주서로
|
||||
· 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운
|
||||
· 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계
|
||||
· 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리
|
||||
· 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게)
|
||||
· 발주 메일: 미리보기 팝업 → [메일 발송](발주 담당 본인 Gmail), 처음엔 [Gmail 연결]
|
||||
· data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function confirmMsg(msg) {
|
||||
return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg));
|
||||
}
|
||||
function alertMsg(msg) {
|
||||
return window.erpAlert ? window.erpAlert(msg) : Promise.resolve(window.alert(msg));
|
||||
}
|
||||
function num(v) {
|
||||
const n = parseInt(String(v || "").replace(/[,\s]/g, ""), 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
function fmt(n) { return n.toLocaleString("ko-KR"); }
|
||||
|
||||
// ── 목록 줄 누르기 → 발주서 ──
|
||||
document.addEventListener("click", function (e) {
|
||||
const row = e.target.closest(".io-row-link");
|
||||
if (!row || e.target.closest("a, button, input, select, label")) return;
|
||||
if (window.getSelection && String(window.getSelection())) return; // 글자 고르는 중
|
||||
location.href = row.dataset.href;
|
||||
});
|
||||
|
||||
// ── 버튼별 확인 ──
|
||||
document.addEventListener("click", function (e) {
|
||||
const btn = e.target.closest("[data-erp-confirm-btn]");
|
||||
if (!btn || btn.dataset.confirmed === "1") return;
|
||||
e.preventDefault();
|
||||
confirmMsg(btn.dataset.erpConfirmBtn).then(function (ok) {
|
||||
if (!ok) return;
|
||||
btn.dataset.confirmed = "1";
|
||||
if (btn.form.requestSubmit) btn.form.requestSubmit(btn); else btn.click();
|
||||
});
|
||||
});
|
||||
|
||||
// ── 발주서 폼 ──
|
||||
const form = document.getElementById("io-order-form");
|
||||
if (form) initOrderForm(form);
|
||||
|
||||
function initOrderForm(form) {
|
||||
const body = form.querySelector("#io-lines tbody");
|
||||
const tpl = document.getElementById("io-line-tpl");
|
||||
const totalQty = document.getElementById("io-total-qty");
|
||||
const totalLines = document.getElementById("io-total-lines");
|
||||
|
||||
const totalAmount = document.getElementById("io-total-amount"), noPrice = document.getElementById("io-total-noprice");
|
||||
function renumber() {
|
||||
let q = 0, k = 0, amount = 0, missing = 0;
|
||||
body.querySelectorAll(".io-line").forEach(function (tr, i) {
|
||||
tr.querySelector(".io-col-no").textContent = String(i + 1);
|
||||
const n = num(tr.querySelector(".io-qty").value);
|
||||
const has = !!tr.querySelector('input[name="item_code"]').value;
|
||||
const price = tr.dataset.price === "" || tr.dataset.price === undefined ? null : parseFloat(tr.dataset.price);
|
||||
const cell = tr.querySelector(".io-amount");
|
||||
// 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로
|
||||
if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-";
|
||||
if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; }
|
||||
});
|
||||
totalQty.textContent = fmt(q);
|
||||
totalLines.textContent = fmt(k);
|
||||
if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR");
|
||||
if (noPrice) noPrice.textContent = missing ? " (단가 없는 " + missing + "종 제외)" : "";
|
||||
}
|
||||
function addLine(focus) {
|
||||
const tr = tpl.content.firstElementChild.cloneNode(true);
|
||||
body.appendChild(tr);
|
||||
wireSearch(tr.querySelector(".io-item-search"));
|
||||
renumber();
|
||||
if (focus) tr.querySelector(".io-item-search").focus();
|
||||
return tr;
|
||||
}
|
||||
form.querySelector("#io-add-line").addEventListener("click", function () { addLine(true); });
|
||||
body.addEventListener("click", function (e) {
|
||||
const del = e.target.closest(".io-del");
|
||||
if (!del) return;
|
||||
const tr = del.closest(".io-line");
|
||||
const search = tr.querySelector(".io-item-search");
|
||||
if (search && search._ioBox) search._ioBox.remove(); // body 에 붙은 드롭다운도 함께
|
||||
tr.remove();
|
||||
if (!body.querySelector(".io-line")) addLine(false);
|
||||
renumber();
|
||||
});
|
||||
body.addEventListener("input", renumber); // 수량을 바꾸거나 제품 글을 고치면(고른 것 풀림) 다시 셈
|
||||
body.addEventListener("io-chosen", renumber); // 검색 목록에서 제품을 고르면
|
||||
body.querySelectorAll(".io-item-search").forEach(wireSearch);
|
||||
if (!body.querySelector(".io-line")) { addLine(false); addLine(false); addLine(false); }
|
||||
renumber();
|
||||
|
||||
form.addEventListener("submit", function (e) {
|
||||
// 검색 글만 있고 목록에서 고르지 않은 줄, 같은 제품 두 줄 — 서버도 막지만 여기서 먼저 알려 준다
|
||||
const codes = [];
|
||||
let bad = null;
|
||||
body.querySelectorAll(".io-line").forEach(function (tr) {
|
||||
const code = tr.querySelector('input[name="item_code"]').value;
|
||||
const text = tr.querySelector(".io-item-search").value.trim();
|
||||
if (!code && text && !bad) bad = { tr: tr, msg: "'" + text + "' — 검색 목록에서 제품을 골라 주세요." };
|
||||
if (code && codes.indexOf(code) >= 0 && !bad) bad = { tr: tr, msg: code + " — 같은 제품이 두 줄에 있습니다. 한 줄로 합쳐 주세요." };
|
||||
if (code) codes.push(code);
|
||||
});
|
||||
if (bad) {
|
||||
e.preventDefault();
|
||||
bad.tr.querySelector(".io-item-search").classList.add("is-invalid");
|
||||
alertMsg(bad.msg).then(function () { bad.tr.querySelector(".io-item-search").focus(); });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 코드표 단품 검색 드롭다운 — 고르면 숨은 칸(코드·이름)을 채우고 수량 칸으로. 글을 다시 고치면 고른 것을 지운다.
|
||||
function wireSearch(input) {
|
||||
if (!input || input.readOnly || input.dataset.wired) return;
|
||||
input.dataset.wired = "1";
|
||||
const cell = input.closest(".io-item-cell");
|
||||
const codeEl = cell.querySelector('input[name="item_code"]');
|
||||
const nameEl = cell.querySelector('input[name="item_name"]');
|
||||
const box = document.createElement("div");
|
||||
box.className = "io-suggest";
|
||||
box.setAttribute("role", "listbox");
|
||||
box.hidden = true;
|
||||
document.body.appendChild(box); // 표 가로 스크롤 상자 밖(fixed) — 아래 줄에서도 잘리지 않게
|
||||
input._ioBox = box;
|
||||
let timer = 0, seq = 0, items = [], active = -1;
|
||||
|
||||
function place() {
|
||||
const r = input.getBoundingClientRect();
|
||||
const below = window.innerHeight - r.bottom;
|
||||
box.style.left = r.left + "px";
|
||||
box.style.width = Math.max(r.width, 320) + "px";
|
||||
if (below < 200 && r.top > below) { box.style.top = ""; box.style.bottom = (window.innerHeight - r.top + 2) + "px"; }
|
||||
else { box.style.bottom = ""; box.style.top = (r.bottom + 2) + "px"; }
|
||||
}
|
||||
window.addEventListener("resize", function () { if (!box.hidden) place(); });
|
||||
document.addEventListener("scroll", function () { if (!box.hidden) place(); }, true);
|
||||
function close() { box.hidden = true; active = -1; input.setAttribute("aria-expanded", "false"); }
|
||||
function paint() {
|
||||
box.innerHTML = "";
|
||||
if (!items.length) {
|
||||
const empty = document.createElement("div");
|
||||
empty.className = "io-suggest-empty";
|
||||
empty.textContent = box.dataset.message || "맞는 단품이 없습니다.";
|
||||
box.appendChild(empty);
|
||||
}
|
||||
items.forEach(function (it, i) {
|
||||
const opt = document.createElement("div");
|
||||
opt.className = "io-suggest-item" + (i === active ? " is-active" : "");
|
||||
opt.setAttribute("role", "option");
|
||||
const c = document.createElement("span");
|
||||
c.className = "io-code";
|
||||
c.textContent = it.code;
|
||||
opt.appendChild(c);
|
||||
opt.appendChild(document.createTextNode(" " + it.name));
|
||||
if (it.unit_price) {
|
||||
const pr = document.createElement("span");
|
||||
pr.className = "io-suggest-price";
|
||||
pr.textContent = it.unit_price + "원";
|
||||
opt.insertBefore(pr, c); // float:right 는 글자보다 앞에 둬야 같은 줄 오른쪽
|
||||
}
|
||||
opt.addEventListener("mousedown", function (e) { e.preventDefault(); choose(i); });
|
||||
box.appendChild(opt);
|
||||
});
|
||||
box.hidden = false;
|
||||
place();
|
||||
input.setAttribute("aria-expanded", "true");
|
||||
}
|
||||
function choose(i) {
|
||||
const it = items[i];
|
||||
if (!it) return;
|
||||
codeEl.value = it.code;
|
||||
const row = input.closest("tr");
|
||||
if (row) { // 단가(상품 정보) — 금액 계산용
|
||||
row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price);
|
||||
const pc = row.querySelector(".io-price");
|
||||
if (pc) pc.textContent = it.unit_price || "-";
|
||||
}
|
||||
nameEl.value = it.name;
|
||||
input.value = it.code + " · " + it.name;
|
||||
input.classList.remove("is-invalid");
|
||||
close();
|
||||
const qty = input.closest("tr").querySelector(".io-qty");
|
||||
if (qty) qty.focus();
|
||||
input.dispatchEvent(new Event("io-chosen", { bubbles: true }));
|
||||
}
|
||||
async function search(q) {
|
||||
const my = ++seq;
|
||||
try {
|
||||
const res = await fetch("/inout/api/items?q=" + encodeURIComponent(q), { headers: { Accept: "application/json" } });
|
||||
const data = await res.json();
|
||||
if (my !== seq) return;
|
||||
items = data.items || [];
|
||||
box.dataset.message = data.enabled === false ? (data.message || "코드표가 연결되지 않았습니다.") : "";
|
||||
active = items.length ? 0 : -1;
|
||||
paint();
|
||||
} catch (_) {
|
||||
if (my !== seq) return;
|
||||
items = [];
|
||||
box.dataset.message = "검색하지 못했습니다. 잠시 뒤 다시 입력하세요.";
|
||||
paint();
|
||||
}
|
||||
}
|
||||
input.setAttribute("aria-autocomplete", "list");
|
||||
input.addEventListener("input", function () {
|
||||
codeEl.value = ""; // 글을 고치면 고른 제품은 풀린다(다시 골라야 저장)
|
||||
const row0 = input.closest("tr");
|
||||
if (row0 && row0.dataset.price !== undefined) { row0.dataset.price = ""; const pc0 = row0.querySelector(".io-price"); if (pc0) pc0.textContent = "-"; }
|
||||
nameEl.value = "";
|
||||
clearTimeout(timer);
|
||||
const q = input.value.trim();
|
||||
if (!q) { close(); return; }
|
||||
timer = setTimeout(function () { search(q); }, 200);
|
||||
});
|
||||
input.addEventListener("keydown", function (e) {
|
||||
if (box.hidden) return;
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (!items.length) return;
|
||||
active = (active + (e.key === "ArrowDown" ? 1 : items.length - 1)) % items.length;
|
||||
paint();
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault(); // 고르기만 — 폼 저장 아님
|
||||
choose(active < 0 ? 0 : active);
|
||||
} else if (e.key === "Escape") {
|
||||
close();
|
||||
}
|
||||
});
|
||||
input.addEventListener("blur", function () { setTimeout(close, 120); });
|
||||
}
|
||||
|
||||
// ── 발주서 화면: 입고 입력 ──
|
||||
const recvForm = document.getElementById("io-receipt-form");
|
||||
if (recvForm) {
|
||||
const total = document.getElementById("io-recv-total");
|
||||
const inputs = Array.from(recvForm.querySelectorAll(".io-recv"));
|
||||
const paintTotal = function () {
|
||||
const t = inputs.reduce(function (s, i) { return s + num(i.value); }, 0);
|
||||
if (total) total.textContent = t ? "(" + fmt(t) + "개)" : "";
|
||||
};
|
||||
recvForm.addEventListener("input", paintTotal);
|
||||
const fill = document.getElementById("io-fill-remaining");
|
||||
if (fill) fill.addEventListener("click", function () {
|
||||
inputs.forEach(function (i) { if (!i.value.trim() && num(i.dataset.remaining)) i.value = i.dataset.remaining; });
|
||||
paintTotal();
|
||||
});
|
||||
paintTotal();
|
||||
}
|
||||
|
||||
// ── 옵션 팝업(톱니, 관리자) — 내용은 GET /inout/settings?panel=1, 저장은 제자리(X-Inout-Options: 1 → JSON) ──
|
||||
const optBtn = document.getElementById("io-options-btn");
|
||||
const optDlg = document.getElementById("io-options");
|
||||
if (optBtn && optDlg) initOptions(optBtn, optDlg);
|
||||
|
||||
function initOptions(btn, dlg) {
|
||||
const body = dlg.querySelector("#io-options-body");
|
||||
const msgEl = dlg.querySelector(".io-dlg-msg");
|
||||
let changed = false, pane = "roles";
|
||||
|
||||
function say(text, bad) {
|
||||
msgEl.textContent = text || "";
|
||||
msgEl.hidden = !text;
|
||||
msgEl.classList.toggle("is-bad", !!bad);
|
||||
}
|
||||
function showPane(name) {
|
||||
pane = name;
|
||||
body.querySelectorAll(".io-dlg-tabs [data-pane]").forEach(function (t) {
|
||||
const on = t.dataset.pane === name;
|
||||
t.classList.toggle("is-active", on);
|
||||
t.setAttribute("aria-selected", on ? "true" : "false");
|
||||
t.tabIndex = on ? 0 : -1;
|
||||
});
|
||||
body.querySelectorAll(".io-dlg-pane").forEach(function (p) { p.hidden = p.dataset.pane !== name; });
|
||||
}
|
||||
async function load() {
|
||||
const res = await fetch("/inout/settings?panel=1", { headers: { "X-Inout-Options": "1" } });
|
||||
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||
body.innerHTML = await res.text();
|
||||
showPane(pane);
|
||||
}
|
||||
async function open() {
|
||||
say("");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
try {
|
||||
await load();
|
||||
dlg.focus({ preventScroll: true }); // 닫기(✕)에 초점 테두리가 생기지 않게 창 자체에(Tab 으로 안으로 이동)
|
||||
} catch (_) {
|
||||
body.innerHTML = '<p class="io-error">옵션을 불러오지 못했습니다. 잠시 뒤 다시 여세요.</p>';
|
||||
}
|
||||
}
|
||||
btn.addEventListener("click", open);
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]")) { dlg.close(); return; }
|
||||
const tab = e.target.closest(".io-dlg-tabs [data-pane]");
|
||||
if (tab) showPane(tab.dataset.pane);
|
||||
});
|
||||
dlg.addEventListener("close", function () {
|
||||
const url = new URL(location.href);
|
||||
const hadParam = url.searchParams.has("options");
|
||||
url.searchParams.delete("options");
|
||||
url.searchParams.delete("msg");
|
||||
if (changed) location.href = url.toString(); // 담당 표시·공장 목록이 바뀌었을 수 있다
|
||||
else if (hadParam) history.replaceState(null, "", url.toString());
|
||||
});
|
||||
dlg.addEventListener("submit", async function (e) {
|
||||
const form = e.target;
|
||||
if (!form.classList || !form.classList.contains("io-dlg-form")) return;
|
||||
e.preventDefault();
|
||||
const sub = e.submitter;
|
||||
if (sub && sub.dataset.confirm && !(await confirmMsg(sub.dataset.confirm))) return;
|
||||
const action = sub && sub.getAttribute("formaction") ? sub.getAttribute("formaction") : form.getAttribute("action");
|
||||
const buttons = Array.from(dlg.querySelectorAll("button[type=submit]"));
|
||||
buttons.forEach(function (b) { b.disabled = true; });
|
||||
try {
|
||||
const res = await fetch(action, { method: "POST", headers: { "X-Inout-Options": "1" },
|
||||
body: new URLSearchParams(new FormData(form)) });
|
||||
let data = {};
|
||||
try { data = await res.json(); } catch (_) {}
|
||||
if (!res.ok || data.ok === false) { say(data.message || data.detail || "저장하지 못했습니다.", true); return; }
|
||||
changed = true;
|
||||
await load();
|
||||
say(data.message || "저장했습니다.");
|
||||
} catch (_) {
|
||||
say("저장하지 못했습니다(연결 오류). 다시 눌러 주세요.", true);
|
||||
} finally {
|
||||
buttons.forEach(function (b) { if (b.isConnected) b.disabled = false; });
|
||||
}
|
||||
});
|
||||
// ── 상품 정보 탭(004) — 단가·무게·은 함유량, 바뀐 줄만 [변경 저장], 불러오기·지우기·되살리기 ──
|
||||
function dirtyRows() {
|
||||
return Array.from(body.querySelectorAll(".io-prod-table tbody tr")).filter(function (tr) {
|
||||
return Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); });
|
||||
});
|
||||
}
|
||||
function paintDirty() {
|
||||
const n = dirtyRows().length;
|
||||
const save = body.querySelector("#io-prod-save"), badge = body.querySelector("#io-prod-dirty");
|
||||
if (save) save.disabled = !n;
|
||||
if (badge) badge.textContent = n ? "(" + n + ")" : "";
|
||||
}
|
||||
function dec(v) { const n = parseFloat(String(v || "").replace(/[,%\s]/g, "")); return Number.isFinite(n) ? n : null; }
|
||||
async function postJSON(url, payload) {
|
||||
const res = await fetch(url, { method: "POST", headers: { "X-Inout-Options": "1", "Content-Type": "application/json" },
|
||||
body: payload === undefined ? "{}" : JSON.stringify(payload) });
|
||||
let out = {};
|
||||
try { out = await res.json(); } catch (_) {}
|
||||
return { ok: res.ok && out.ok !== false, message: out.message || out.detail || (res.ok ? "" : "HTTP " + res.status) };
|
||||
}
|
||||
async function act(url, payload) {
|
||||
const r = await postJSON(url, payload);
|
||||
if (r.ok) { changed = true; await load(); }
|
||||
say(r.message || (r.ok ? "저장했습니다." : "저장하지 못했습니다."), !r.ok);
|
||||
return r.ok;
|
||||
}
|
||||
body.addEventListener("input", function (e) {
|
||||
const inp = e.target;
|
||||
if (inp.id === "io-prod-search") {
|
||||
const q = inp.value.trim().toLowerCase();
|
||||
let shown = 0;
|
||||
body.querySelectorAll(".io-prod-table tbody tr").forEach(function (tr) {
|
||||
const hit = !q || tr.dataset.search.indexOf(q) >= 0;
|
||||
tr.hidden = !hit;
|
||||
if (hit) shown++;
|
||||
});
|
||||
const cnt = body.querySelector("#io-prod-count");
|
||||
if (cnt) cnt.dataset.base = cnt.dataset.base || cnt.textContent;
|
||||
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
|
||||
return;
|
||||
}
|
||||
if (!inp.dataset || !inp.dataset.key) return;
|
||||
const tr = inp.closest("tr");
|
||||
const w = dec(tr.querySelector('[data-key="weight_g"]').value), pct = dec(tr.querySelector('[data-key="silver_pct"]').value);
|
||||
const ag = tr.querySelector(".io-ag");
|
||||
if (ag) ag.textContent = w !== null && pct !== null ? (Math.round(w * pct / 100 * 10000) / 10000).toLocaleString("ko-KR", { maximumFractionDigits: 4 }) : "-";
|
||||
tr.classList.toggle("is-dirty", Array.from(tr.querySelectorAll("input[data-key]")).some(function (i) { return i.value.trim() !== i.defaultValue.trim(); }));
|
||||
paintDirty();
|
||||
});
|
||||
body.addEventListener("click", async function (e) {
|
||||
const t = e.target;
|
||||
if (t.id === "io-prod-import") {
|
||||
if (dirtyRows().length && !(await confirmMsg("저장 안 한 변경이 있습니다. 버리고 불러올까요?"))) return;
|
||||
t.disabled = true;
|
||||
say("코드표에서 단품을 불러오는 중…");
|
||||
try { await act("/inout/settings/products/import"); } finally { t.disabled = false; }
|
||||
} else if (t.closest("#io-prod-save")) {
|
||||
const rows = dirtyRows().map(function (tr) {
|
||||
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
|
||||
return { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
});
|
||||
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
|
||||
} else if (t.dataset && t.dataset.exclude) {
|
||||
if (await confirmMsg(t.dataset.exclude + " 를 상품 정보에서 지울까요? 다음 불러오기에서도 빠집니다(지난 발주서는 그대로)."))
|
||||
await act("/inout/settings/products/" + encodeURIComponent(t.dataset.exclude) + "/exclude");
|
||||
} else if (t.dataset && t.dataset.restore) {
|
||||
await act("/inout/settings/products/" + encodeURIComponent(t.dataset.restore) + "/restore");
|
||||
}
|
||||
});
|
||||
// 저장 안 한 상품 정보가 있으면 닫기 전에 묻는다(✕·취소·Esc)
|
||||
dlg.addEventListener("cancel", function (e) {
|
||||
if (dirtyRows().length) { e.preventDefault(); confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); }); }
|
||||
});
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]") && dirtyRows().length) {
|
||||
e.stopImmediatePropagation();
|
||||
confirmMsg("저장 안 한 상품 정보 변경이 있습니다. 닫을까요?").then(function (ok) { if (ok) dlg.close(); });
|
||||
}
|
||||
}, true);
|
||||
if (btn.dataset.open === "1") open();
|
||||
}
|
||||
|
||||
// ── 입고증 사진(003) — 브라우저에서 줄여(긴 변 2000px JPEG) 올린다. 못 줄이는 형식(HEIC 등)은 원본 그대로 ──
|
||||
const PHOTO_MAX_SIDE = 2000;
|
||||
async function shrinkPhoto(file) {
|
||||
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) return file; // GIF(움직임)·HEIC 등은 그대로
|
||||
try {
|
||||
const bmp = await createImageBitmap(file);
|
||||
const scale = Math.min(1, PHOTO_MAX_SIDE / Math.max(bmp.width, bmp.height));
|
||||
if (scale === 1 && file.size < 1.5 * 1024 * 1024) { bmp.close && bmp.close(); return file; }
|
||||
const cv = document.createElement("canvas");
|
||||
cv.width = Math.round(bmp.width * scale);
|
||||
cv.height = Math.round(bmp.height * scale);
|
||||
cv.getContext("2d").drawImage(bmp, 0, 0, cv.width, cv.height);
|
||||
bmp.close && bmp.close();
|
||||
const blob = await new Promise(function (r) { cv.toBlob(r, "image/jpeg", 0.85); });
|
||||
if (!blob || blob.size >= file.size) return file;
|
||||
return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".jpg", { type: "image/jpeg", lastModified: file.lastModified });
|
||||
} catch (_) { return file; }
|
||||
}
|
||||
async function prepare(input) {
|
||||
const max = parseInt(input.dataset.max || "10", 10);
|
||||
let files = Array.from(input._ioFiles || []).concat(Array.from(input.files || []));
|
||||
if (files.length > max) {
|
||||
alertMsg("입고증 사진은 " + max + "장까지 올릴 수 있습니다 — 앞의 " + max + "장만 넣습니다.");
|
||||
files = files.slice(0, max);
|
||||
}
|
||||
input.disabled = true;
|
||||
const done = [];
|
||||
for (const f of files) done.push(f._ioShrunk ? f : Object.assign(await shrinkPhoto(f), { _ioShrunk: true }));
|
||||
input.disabled = false;
|
||||
setFiles(input, done);
|
||||
return done;
|
||||
}
|
||||
function setFiles(input, files) {
|
||||
input._ioFiles = files;
|
||||
try {
|
||||
const dt = new DataTransfer();
|
||||
files.forEach(function (f) { dt.items.add(f); });
|
||||
input.files = dt.files;
|
||||
} catch (_) { /* 아주 옛 브라우저 — 고른 원본 그대로 올라간다 */ }
|
||||
}
|
||||
function paintPreviews(input, box) {
|
||||
box.innerHTML = "";
|
||||
(input._ioFiles || []).forEach(function (f, i) {
|
||||
const chip = document.createElement("span");
|
||||
chip.className = "io-photo-chip";
|
||||
const img = document.createElement("img");
|
||||
img.alt = "";
|
||||
if (/^image\/(jpeg|png|webp|gif)$/i.test(f.type)) img.src = URL.createObjectURL(f);
|
||||
chip.appendChild(img);
|
||||
const meta = document.createElement("span");
|
||||
meta.textContent = f.name + " · " + Math.max(1, Math.round(f.size / 1024)) + "KB";
|
||||
chip.appendChild(meta);
|
||||
const x = document.createElement("button");
|
||||
x.type = "button";
|
||||
x.textContent = "✕";
|
||||
x.setAttribute("aria-label", f.name + " 빼기");
|
||||
x.addEventListener("click", function () {
|
||||
const left = input._ioFiles.filter(function (_f, k) { return k !== i; });
|
||||
input.value = "";
|
||||
setFiles(input, left);
|
||||
paintPreviews(input, box);
|
||||
});
|
||||
chip.appendChild(x);
|
||||
box.appendChild(chip);
|
||||
});
|
||||
}
|
||||
document.addEventListener("change", async function (e) {
|
||||
const input = e.target;
|
||||
if (!input.classList || !input.classList.contains("io-photo-input")) return;
|
||||
if (input.classList.contains("io-photo-auto")) { // 입고 기록 [+] — 고르면 바로 올림
|
||||
input._ioFiles = [];
|
||||
const files = await prepare(input);
|
||||
if (files.length) input.form.submit();
|
||||
return;
|
||||
}
|
||||
const fresh = Array.from(input.files || []);
|
||||
input._ioFiles = (input._ioFiles || []).filter(function () { return true; });
|
||||
input.value = "";
|
||||
try { const dt = new DataTransfer(); fresh.forEach(function (f) { dt.items.add(f); }); input.files = dt.files; } catch (_) {}
|
||||
await prepare(input);
|
||||
const box = document.getElementById("io-photo-previews");
|
||||
if (box) paintPreviews(input, box);
|
||||
});
|
||||
|
||||
// ── 입고 저장 전 초과 확인(브라우저) — 서버까지 갔다 오면 고른 사진이 사라지므로 여기서 먼저 묻는다 ──
|
||||
const recvForm2 = document.getElementById("io-receipt-form");
|
||||
if (recvForm2) recvForm2.addEventListener("submit", function (e) {
|
||||
const flag = document.getElementById("io-confirm-over");
|
||||
if (!flag || flag.value === "1" || (e.submitter && e.submitter.name === "confirm_over")) return;
|
||||
const overs = Array.from(recvForm2.querySelectorAll(".io-recv")).map(function (i) {
|
||||
const after = num(i.dataset.received) + num(i.value);
|
||||
return { code: i.dataset.code, name: i.dataset.name, ordered: num(i.dataset.ordered), after: after, add: num(i.value) };
|
||||
}).filter(function (x) { return x.add && x.after > x.ordered; });
|
||||
if (!overs.length) return;
|
||||
e.preventDefault();
|
||||
const lines = overs.map(function (x) { return x.code + " " + x.name + " — 발주 " + fmt(x.ordered) + "개, 입고 후 " + fmt(x.after) + "개(+" + fmt(x.after - x.ordered) + ")"; });
|
||||
confirmMsg("발주보다 많이 입고하려고 합니다.\n\n" + lines.join("\n") + "\n\n초과 입고로 저장할까요?").then(function (ok) {
|
||||
if (!ok) return;
|
||||
flag.value = "1";
|
||||
if (recvForm2.requestSubmit) recvForm2.requestSubmit(); else recvForm2.submit();
|
||||
});
|
||||
});
|
||||
|
||||
// ── 입고증 사진 크게 보기 ──
|
||||
const viewer = document.getElementById("io-viewer");
|
||||
if (viewer) {
|
||||
const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic");
|
||||
const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open");
|
||||
const del = document.getElementById("io-viewer-del");
|
||||
let list = [], at = 0;
|
||||
function show(i) {
|
||||
at = (i + list.length) % list.length;
|
||||
const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic";
|
||||
img.hidden = isHeic;
|
||||
heic.hidden = !isHeic;
|
||||
if (!isHeic) img.src = "/inout/photos/" + id;
|
||||
openA.href = "/inout/photos/" + id;
|
||||
title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")";
|
||||
if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete";
|
||||
viewer.querySelectorAll(".io-viewer-nav").forEach(function (n) { n.hidden = list.length < 2; });
|
||||
}
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest(".io-thumb[data-photo]");
|
||||
if (!b) return;
|
||||
list = Array.from(document.querySelectorAll('.io-thumb[data-receipt="' + b.dataset.receipt + '"][data-photo]'));
|
||||
show(list.indexOf(b));
|
||||
viewer.showModal();
|
||||
viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음)
|
||||
});
|
||||
viewer.addEventListener("click", function (e) {
|
||||
if (e.target === viewer || e.target.closest("[data-close]")) viewer.close();
|
||||
const step = e.target.closest("[data-step]");
|
||||
if (step) show(at + parseInt(step.dataset.step, 10));
|
||||
});
|
||||
viewer.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowLeft") show(at - 1);
|
||||
if (e.key === "ArrowRight") show(at + 1);
|
||||
});
|
||||
}
|
||||
|
||||
// ── 발주 메일(003) — 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ──
|
||||
const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail");
|
||||
if (mailBtn && mailDlg) initMail(mailBtn, mailDlg);
|
||||
|
||||
function initMail(btn, dlg) {
|
||||
const body = document.getElementById("io-mail-body"), foot = document.getElementById("io-mail-foot");
|
||||
const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = document.getElementById("io-mail-send");
|
||||
const base = "/inout/orders/" + btn.dataset.order + "/mail";
|
||||
let data = null, sent = false;
|
||||
function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); }
|
||||
function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }
|
||||
async function load() {
|
||||
const res = await fetch(base, { headers: { Accept: "application/json" } });
|
||||
data = await res.json();
|
||||
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
|
||||
if (!data.connected) {
|
||||
foot.hidden = true;
|
||||
body.innerHTML = '<div class="io-mail-connect">' +
|
||||
"<p><b>발주 메일은 내 Gmail(" + esc(data.from) + ")로 보냅니다.</b> 처음 한 번만 Gmail 연결이 필요합니다.</p>" +
|
||||
"<p class=\"erp-muted\">구글 화면에서 <b>같은 계정</b>을 고르고 '메일 보내기' 권한을 허락하세요. 보내기 권한만 받으며, 메일함은 읽지 않습니다.</p>" +
|
||||
(data.configured ? "" : '<p class="io-error">서버 설정(APP_ENCRYPTION_KEY·구글 OAuth)이 없어 연결할 수 없습니다 — 관리자에게 알려 주세요.</p>') +
|
||||
'<a class="erp-btn erp-btn-primary" href="' + esc(data.connect_url) + '">Gmail 연결</a>' +
|
||||
// 구글이 redirect_uri_mismatch 로 막으면 ERP 로 돌아오지 않는다 — 등록할 주소를 미리 보여 준다
|
||||
'<div class="io-mail-admin">구글 화면에 <b>400 오류: redirect_uri_mismatch</b> 가 나오면, 관리자가 구글 클라우드 → API 및 서비스 → 사용자 인증 정보 → ' +
|
||||
'로그인용 OAuth 클라이언트 → <b>승인된 리디렉션 URI</b>에 아래 주소를 추가해야 합니다(Gmail API 사용·gmail.send 범위도 함께).<br>' +
|
||||
'<code>' + esc(data.callback_url) + '</code></div></div>';
|
||||
return;
|
||||
}
|
||||
foot.hidden = false;
|
||||
const sentList = (data.sent || []).map(function (m) { return "<li>" + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "</li>"; }).join("");
|
||||
body.innerHTML =
|
||||
'<div class="io-mail-fields">' +
|
||||
"<label><span>보내는 사람</span><input class=\"io-in\" value=\"" + esc(data.from) + "\" readonly /></label>" +
|
||||
"<label><span>받는 사람 *</span><input class=\"io-in\" id=\"io-mail-to\" value=\"" + esc(data.to) + "\" placeholder=\"공장 이메일 — 옵션에서 넣어 두면 자동\" /></label>" +
|
||||
"<label><span>참조</span><input class=\"io-in\" id=\"io-mail-cc\" placeholder=\"여러 개는 쉼표로\" /></label>" +
|
||||
"<label><span>제목</span><input class=\"io-in\" value=\"" + esc(data.subject) + "\" readonly /></label></div>" +
|
||||
(data.to ? "" : '<p class="io-hint">' + esc(data.factory) + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.</p>") +
|
||||
(sentList ? '<div class="io-mail-sentlist"><b>보낸 기록</b><ul>' + sentList + "</ul></div>" : "") +
|
||||
'<iframe class="io-mail-preview" sandbox title="메일 본문 미리보기"></iframe>';
|
||||
body.querySelector(".io-mail-preview").srcdoc = data.html;
|
||||
sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송";
|
||||
}
|
||||
async function open() {
|
||||
say("");
|
||||
sent = false;
|
||||
if (!dlg.open) dlg.showModal();
|
||||
dlg.focus({ preventScroll: true });
|
||||
body.innerHTML = '<p class="erp-muted">불러오는 중…</p>';
|
||||
try { await load(); } catch (err) { body.innerHTML = '<p class="io-error">' + esc(err.message) + "</p>"; foot.hidden = true; }
|
||||
}
|
||||
async function send(resend) {
|
||||
const to = document.getElementById("io-mail-to").value, cc = document.getElementById("io-mail-cc").value;
|
||||
sendBtn.disabled = true;
|
||||
say("보내는 중…");
|
||||
try {
|
||||
const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) });
|
||||
const out = await res.json();
|
||||
if (out.resend_needed) {
|
||||
say("");
|
||||
if (await confirmMsg(out.message)) return send(true);
|
||||
return;
|
||||
}
|
||||
if (out.reconnect) { say(out.message, true); await load(); return; }
|
||||
if (!res.ok || !out.ok) { say(out.message || out.detail || "보내지 못했습니다.", true); return; }
|
||||
sent = true;
|
||||
say(out.message);
|
||||
await load();
|
||||
} catch (_) {
|
||||
say("보내지 못했습니다(연결 오류). 다시 눌러 주세요.", true);
|
||||
} finally { sendBtn.disabled = false; }
|
||||
}
|
||||
btn.addEventListener("click", open);
|
||||
sendBtn.addEventListener("click", function () { send(false); });
|
||||
document.getElementById("io-gmail-disconnect").addEventListener("click", async function () {
|
||||
if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return;
|
||||
await fetch("/inout/gmail/disconnect", { method: "POST" });
|
||||
await load();
|
||||
say("Gmail 연결을 끊었습니다.");
|
||||
});
|
||||
dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); });
|
||||
dlg.addEventListener("close", function () {
|
||||
const url = new URL(location.href);
|
||||
const had = url.searchParams.has("mail");
|
||||
url.searchParams.delete("mail");
|
||||
url.searchParams.delete("msg");
|
||||
if (sent) location.href = url.toString(); // 머리의 '발주 메일' 기록이 바뀌었다
|
||||
else if (had) history.replaceState(null, "", url.toString());
|
||||
});
|
||||
if (btn.dataset.open === "1") open();
|
||||
}
|
||||
})();
|
||||
@@ -75,6 +75,9 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-detail-btn .material-symbols-outlined { font-size: 16px; }
|
||||
.perf-detail-btn:hover { background: #fff1ea; text-decoration: underline; }
|
||||
.perf-detail-table th, .perf-detail-table td { white-space: nowrap; }
|
||||
/* 상세보기 [합계 | 계정…] 탭(메타 — 여러 광고 계정) */
|
||||
.perf-detail-tabs { flex-wrap: wrap; margin-bottom: 10px; }
|
||||
.perf-detail-tabs .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ad-upload-btn { margin-left: auto; }
|
||||
.perf-kpi-pct { font-size: 26px; font-weight: 700; }
|
||||
|
||||
|
||||
+39
-10
@@ -403,7 +403,7 @@
|
||||
}
|
||||
});
|
||||
|
||||
// 광고 보고서 일자별 상세(네이버·구글 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||||
// 광고 보고서 일자별 상세(네이버·구글·메타 머리글) — 지금 보는 기간의 날마다 광고비·ROAS·보고서 항목, 맨 아래 합계.
|
||||
root.addEventListener("click", async function (e) {
|
||||
const btn = e.target.closest("[data-detail-channel]");
|
||||
if (!btn) return;
|
||||
@@ -425,15 +425,44 @@
|
||||
const d = new Date(iso + "T00:00:00");
|
||||
return iso.slice(5, 7) + "/" + iso.slice(8, 10) + "(" + WD[d.getDay()] + ")";
|
||||
};
|
||||
m.body.innerHTML = '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||
cols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||
res.rows.map(function (r) {
|
||||
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
|
||||
cols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
|
||||
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
|
||||
cols.map(function (c) { return '<td class="perf-num">' + cell((res.total || {})[c]) + "</td>"; }).join("") +
|
||||
"</tr></tfoot></table></div>" +
|
||||
'<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
|
||||
const table = function (t) {
|
||||
const tcols = t.columns || cols;
|
||||
return '<div class="perf-ev-wrap"><table class="perf-table perf-detail-table"><thead><tr><th class="perf-th-label">날짜</th>' +
|
||||
tcols.map(function (c) { return "<th>" + esc(c) + "</th>"; }).join("") + "</tr></thead><tbody>" +
|
||||
(t.rows || []).map(function (r) {
|
||||
return '<tr><th class="perf-td-label" scope="row">' + esc(day(r.date)) + "</th>" +
|
||||
tcols.map(function (c) { return '<td class="perf-num">' + cell((r.values || {})[c]) + "</td>"; }).join("") + "</tr>";
|
||||
}).join("") + '</tbody><tfoot><tr class="perf-row-total"><th class="perf-td-label" scope="row">합계</th>' +
|
||||
tcols.map(function (c) { return '<td class="perf-num">' + cell((t.total || {})[c]) + "</td>"; }).join("") +
|
||||
"</tr></tfoot></table></div>";
|
||||
};
|
||||
const foot = '<p class="perf-muted">합계: 숫자 항목은 더한 값, 클릭률 = 클릭수 ÷ 노출수, 광고수익률·ROAS = 날짜별 값을 광고비로 가중 평균.</p>';
|
||||
const tabs = res.tabs || [];
|
||||
if (tabs.length < 2) { m.body.innerHTML = table(res) + foot; return; }
|
||||
// 여러 광고 계정을 합치는 채널(메타) — [합계 | 계정…] 탭. 계정 탭 = 그 계정이 광고를 낸 날만.
|
||||
const missing = res.accounts_missing
|
||||
? '<p class="perf-notice">' + fmt(res.accounts_missing) + "일은 계정별 자료가 없어 합계 탭에만 있습니다 — [" + esc(name) +
|
||||
" 광고 불러오기]로 그 기간을 다시 가져오면 계정별로 나뉩니다.</p>"
|
||||
: "";
|
||||
m.body.innerHTML = '<div class="perf-quick perf-detail-tabs" role="tablist" aria-label="계정">' +
|
||||
tabs.map(function (t, i) {
|
||||
return '<button type="button" class="perf-seg' + (i ? "" : " is-active") + '" role="tab" aria-selected="' + (i ? "false" : "true") +
|
||||
'" data-tab="' + i + '"' + (t.account_id ? ' title="act_' + esc(t.account_id) + '"' : "") + ">" + esc(t.label) + "</button>";
|
||||
}).join("") + '</div><div class="perf-detail-tab-body"></div>' + missing + foot;
|
||||
const bodyEl = m.body.querySelector(".perf-detail-tab-body");
|
||||
const show = function (i) {
|
||||
m.body.querySelectorAll(".perf-detail-tabs [data-tab]").forEach(function (b) {
|
||||
const on = Number(b.dataset.tab) === i;
|
||||
b.classList.toggle("is-active", on);
|
||||
b.setAttribute("aria-selected", on ? "true" : "false");
|
||||
});
|
||||
bodyEl.innerHTML = table(tabs[i]) + (i ? '<p class="perf-muted">계정마다 따로 반올림해 계정 광고비의 합이 합계 탭과 1원 다를 수 있습니다.</p>' : "");
|
||||
};
|
||||
m.body.querySelector(".perf-detail-tabs").addEventListener("click", function (ev) {
|
||||
const b = ev.target.closest("[data-tab]");
|
||||
if (b) show(Number(b.dataset.tab));
|
||||
});
|
||||
show(0);
|
||||
} catch (err) {
|
||||
m.body.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
|
||||
}
|
||||
|
||||
+111
-13
@@ -5,36 +5,134 @@
|
||||
button.dataset.bound = "1";
|
||||
const names = { system: null, pretendard: "Pretendard Variable", "nanum-square": "NanumSquare",
|
||||
"nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" };
|
||||
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
|
||||
const FONT_DEFAULT = "system";
|
||||
const SYS_DEFAULTS = { default_view: "board", board_cover: true }; // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게
|
||||
const form = document.getElementById("pj-options-form");
|
||||
const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview");
|
||||
const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save");
|
||||
const cancel = document.getElementById("pj-options-cancel");
|
||||
function current() { const v = document.documentElement.dataset.pjFont; return Object.hasOwn(names, v) ? v : "system"; }
|
||||
const cancel = document.getElementById("pj-options-cancel"), closeX = document.getElementById("pj-options-x");
|
||||
const reset = document.getElementById("pj-options-reset");
|
||||
const tabs = Array.from(dialog.querySelectorAll(".pj-options-nav [role=tab]"));
|
||||
const panes = Array.from(dialog.querySelectorAll(".pj-options-pane"));
|
||||
// 처음 여는 탭·카드 표지 = 시스템 전체 설정(서버, 모든 사용자) — 수퍼관리자·Admin 창에만 있다(_options.html).
|
||||
// 없으면 폰트(이 브라우저)만 다룬다.
|
||||
const cover = document.getElementById("pj-options-cover");
|
||||
const views = form.elements.default_view || null;
|
||||
const sysControls = [cover].concat(Array.from(views || [])).filter(Boolean);
|
||||
const localControls = [select, cancel, closeX, reset];
|
||||
let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장)
|
||||
let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다
|
||||
|
||||
function setError(msg) { error.textContent = msg || ""; error.hidden = !msg; }
|
||||
async function request(method, body) {
|
||||
const opts = { method: method, headers: { "Content-Type": "application/json" } };
|
||||
if (body !== undefined) opts.body = JSON.stringify(body);
|
||||
const res = await fetch("/project/api/options", opts);
|
||||
let data = null;
|
||||
try { data = await res.json(); } catch (_) {}
|
||||
if (!res.ok) throw new Error((data && typeof data.detail === "string" && data.detail) || res.statusText || "오류");
|
||||
return data || {};
|
||||
}
|
||||
function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; }
|
||||
function fillSys(o) {
|
||||
if (views) views.value = o.default_view;
|
||||
if (cover) cover.checked = o.board_cover;
|
||||
}
|
||||
function paint() {
|
||||
const font = names[select.value];
|
||||
preview.style.fontFamily = font ? '"' + font + '", sans-serif' : "var(--pj-system-font)";
|
||||
}
|
||||
function showPane(name, focus) {
|
||||
tabs.forEach(function (t) {
|
||||
const on = t.dataset.pane === name;
|
||||
t.classList.toggle("is-active", on);
|
||||
t.setAttribute("aria-selected", on ? "true" : "false");
|
||||
t.tabIndex = on ? 0 : -1;
|
||||
if (on && focus) t.focus();
|
||||
});
|
||||
panes.forEach(function (p) { p.hidden = p.dataset.pane !== name; });
|
||||
}
|
||||
function busy(on) {
|
||||
save.disabled = on;
|
||||
localControls.forEach(function (c) { c.disabled = on; });
|
||||
sysControls.forEach(function (c) { c.disabled = on || !sys; });
|
||||
}
|
||||
function close() { if (!save.disabled) dialog.close(); }
|
||||
async function loadSys() {
|
||||
if (!sysControls.length) return;
|
||||
const seq = ++openSeq;
|
||||
sys = null; busy(false); // 읽는 동안 시스템 칸은 잠금
|
||||
try {
|
||||
const data = await request("GET");
|
||||
if (seq !== openSeq) return;
|
||||
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
|
||||
fillSys(sys);
|
||||
} catch (err) {
|
||||
if (seq !== openSeq) return;
|
||||
setError("모든 사용자 설정을 불러오지 못했습니다(" + err.message + "). 폰트만 저장됩니다.");
|
||||
}
|
||||
if (!save.disabled) busy(false);
|
||||
}
|
||||
|
||||
button.addEventListener("click", function () {
|
||||
select.value = current(); error.hidden = true; paint(); dialog.showModal(); select.focus();
|
||||
select.value = currentFont(); fillSys(SYS_DEFAULTS); paint(); setError("");
|
||||
showPane(tabs[0].dataset.pane); dialog.showModal(); tabs[0].focus();
|
||||
loadSys();
|
||||
});
|
||||
dialog.querySelector(".pj-options-nav").addEventListener("click", function (e) {
|
||||
const t = e.target.closest("[role=tab]");
|
||||
if (t) showPane(t.dataset.pane);
|
||||
});
|
||||
// 분류 목록 — 위/아래 화살표로 이동(데스크톱 프로그램 설정 창처럼)
|
||||
dialog.querySelector(".pj-options-nav").addEventListener("keydown", function (e) {
|
||||
const i = tabs.indexOf(document.activeElement);
|
||||
if (i < 0 || (e.key !== "ArrowDown" && e.key !== "ArrowUp")) return;
|
||||
e.preventDefault();
|
||||
showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true);
|
||||
});
|
||||
select.addEventListener("change", paint);
|
||||
cancel.addEventListener("click", function () { if (!save.disabled) dialog.close(); });
|
||||
reset.addEventListener("click", function () {
|
||||
select.value = FONT_DEFAULT; paint();
|
||||
if (sys) fillSys(SYS_DEFAULTS);
|
||||
});
|
||||
cancel.addEventListener("click", close);
|
||||
closeX.addEventListener("click", close);
|
||||
dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); });
|
||||
dialog.addEventListener("close", function () { button.focus(); });
|
||||
document.getElementById("pj-options-form").addEventListener("submit", async function (e) {
|
||||
dialog.addEventListener("close", function () { openSeq++; button.focus(); });
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault(); if (save.disabled) return;
|
||||
const value = select.value, font = names[value];
|
||||
if (!Object.hasOwn(names, value)) return;
|
||||
save.disabled = select.disabled = cancel.disabled = true; error.hidden = true;
|
||||
const fontValue = select.value, font = names[fontValue];
|
||||
if (!Object.hasOwn(names, fontValue)) return;
|
||||
// 시스템 옵션은 바뀐 키만 보낸다(그대로면 서버에 쓰지 않음)
|
||||
const sysChanges = {};
|
||||
if (sys) {
|
||||
if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value;
|
||||
if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked;
|
||||
}
|
||||
busy(true); setError("");
|
||||
try {
|
||||
if (font && document.fonts) {
|
||||
const loaded = await Promise.all([document.fonts.load('400 14px "' + font + '"', "가나다 Project"), document.fonts.load('700 14px "' + font + '"', "가나다 Project")]);
|
||||
if (loaded.some(function (list) { return !list.length; })) throw new Error("폰트를 불러오지 못했습니다. 다시 시도해 주세요.");
|
||||
}
|
||||
localStorage.setItem("pj_font", value);
|
||||
document.documentElement.dataset.pjFont = value;
|
||||
const changed = Object.keys(sysChanges);
|
||||
if (changed.length) {
|
||||
const data = await request("PUT", sysChanges);
|
||||
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
|
||||
}
|
||||
if (fontValue !== currentFont()) changed.push("font");
|
||||
localStorage.setItem("pj_font", fontValue);
|
||||
document.documentElement.dataset.pjFont = fontValue;
|
||||
// project.js 가 듣는다 — 보드 표지가 바뀌면 보던 보드를 다시 그린다(다른 사용자는 다음에 화면을 열 때부터).
|
||||
if (changed.length) {
|
||||
window.dispatchEvent(new CustomEvent("pj-options-change", {
|
||||
detail: { options: Object.assign({ font: fontValue }, sys || {}), changed: changed },
|
||||
}));
|
||||
}
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
dialog.close();
|
||||
} catch (err) { error.textContent = "설정을 저장하지 못했습니다. " + err.message; error.hidden = false; }
|
||||
finally { save.disabled = select.disabled = cancel.disabled = false; }
|
||||
} catch (err) { setError("설정을 저장하지 못했습니다. " + err.message); }
|
||||
finally { busy(false); }
|
||||
});
|
||||
})();
|
||||
|
||||
+61
-7
@@ -554,6 +554,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
.pj-hovertip.is-below { transform: translate(-50%, 0); }
|
||||
.pj-hovertip.is-below::after { top: auto; bottom: 100%; border-top-color: transparent; border-bottom-color: #1e1f21; }
|
||||
.pj-hovertip[hidden] { display: none; }
|
||||
/* 모달 대화창(showModal) 안의 말풍선은 popover(브라우저 맨 위 층)로 띄운다 — 브라우저 기본 popover 모양(가운데 배치·테두리·스크롤)을 지운다 */
|
||||
.pj-hovertip[popover] { inset: auto; margin: 0; border: 0; overflow: visible; }
|
||||
@keyframes pj-tip-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
|
||||
/* ── 달력 (휴가 모듈과 동일한 월간 그리드 룩) ── */
|
||||
@@ -3131,15 +3133,67 @@ html[data-pj-font="pretendard"] { --pj-font: "Pretendard Variable", var(--pj-sys
|
||||
html[data-pj-font="nanum-square"] { --pj-font: "NanumSquare", var(--pj-system-font); }
|
||||
html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); }
|
||||
html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); }
|
||||
.pj-options-dialog { width: min(440px, calc(100vw - 40px)); box-sizing: border-box; padding: 24px; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; }
|
||||
/* ── Project 옵션 대화창(_options.html) — 데스크톱 프로그램 설정 창처럼 왼쪽 분류 | 오른쪽 설정 ── */
|
||||
.pj-options-dialog { width: min(720px, calc(100vw - 40px)); max-height: min(600px, calc(100vh - 40px)); box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; }
|
||||
.pj-options-dialog[open] { display: flex; }
|
||||
.pj-options-dialog::backdrop { background: #0005; }
|
||||
.pj-options-dialog h2 { margin: 0 0 22px; font-size: 20px; font-weight: 500; }
|
||||
.pj-options-dialog label { display: block; margin-bottom: 8px; }
|
||||
.pj-options-dialog form { display: flex; flex-direction: column; width: 100%; min-height: 0; }
|
||||
.pj-options-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 14px 20px; border-bottom: 1px solid var(--pj-border); }
|
||||
.pj-options-head h2 { display: flex; align-items: center; gap: 8px; margin: 0; font-size: 18px; font-weight: 500; }
|
||||
.pj-options-head h2 .material-symbols-outlined { font-size: 22px; color: var(--pj-accent); }
|
||||
.pj-options-x { display: inline-flex; padding: 4px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; }
|
||||
.pj-options-x:hover { background: #f1f2f4; color: var(--pj-ink); }
|
||||
.pj-options-body { display: flex; flex: 1; min-height: 380px; overflow: hidden; }
|
||||
.pj-options-nav { flex: 0 0 180px; display: flex; flex-direction: column; gap: 2px; padding: 12px 8px; background: #f7f8fa; border-right: 1px solid var(--pj-border); }
|
||||
.pj-options-nav button { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border: 0; border-radius: 6px; background: none; color: #3d3f42; font: inherit; font-size: 14px; text-align: left; cursor: pointer; }
|
||||
.pj-options-nav button .material-symbols-outlined { font-size: 20px; color: #6d6e6f; }
|
||||
.pj-options-nav button:hover { background: #eceef1; }
|
||||
.pj-options-nav button.is-active { background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; }
|
||||
.pj-options-nav button.is-active .material-symbols-outlined { color: var(--pj-accent); }
|
||||
.pj-options-nav button:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: -2px; }
|
||||
.pj-options-panes { flex: 1; min-width: 0; padding: 20px 24px; overflow-y: auto; }
|
||||
.pj-options-pane h3 { display: flex; align-items: center; gap: 10px; margin: 0 0 14px; font-size: 15px; font-weight: 600; }
|
||||
/* 설정이 어디에 적용되나 — 이 브라우저(회색) · 모든 사용자(보라) */
|
||||
.pj-options-badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px 2px 6px; border-radius: 999px; background: #f1f2f4; color: #5f6368; font-size: 11.5px; font-weight: 500; }
|
||||
.pj-options-badge .material-symbols-outlined { font-size: 15px; }
|
||||
.pj-options-badge.is-global { background: var(--pj-accent-tint); color: var(--pj-accent-dark); }
|
||||
.pj-options-group { border: 1px solid var(--pj-border); border-radius: 8px; }
|
||||
.pj-options-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 16px; }
|
||||
.pj-options-row + .pj-options-row { border-top: 1px solid var(--pj-border); }
|
||||
.pj-options-row.is-stack { flex-direction: column; align-items: stretch; gap: 10px; }
|
||||
label.pj-options-row[for] { cursor: pointer; }
|
||||
.pj-options-row > label, .pj-options-label { display: flex; flex-direction: column; gap: 3px; font-size: 14px; }
|
||||
.pj-options-row > label b, .pj-options-label b { font-weight: 500; }
|
||||
.pj-options-row small, .pj-options-note { font-size: 12px; color: var(--pj-ink-soft); }
|
||||
.pj-options-dialog select { width: 100%; padding: 9px; border: 1px solid #d8dce2; border-radius: 6px; font: inherit; }
|
||||
.pj-options-preview { padding: 18px 12px; margin-top: 16px; border: 1px solid #e5e6e8; border-radius: 6px; font-size: 16px; line-height: 1.7; }
|
||||
.pj-options-dialog p { font-size: 12px; color: var(--pj-ink-soft); }
|
||||
.pj-options-dialog .pj-options-error { color: #c22b10; }
|
||||
.pj-options-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 22px; }
|
||||
.pj-options-preview { padding: 16px 12px; border: 1px solid #e5e6e8; border-radius: 6px; background: #fcfcfd; font-size: 16px; line-height: 1.7; }
|
||||
/* 처음 여는 탭 — 아이콘 카드 5개 중 하나 */
|
||||
.pj-options-views { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; }
|
||||
.pj-options-views label { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 4px 10px; border: 1px solid #d8dce2; border-radius: 8px; font-size: 13px; cursor: pointer; transition: border-color .12s, background .12s; }
|
||||
.pj-options-views label .material-symbols-outlined { font-size: 26px; color: #6d6e6f; }
|
||||
.pj-options-views label:hover { border-color: var(--pj-accent); }
|
||||
.pj-options-views input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.pj-options-views label:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; box-shadow: 0 0 0 1px var(--pj-accent) inset; }
|
||||
.pj-options-views label:has(input:checked) .material-symbols-outlined { color: var(--pj-accent); }
|
||||
.pj-options-views label:has(input:focus-visible) { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
|
||||
/* 켜기/끄기 스위치 */
|
||||
.pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; }
|
||||
.pj-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
|
||||
.pj-switch span { position: absolute; inset: 0; border-radius: 999px; background: #c9ccd1; transition: background .15s; pointer-events: none; }
|
||||
.pj-switch span::after { content: ""; position: absolute; top: 3px; left: 3px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px #0003; transition: transform .15s; }
|
||||
.pj-switch input:checked + span { background: var(--pj-accent); }
|
||||
.pj-switch input:checked + span::after { transform: translateX(18px); }
|
||||
.pj-switch input:focus-visible + span { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
|
||||
.pj-switch input:disabled + span { opacity: .5; }
|
||||
.pj-options-foot { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--pj-border); background: #fafbfc; }
|
||||
.pj-options-foot .pj-options-reset { margin-right: auto; }
|
||||
.pj-options-dialog .pj-options-error { margin: 0 6px 0 0; font-size: 12px; color: #c22b10; }
|
||||
@media (max-width: 560px) {
|
||||
.pj-options-body { flex-direction: column; min-height: 0; overflow-y: auto; }
|
||||
.pj-options-nav { flex: none; flex-direction: row; overflow-x: auto; border-right: 0; border-bottom: 1px solid var(--pj-border); }
|
||||
.pj-options-nav button { white-space: nowrap; }
|
||||
.pj-options-views { grid-template-columns: repeat(3, 1fr); }
|
||||
}
|
||||
.pj-goal-format { position: fixed; z-index: 1200; display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 4px 6px; max-width: calc(100vw - 16px); box-sizing: border-box; border: 1px solid var(--pj-border); border-radius: 8px; box-shadow: 0 4px 16px #0002; background: #fff; color: var(--pj-ink); font-family: var(--pj-font); font-size: 12px; }
|
||||
.pj-goal-format[hidden], .pj-goal-color-grid[hidden] { display: none; }
|
||||
.pj-goal-format-group { display: inline-flex; align-items: center; gap: 2px; }
|
||||
|
||||
+43
-10
@@ -3419,6 +3419,9 @@
|
||||
// isPAdmin = Admin 이상(남이 만든 섹션도 삭제).
|
||||
const isPro = root.dataset.isPro === "true";
|
||||
const isPAdmin = root.dataset.isPadmin === "true";
|
||||
// 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔.
|
||||
// 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래).
|
||||
let boardCover = root.dataset.boardCover !== "0";
|
||||
const me = (root.dataset.me || "").toLowerCase();
|
||||
// 섹션 삭제 — Admin 이상은 누구 것이든, 그 밖은 만든 사람만. created_by 없으면 서버가 최종 판정.
|
||||
function canDelete(createdBy) {
|
||||
@@ -3575,19 +3578,22 @@
|
||||
}
|
||||
|
||||
let timeline = null;
|
||||
// 기본 보기는 항상 보드(왼쪽 프로젝트 클릭 등으로 들어오면 보드).
|
||||
// 기본 보기는 시스템 Project 옵션의 "처음 여는 탭"(서버 project_options → data-default-view, 없으면 보드) —
|
||||
// 왼쪽 프로젝트 클릭 등으로 들어오면 그 탭.
|
||||
// 예외: 달력 이전/다음달 이동은 페이지를 통째로 새로고침하므로(?y=&m=),
|
||||
// 그때만 마지막으로 보던 뷰를 되살린다 — 안 그러면 달력을 넘기다가
|
||||
// 보드로 튕겨나간다.
|
||||
// 왼쪽 "전체 보기"(?scope=all)로 들어오면 기본 보기는 대시보드.
|
||||
// 처음 탭으로 튕겨나간다.
|
||||
// 왼쪽 "전체 보기"(?scope=all)로 들어오면 기본 보기는 대시보드(옵션과 무관).
|
||||
const VIEW_KEY = "pj_view";
|
||||
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
|
||||
let currentView = "board";
|
||||
try {
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const saved = localStorage.getItem(VIEW_KEY);
|
||||
if ((qs.has("y") || qs.has("m")) && saved &&
|
||||
["board", "list", "calendar", "timeline", "dashboard"].indexOf(saved) >= 0) currentView = saved;
|
||||
const preferred = root.dataset.defaultView; // 시스템 옵션(서버가 넣어 줌)
|
||||
if ((qs.has("y") || qs.has("m")) && saved && VIEWS.indexOf(saved) >= 0) currentView = saved;
|
||||
else if (isPro && qs.get("scope") === "all") currentView = "dashboard";
|
||||
else if (qs.get("embed") !== "1" && VIEWS.indexOf(preferred) >= 0) currentView = preferred; // 업무 창 패널(iframe)은 그대로 보드
|
||||
} catch (_) {}
|
||||
|
||||
// ── 프로젝트 스코프 — 아사나처럼 기본은 "이 프로젝트만", "전체 프로젝트"로
|
||||
@@ -3706,6 +3712,14 @@
|
||||
if (!btn) return;
|
||||
selectView(btn.dataset.view);
|
||||
});
|
||||
// Project 옵션 저장 — 보드 표지 켜기/끄기는 보고 있는 보드에 바로 반영(다른 사용자는 다음에 화면을 열 때)
|
||||
window.addEventListener("pj-options-change", function (e) {
|
||||
const d = e.detail || {}, changed = d.changed || [], opts = d.options || {};
|
||||
if (typeof opts.default_view === "string") root.dataset.defaultView = opts.default_view;
|
||||
if (changed.indexOf("board_cover") < 0 || typeof opts.board_cover !== "boolean") return;
|
||||
boardCover = opts.board_cover;
|
||||
if (currentView === "board") renderBoard();
|
||||
});
|
||||
// 서버가 그린 기본 탭(보드)과 기억된 탭이 다르면 화면을 맞춰준다.
|
||||
if (currentView !== "board") {
|
||||
tabs.querySelectorAll(".pj-tab").forEach(function (t) {
|
||||
@@ -5935,8 +5949,8 @@
|
||||
const showProjTag = viewScope === "all" || t.project_id !== projectId;
|
||||
// 카드 윗부분(배지·제목·담당자/마감일/세부 작업 줄)은 .pj-card-head 로 묶는다 —
|
||||
// 세부 작업을 펼쳐 컬럼을 스크롤하면 이 부분이 컬럼 맨 위에 고정된다(CSS sticky).
|
||||
// 설명에 이미지가 있으면 첫 이미지를 카드 위에(아사나 카드 표지)
|
||||
const cover = cardCoverSrc(t.description);
|
||||
// 설명에 이미지가 있으면 첫 이미지를 카드 위에(아사나 카드 표지) — Project 옵션 "카드 표지 이미지"로 끌 수 있다
|
||||
const cover = boardCover ? cardCoverSrc(t.description) : "";
|
||||
card.classList.toggle("has-cover", !!cover);
|
||||
card.innerHTML =
|
||||
(cover ? '<div class="pj-card-cover"><img src="' + escapeHtml(cover) + '" alt="" loading="lazy" draggable="false"></div>' : "") +
|
||||
@@ -9805,7 +9819,25 @@
|
||||
function initHoverTips() {
|
||||
let tipEl = null;
|
||||
let shown = false;
|
||||
function show(text, x, y) {
|
||||
// 모달 대화창(dialog.showModal — Project 옵션 등)은 브라우저 맨 위 층(top layer)에 떠서 body 의 말풍선이
|
||||
// z-index 와 상관없이 그 뒤에 가려진다. 그 안에서는 말풍선을 popover 로 띄워 같은 층, 대화창보다 위에 둔다.
|
||||
function inModal(target) {
|
||||
const dlg = target.closest("dialog[open]");
|
||||
if (!dlg) return false;
|
||||
try { return dlg.matches(":modal"); } catch (_) { return true; }
|
||||
}
|
||||
function topLayer(on) {
|
||||
if (typeof tipEl.showPopover !== "function") return; // popover 미지원 브라우저 — 예전처럼
|
||||
const open = tipEl.hasAttribute("popover") && tipEl.matches(":popover-open");
|
||||
if (on) {
|
||||
if (!tipEl.hasAttribute("popover")) tipEl.setAttribute("popover", "manual");
|
||||
if (!open) tipEl.showPopover();
|
||||
} else if (tipEl.hasAttribute("popover")) {
|
||||
if (open) tipEl.hidePopover();
|
||||
tipEl.removeAttribute("popover");
|
||||
}
|
||||
}
|
||||
function show(text, x, y, modal) {
|
||||
if (!tipEl) {
|
||||
tipEl = document.createElement("div");
|
||||
tipEl.className = "pj-hovertip";
|
||||
@@ -9813,6 +9845,7 @@
|
||||
}
|
||||
tipEl.textContent = text;
|
||||
tipEl.hidden = false;
|
||||
topLayer(!!modal);
|
||||
// 화면 가장자리 보정 — 좌우로 넘치면 말풍선만 안쪽으로 밀고 꼬리는
|
||||
// 커서를 계속 가리키게(--pj-tip-shift).
|
||||
// 늘 커서 **위**에 — 마우스 화살표(핫스팟에서 아래로 약 20px)에 가려지지 않게. 화면 맨 위(회의록 머리 버튼 등)라
|
||||
@@ -9829,7 +9862,7 @@
|
||||
tipEl.style.left = cx + "px";
|
||||
tipEl.style.top = (below ? y + 28 : roomy ? y - 10 : y - 2) + "px";
|
||||
}
|
||||
function hide() { shown = false; if (tipEl) tipEl.hidden = true; }
|
||||
function hide() { shown = false; if (tipEl) { topLayer(false); tipEl.hidden = true; } }
|
||||
document.addEventListener("mouseover", function (e) {
|
||||
const el = e.target.closest ? e.target.closest("[title]") : null;
|
||||
if (!el) return;
|
||||
@@ -9841,7 +9874,7 @@
|
||||
const target = e.target.closest ? e.target.closest("[data-tip]") : null;
|
||||
if (!target || !target.dataset.tip) { if (shown) hide(); return; }
|
||||
shown = true;
|
||||
show(target.dataset.tip, e.clientX, e.clientY);
|
||||
show(target.dataset.tip, e.clientX, e.clientY, inModal(target));
|
||||
});
|
||||
// 누르거나 스크롤하면 숨긴다 — 클릭으로 요소가 다시 그려지면 말풍선만
|
||||
// 허공에 남는 일이 없게.
|
||||
|
||||
@@ -34,6 +34,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"cafe24",
|
||||
"performance",
|
||||
"asset",
|
||||
"inout",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-shell.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-attach-viewer.css" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20261017a" />
|
||||
<link rel="stylesheet" href="/static/erp-notice.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/erp-overdue.css?v=20261013a" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
@@ -189,7 +189,7 @@
|
||||
|
||||
{# 공용 확인/경고 창. defer 를 쓰지 않는다 — 아래 {% block scripts %} 의
|
||||
인라인 스크립트가 곧바로 erpConfirm/erpAlert 을 쓸 수 있어야 한다. #}
|
||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||
<script src="/static/erp-dialog.js?v=20261017a"></script>
|
||||
<script src="/static/erp-attach-viewer.js" defer></script>
|
||||
{# 긴급 공지 — 로그인한 모든 화면 가운데(받는 사람이 [확인] 전까지). app/modules/notice #}
|
||||
{% if user %}<script src="/static/erp-notice.js?v=20261015a" defer></script>{% endif %}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
| `malaysia_stock_db` | 말레이시아 창고 재고관리 — 창고/아이템/세트 BOM/입출고 이력/일일 재고조사 |
|
||||
| `cafe24_db` | 카페24 연동 — OAuth 토큰/상품 캐시/상세페이지 버전/예약/감사·API 로그 |
|
||||
| `performance_db` | 실적(쇼핑몰 통합 매출) — 쇼핑몰 설정/수수료율 이력/API 인증정보(암호문)/연결 상태/매출 사건/동기화 기록 |
|
||||
| `inout_db` | 입출고 관리 — 공장/발주 담당·입고 담당/발주서·발주 품목/입고·입고 품목/상품 정보(단가·무게·은 함유량, 004) (2026-10-16, 앱 계정 `inout_app`, `INOUT_DB_URL`, 초기화 `scripts/sql/inout_db_init.sql`, 상세 `docs/INOUT_MODULE.md`) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -150,6 +150,20 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT COUNT(*) FROM
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_028_followers_exclude_assignee.sql
|
||||
```
|
||||
|
||||
## Project 옵션(시스템 전체 설정) 마이그레이션 (029)
|
||||
|
||||
029는 `project_options` 테이블만 추가한다(키 하나 = 행 하나, 기존 값 변경 없음, 다시 실행 가능). 수퍼관리자·Admin 이 Project 옵션 창에서
|
||||
바꾸는 "처음 여는 탭"·"보드 카드 표지"를 모든 사용자에게 적용하는 저장소다. 행이 없으면 기본값(보드·표지 켬).
|
||||
미적용이면 화면은 기본값으로 열리고, 옵션 저장만 503 안내(폰트는 브라우저 저장이라 그대로 동작).
|
||||
되돌리기 = `DROP TABLE project_options;`(사용자 확인 후 — 저장한 시스템 설정만 사라지고 기본값으로).
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_029_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_029_project_options.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT key, value, updated_by, updated_at FROM project_options;"
|
||||
```
|
||||
|
||||
## 실적 수동 입력·열 순서 마이그레이션 (performance_db 002)
|
||||
|
||||
002는 `perf_marketplaces.manual_input` 열(기본 꺼짐) + `perf_manual_sales` 표를 추가하고, 쇼핑몰 순서(`sort_order`)를
|
||||
@@ -250,6 +264,68 @@ docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < s
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('goal_meeting_tasks') AS t;"
|
||||
```
|
||||
|
||||
## 입출고 관리 DB 생성 (inout_db, 2026-10-16)
|
||||
|
||||
새 DB 라 기존 DB·데이터는 건드리지 않는다(초기화 SQL 은 멱등, DROP·TRUNCATE 없음).
|
||||
**비밀번호를 DSN 에 그대로 넣지 않는다** — `@`·`:`·`/`·`#`·`%` 같은 문자가 있으면 주소가 깨져 앱이 DB 를 못 찾고
|
||||
(`failed to resolve host '…@postgres-db'`) 화면은 30초 뒤 500(PoolTimeout)이 된다(2026-10-16 실제 발생). 아래처럼 URL 인코딩해서 넣는다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull
|
||||
docker exec postgres-db psql -U postgres -lqt | cut -d| -f1 | grep -w inout_db || echo "inout_db 없음 — 새로 만든다"
|
||||
read -s -p "inout_app password: " APP_PWD; echo
|
||||
docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/inout_db_init.sql
|
||||
ENC=$(APP_PWD="$APP_PWD" python3 -c "import os,urllib.parse;print(urllib.parse.quote(os.environ['APP_PWD'],safe=''))")
|
||||
# .env 끝에 줄바꿈이 없으면 앞 줄에 붙으므로 printf 로 새 줄부터, 이미 있으면 그 줄을 바꾼다
|
||||
grep -q "^INOUT_DB_URL=" .env && sed -i "s|^INOUT_DB_URL=.*|INOUT_DB_URL=postgresql://inout_app:${ENC}@postgres-db:5432/inout_db|" .env \
|
||||
|| printf '\nINOUT_DB_URL=postgresql://inout_app:%s@postgres-db:5432/inout_db\n' "$ENC" >> .env
|
||||
docker compose up --build -d --force-recreate web
|
||||
docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['INOUT_DB_URL']).execute('select 1 from inout_roles limit 1'); print('DB OK')"
|
||||
curl -s http://127.0.0.1:8080/inout/health # {"status":"ok"} — DSN 이 있다는 뜻일 뿐, 실제 연결 확인은 위 DB OK
|
||||
```
|
||||
|
||||
그다음 ERP 관리자 화면에서 쓸 사람에게 **입출고 관리** 권한 → 입출고 관리 → 옵션에서 공장·발주 담당·입고 담당 지정.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`.
|
||||
|
||||
## 입출고 관리 상품 정보 마이그레이션 (inout_db 004)
|
||||
|
||||
004는 표 2개(`inout_products` 상품 정보 — 단가·무게(개당 g)·은 함유량(%), `inout_products_excluded` 지운 단품)와
|
||||
`inout_order_lines` 의 `unit_price`·`weight_g`·`silver_pct` 열(발주할 때 값 사본)을 추가한다. 다시 실행 가능, 기존 데이터 변경 없음, 새 환경변수 없음.
|
||||
적용 뒤 옵션(톱니) → 상품 정보 → [단품 불러오기] 를 한 번 누르면 그때부터 발주서 제품은 그 목록에서 고른다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull
|
||||
docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_004_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_004_products.sql
|
||||
docker compose up --build -d web
|
||||
```
|
||||
|
||||
## 입출고 관리 발주 메일·입고증 사진 마이그레이션 (inout_db 003)
|
||||
|
||||
003은 공장 이메일 열, Gmail 연결(토큰 암호문)·발주 메일 기록·입고증 사진 표만 추가한다(다시 실행 가능, 기존 값 변경 없음).
|
||||
미적용이어도 발주·입고는 그대로(사진·메일만 안내). 발주 메일은 **구글 클라우드 준비(관리자 1회)**가 필요하다 — `docs/INOUT_MODULE.md` 6-1:
|
||||
Gmail API 사용 · OAuth 동의 화면에 `…/auth/gmail.send` 범위 · 로그인용 OAuth 클라이언트에 리디렉션 URI `{PUBLIC_BASE_URL}/inout/gmail/callback`.
|
||||
새 환경변수 없음(`APP_ENCRYPTION_KEY`·`GOOGLE_CLIENT_ID/SECRET`·`PUBLIC_BASE_URL` 재사용).
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_003_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_003_mail_photos.sql
|
||||
grep -c "^APP_ENCRYPTION_KEY=" .env # 1 이어야 Gmail 연결 저장 가능
|
||||
```
|
||||
|
||||
## 입출고 관리 공장 담당자 마이그레이션 (inout_db 002)
|
||||
|
||||
002는 `inout_factories.manager`(담당자) 열만 추가한다(다시 실행 가능). 예전 "담당자·연락처" 한 칸에 숫자 없이 이름만 있던 값은 담당자로 옮긴다.
|
||||
미적용이면 공장 저장만 안내(발주·입고는 그대로).
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_002_$(date +%Y%m%d%H%M).sql
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_002_factory_manager.sql
|
||||
docker exec postgres-db psql -U postgres -d inout_db -c "SELECT name, manager, contact FROM inout_factories ORDER BY id;"
|
||||
```
|
||||
|
||||
## 긴급 공지 마이그레이션 (024)
|
||||
|
||||
024는 `urgent_notices`·`urgent_notice_targets`·`urgent_notice_acks`·`urgent_notice_images` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능).
|
||||
@@ -356,6 +432,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
|
||||
| `APP_ENCRYPTION_KEY` | 쇼핑몰 API 인증정보 암호화 마스터 키(32바이트, `openssl rand -hex 32`). DB 에 저장하지 않음. **분실 시 저장된 인증정보 복구 불가 — 별도 안전 보관**. 쇼핑몰별 ID/Key/Secret 은 `.env` 에 넣지 않고 실적 → 설정 화면에서 입력 |
|
||||
| `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) |
|
||||
| `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) |
|
||||
| `INOUT_DB_URL` | 입출고 관리 DB DSN (예: `postgresql://inout_app:<pwd>@postgres-db:5432/inout_db`). 미설정 시 입출고 모듈 비활성(설정 필요 안내). 권한키 `inout`. 제품은 `ITEMCODE_DB_URL`(단품) 재사용 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# 입출고 관리(inout) 모듈
|
||||
|
||||
> `app/modules/inout/` · DB `inout_db` · URL `/inout/` · 권한키 `inout` · 2026-10-16 신설
|
||||
|
||||
본사가 공장에 **제품 제작 발주**를 넣고, 공장 물건이 **물류에 입고**될 때마다 입고 수량을 입력해서
|
||||
발주한 제품이 다 들어왔는지, **미입고**(덜 들어옴)·**초과 입고**(더 들어옴)가 있는지 관리한다.
|
||||
|
||||
## 1. 참고한 상용 프로그램
|
||||
|
||||
| 프로그램 | 가져온 것 |
|
||||
|---|---|
|
||||
| 이카운트 ERP | 입고(구매입력)를 **발주서를 불러와서** 처리(발주번호 + 품목코드가 기준), **발주 대비 미입고 현황**(거래처별·품목별) |
|
||||
| Odoo | 한 발주를 **여러 번 나눠 입고**, 덜 들어온 잔량은 "나중에 받기" 또는 **"더 안 받음(종결)"** 선택, 초과 입고는 확인 후 허용 |
|
||||
|
||||
## 2. 흐름과 상태
|
||||
|
||||
```
|
||||
발주(open) ──입고 일부──▶ 부분입고(partial) ──남은 것 다 입고──▶ 입고완료(done)
|
||||
│ │ └─발주보다 많이──▶ 초과입고(over)
|
||||
│ └─[잔량 종결]──▶ 종결(closed) ─[종결 풀기]─▶ 원래 상태
|
||||
└─[발주 취소](입고 기록 없을 때만)──▶ 취소(cancelled)
|
||||
```
|
||||
|
||||
- 상태는 **저장하지 않고** 품목별 누적 입고로 계산한다(`store.order_status`, `store.line_status`) — 어긋날 수 없다.
|
||||
- 품목 상태: 미입고 / 부분입고 / 입고완료 / 초과입고. 발주서는 하나라도 남으면 부분입고(초과가 섞여 있어도).
|
||||
- **모든 품목이 입고완료 또는 초과입고**(발주서 done·over)면 목록·발주서 머리에 초록 **"✓ 전체 입고 완료"**, 초과가 있으면 옆에 빨강 "초과 포함"
|
||||
(`_macros.html order_badge`, 2026-10-17 요청). 품목 줄의 초과입고 배지는 그대로 빨강.
|
||||
- **날짜 서식은 모두 `yyyy.mm.dd(요일)`** — 예 `2026.10.17(토)`, 시각이 있으면 `2026.10.17(토) 15:14`(화면 `_macros.html ymd·ymdhm`,
|
||||
메일·JSON `store.fmt_date·fmt_datetime`, 2026-10-17 요청). 날짜 입력 칸(달력)은 브라우저 모양 그대로.
|
||||
- **미입고 현황**(`/inout/pending`)은 종결·취소가 아닌 발주의 남은 수량만 — 제품별 합계, 발주별(입고 예정일 순, 지난 것 빨강), 초과 입고 목록.
|
||||
- **초과 입고**: 입고 저장 때 발주를 넘는 품목이 있으면 저장하지 않고 확인 화면(409, 넣은 숫자 유지) → [초과 입고로 저장](`confirm_over=1`).
|
||||
판단은 DB 트랜잭션 안에서 발주서 행을 잠그고(`FOR UPDATE`) 누적 입고를 다시 읽어 한다 — 동시에 입고해도 확인을 건너뛰지 않음.
|
||||
Enter 키는 숨은 기본 버튼(일반 저장)으로 가게 해 확인 없이 초과가 저장되지 않게 했다.
|
||||
- 발주서 고치기: 입고된 품목은 **뺄 수 없다**(입고 기록이 사라지므로) — 수량은 바꿀 수 있다(입고보다 줄이면 초과로 보임).
|
||||
- 입고 기록 지우기(입고 담당): 잘못 넣은 1건을 지우면 그만큼 다시 미입고.
|
||||
- 발주번호: `PO-YYMMDD-NN`(발주일 기준 그날 순번, advisory lock 으로 동시 생성해도 겹치지 않음). 순번은 숫자로 비교한다 — 100번째부터 세 자리(`-100`).
|
||||
- 시각(입력·보낸·종결 시각 등)은 DB 서버 시간대와 무관하게 **한국 시각** — 연결마다 TIMESTAMPTZ 를 KST 로 읽는다(`db._KstTimestamptzLoader`).
|
||||
|
||||
## 3. 권한·담당자
|
||||
|
||||
| 누구 | 할 수 있는 것 |
|
||||
|---|---|
|
||||
| 모듈 권한 `inout` | 발주 목록·발주서·미입고 현황 조회 |
|
||||
| **발주 담당**(옵션에서 지정) | 발주서 작성·고치기·잔량 종결/풀기·취소 |
|
||||
| **입고 담당**(옵션에서 지정) | 입고 수량 입력·입고 기록 지우기. 발주 담당이 아니면 발주서 품목은 **제품 이름·발주 수량**(+ 이번 입고 칸)만 보인다 — 코드·입고·미입고·상태·단가·금액 숨김, 입고 기록 칩도 이름(2026-10-16 요청) |
|
||||
| **수퍼관리자**(`SUPER_ADMIN_EMAIL`) | 위 전부 + 발주 목록 줄 끝 🗑 **발주 삭제**(`POST /inout/orders/{id}/delete`) — 확인 후 품목·입고 기록·입고증 사진·발주 메일 기록까지 완전히 지움(CASCADE, 되돌릴 수 없음), 서버 로그에 남김, 보던 목록(거르기)으로 돌아감(2026-10-17) |
|
||||
| ERP 관리자(`role=admin`) | 위 전부 + **옵션**(공장 목록·담당자·상품 정보) — 상단 오른쪽 **톱니** → 팝업. 입고 담당·발주 담당은 옵션을 못 본다 |
|
||||
|
||||
담당자 후보 = ERP 관리자 화면에서 `inout` 권한을 받은 사용자. 권한이 빠졌는데 담당으로 남은 사람도 옵션에 보여서 뺄 수 있다.
|
||||
담당은 `inout_roles(email, role)` — role `order`(발주)·`receive`(입고).
|
||||
|
||||
## 4. 제품 = 코드표 단품
|
||||
|
||||
발주 품목은 `itemcode_db.single_items`(단품)에서만 고른다(세트 아님) — `itemcode.py SingleItemReader`(읽기 전용, `ITEMCODE_DB_URL` 재사용,
|
||||
cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET /inout/api/items?q=`, 코드 앞부분 일치 먼저 30개),
|
||||
저장할 때 서버가 다시 코드표에 있는지 확인(`lookup`) — 없으면 "코드표 단품에 없는 제품". 발주 줄에는 코드·**발주 당시 이름** 사본을 둔다.
|
||||
이미 발주서에 있던 코드는 나중에 코드표에서 빠져도 그대로 고칠 수 있다. 코드표 연결이 안 되면 새 제품을 넣는 저장만 막힌다(안내 문구).
|
||||
**옵션 → 상품 정보에 단품을 한 번이라도 불러오면** 그때부터 발주서 제품은 그 목록에서만 고른다(지운 단품 제외, 단가 함께) — 6-3.
|
||||
|
||||
## 5. 화면
|
||||
|
||||
| 주소 | 내용 |
|
||||
|---|---|
|
||||
| `/inout/` | 발주 목록 — 상태(진행 중·완료·종결·취소·전체)·공장·발주일 기간·검색(발주번호·제품 코드·이름), 진행률 막대, 지연 표시 |
|
||||
| `/inout/pending` | 미입고 현황 — 요약 숫자, 제품별 합계, 발주별, 초과 입고 |
|
||||
| `/inout/orders/new`, `/{id}/edit` | 발주서 폼 — 공장·발주일·입고 예정일·메모, 제품 줄(검색 드롭다운·수량·**단가·금액**·줄 메모), 합계(수량·종·금액) |
|
||||
| `/inout/orders/{id}` | 발주서 — 품목별 발주·(발주 담당) **단가·금액·PP(g/개)·은(Ag)** ·입고·미입고·상태 + 합계 줄(금액·PP kg·은 g), **이번 입고** 칸(입고 담당) + [남은 수량 모두 채우기], 입고 기록, 종결·취소. 입고 담당만이면 이름·발주 수량만 |
|
||||
| 톱니 → 옵션 팝업 | 관리자만. 탭 **담당자**(발주·입고 체크) · **공장**(이름·담당자·연락처·메모·순서·사용, 발주 기록 없을 때만 지우기) · **상품 정보**(6-3). 내용은 `GET /inout/settings?panel=1`, 저장은 팝업 안에서(`X-Inout-Options: 1` → JSON, 같은 탭 그대로 다시 그림), 바뀐 게 있으면 닫을 때 화면 새로고침. 예전 주소 `/inout/settings` = 목록으로 가서 팝업(`?options=1`) |
|
||||
|
||||
화면은 서버 폼(POST → 303 + `?msg=` 안내). `static/inout.js` 는 입력 보조만(제품 검색 드롭다운 — `position: fixed` 로 body 에 붙여
|
||||
표 가로 스크롤에 잘리지 않음, 줄 추가·삭제·합계, 남은 수량 채우기, 버튼별 확인 `data-erp-confirm-btn`).
|
||||
공용 스타일과 겹치는 것 — 이 모듈 안에서만 바로잡는다(공용 파일은 그대로):
|
||||
`.erp-page` 가 content-box 라 넓은 표에서 48px 넘침 → `.erp-page:has(> .io) { box-sizing: border-box }`;
|
||||
`.erp-input` 이 min-width 240px + content-box 라 좁은 칸에서 옆 칸을 덮음, `.erp-table-wrap` 이 카드 모양(그림자·둥근 모서리)이라 카드 안에서 상자가 겹쳐 보임
|
||||
→ `.io`·`.io-dlg` 안은 border-box·최소폭 없음·카드 안 표는 평평하게(2026-10-16 옵션 화면 겹침). 공장 표는 진짜 `<table>` + 입력칸 `form="…"` 속성(줄마다 표 밖 폼)으로 열을 맞춘다.
|
||||
|
||||
## 6. DB (`inout_db`, `scripts/sql/inout_db_init.sql`)
|
||||
|
||||
| 표 | 내용 |
|
||||
|---|---|
|
||||
| `inout_factories` | 공장 — 이름(대소문자 무시 유일)·담당자(`manager`, 002)·연락처(`contact`)·이메일(`email`, 003)·메모·사용·순서 |
|
||||
| `inout_gmail_tokens` | 사람별 Gmail 연결 — 갱신 토큰 **암호문**만(003) |
|
||||
| `inout_order_mails` | 발주 메일 보낸 기록(003) |
|
||||
| `inout_receipt_photos` | 입고증 사진(bytea, 003) |
|
||||
| `inout_roles` | 담당자 — (email, role: order/receive) |
|
||||
| `inout_orders` | 발주서 — 번호·공장·발주일·입고 예정일·메모·종결(시각·사람·사유)·취소 |
|
||||
| `inout_order_lines` | 발주 품목 — 단품 코드·이름 사본·수량·줄 메모, 발주서 안에서 코드 유일. 004: 발주할 때의 `unit_price`·`weight_g`·`silver_pct` 사본 |
|
||||
| `inout_products` | 상품 정보(004) — 코드표에서 불러온 단품 + 단가(원)·무게(개당 g = PP량)·은(Ag) 함유량(%) |
|
||||
| `inout_products_excluded` | 상품 정보에서 지운 단품(004) — 다음 불러오기에서 빠진다 |
|
||||
| `inout_receipts` | 입고 1건(한 번 들어온 것) — 입고일·메모·입력자 |
|
||||
| `inout_receipt_lines` | 입고 품목별 수량 |
|
||||
|
||||
마이그레이션 `inout_db_002_factory_manager.sql`(2026-10-16): `manager` 열 추가, 예전 한 칸에 숫자 없이 이름만 있던 값은 담당자로 옮김(숫자가 있으면 연락처로 둠).
|
||||
002 미적용이어도 발주서 화면은 열리고(담당자 = `to_jsonb(f)->>'manager'`), 공장 저장만 "002 필요" 안내.
|
||||
앱 계정 `inout_app` 은 SELECT/INSERT/UPDATE/DELETE + 시퀀스만. 초기화는 멱등(DROP·TRUNCATE 없음). 백업 권장: 매일 `pg_dump inout_db`.
|
||||
|
||||
## 6-1. 발주 메일 — 발주 담당자 본인 Gmail(2026-10-16, 마이그레이션 003)
|
||||
|
||||
- **받는 사람** = 옵션 → 공장 **이메일**(`inout_factories.email`, 여러 개는 쉼표). 발주서 화면에서 바꾸거나 참조를 더할 수 있다.
|
||||
- **흐름**: 새 발주서를 저장하면 발주서 화면이 `?mail=1` 로 열려 **메일 미리보기 팝업**이 바로 뜬다(받는 사람·제목·본문).
|
||||
사람이 **[메일 발송]**을 눌러야만 보낸다(자동 발송 없음). 머리 **[발주 메일 보내기 / 다시 보내기]**로 언제든 다시 연다.
|
||||
- **본문**(`store.order_mail`) = 인사(공장 담당자 이름) · 발주번호·발주일·입고 예정일·품목 수·총수량·요청 사항(메모) 표 ·
|
||||
품목 표(No·제품 코드·제품명·수량·비고, 합계) · 보낸 사람. HTML + 글 본문(둘 다), 값은 모두 escape. 제목 `[발주] {번호} · {공장} · {첫 품목} 외 n종`.
|
||||
- **보내는 계정** = 누른 사람(발주 담당)의 Gmail — Gmail API `users.messages.send`(`gmail.py`).
|
||||
사람마다 처음 한 번 **[Gmail 연결]**: 구글 동의 화면(로그인과 같은 OAuth 클라이언트, 범위 `openid email gmail.send` 만, `hd=` 회사 도메인,
|
||||
`login_hint` = ERP 계정) → `/inout/gmail/callback` 에서 **고른 구글 계정 = ERP 로그인 계정**인지(다르면 거절), gmail.send 허락·갱신 토큰 확인 →
|
||||
갱신 토큰을 `APP_ENCRYPTION_KEY`(실적 모듈과 같은 마스터 키, AES-256-GCM, AAD `inout:gmail:{email}`)로 암호화해 `inout_gmail_tokens`.
|
||||
원문·접근 토큰은 저장·출력하지 않는다. 연결 끊기 = 구글 권한 취소(revoke) + 토큰 삭제.
|
||||
- **기록**: `inout_order_mails`(보낸 사람·받는 사람·참조·제목·Gmail id·시각) — 머리 "발주 메일: 보냄 MM-DD HH:MM … · 모두 n번".
|
||||
이미 보낸 발주서는 `resend: true` 를 같이 보내야 한다(409 → 화면이 "다시 보낼까요?" 확인) — 실수로 두 번 안 가게.
|
||||
- **오류**: 구글이 연결을 끊었으면(invalid_grant·권한 없음) 토큰을 지우고 "다시 연결" 안내, Gmail API 꺼짐은 관리자 안내, 그 밖은 구글 문구.
|
||||
- **권한**: 미리보기·발송·연결 = 발주 담당(관리자 포함). 취소된 발주서는 보낼 수 없다.
|
||||
|
||||
### 구글 클라우드 준비(관리자 1회 — 로그인에 쓰는 OAuth 클라이언트가 있는 프로젝트)
|
||||
|
||||
1. **API 및 서비스 → 라이브러리 → Gmail API → 사용**.
|
||||
2. **OAuth 동의 화면 → 범위(데이터 액세스) → 범위 추가**: `https://www.googleapis.com/auth/gmail.send`
|
||||
(사용자 유형이 **내부**(Workspace)면 구글 심사 없이 바로 쓸 수 있다).
|
||||
3. **사용자 인증 정보 → 로그인용 OAuth 2.0 클라이언트 → 승인된 리디렉션 URI 추가**: `{PUBLIC_BASE_URL}/inout/gmail/callback`
|
||||
(예: `https://dbx.no1king.freeddns.org/inout/gmail/callback`).
|
||||
4. 서버 `.env` 에 `APP_ENCRYPTION_KEY`(실적 모듈과 같은 키)·`GOOGLE_CLIENT_ID/SECRET`·`PUBLIC_BASE_URL` 이 있어야 한다(새 변수 없음).
|
||||
|
||||
## 6-2. 입고증 사진(2026-10-16, 마이그레이션 003)
|
||||
|
||||
- 입고 담당이 **입고 저장 때** [사진 고르기·찍기](여러 장, 휴대폰은 카메라) — 브라우저가 긴 변 2000px JPEG 로 줄여 올린다
|
||||
(4032×3024 7.9MB → 2000×1500 약 0.8MB, 줄인 게 더 크면 원본, HEIC·GIF 는 그대로). 입고 한 건에 **10장**, 한 장 **10MB**까지.
|
||||
- 서버는 파일 머리로 종류를 판단(`store.sniff_image` — JPG·PNG·WEBP·GIF·HEIC, SVG·PDF 등 거절)하고 **입고와 한 트랜잭션**으로
|
||||
`inout_receipt_photos`(bytea — 백업에 함께)에 넣는다 — 사진이 틀리면 입고도 저장 안 함, 초과 확인에 막혀도 사진 저장 안 함.
|
||||
- 초과 입고는 **브라우저가 먼저 확인**한다(저장 전 확인 창 → `confirm_over=1`) — 서버 확인 화면으로 돌아가면 고른 파일이 사라지기 때문.
|
||||
그래도 서버까지 가서 막히면(동시 입고 등) "사진은 다시 첨부" 안내.
|
||||
- 입고 기록 **입고증** 칸 = 썸네일(누르면 크게 보기 — ←/→ 넘기기, [원본], [지우기](입고 담당)) + **[+]** 로 나중에 더하기.
|
||||
입고 기록을 지우면 사진도 함께 지워진다(CASCADE).
|
||||
- 보기 `GET /inout/photos/{id}` — 모듈 권한자, `X-Content-Type-Options: nosniff`·CSP sandbox, HEIC 는 내려받기(브라우저가 못 보여 줌).
|
||||
|
||||
## 6-3. 상품 정보 — 단가·무게(PP)·은 함유량(2026-10-16, 마이그레이션 004)
|
||||
|
||||
- 옵션 팝업 세 번째 탭 **상품 정보**(관리자만). **[단품 불러오기]** = 코드표(`itemcode_db.single_items`) 단품 전체 → `inout_products`
|
||||
(`itemcode.list_all`, `POST /inout/settings/products/import`).
|
||||
- 새 단품은 추가, **값(단가·무게·은 함유량 중 하나라도)을 넣은 상품은 그대로**(이름도), 값이 없는 상품은 이름만 최신으로.
|
||||
- **지운 단품**(제외 목록 `inout_products_excluded`)은 건너뛴다. 코드표에서 빠진 단품을 지우지는 않는다.
|
||||
- 표: 코드·제품명·**단가(원)**·**무게·PP(g/개)**·**은 함유량(%)**·은(g/개) = 무게 × % ÷ 100(자동, 화면에서 바로 계산).
|
||||
찾기 칸, 바뀐 줄은 노랗게 + **[변경 저장 (n)]**(`POST …/products/save`, 바뀐 줄만, 하나라도 틀리면 아무것도 저장 안 함),
|
||||
저장 안 하고 닫거나 다시 불러오면 확인. 빈칸 = 미입력. 단가 소수 둘째·무게 둘째·함유량 넷째 자리까지(넘치면 사사오입), 함유량 0~100%.
|
||||
- 사용자 확인(2026-10-16): 요청의 "PP함유량" = **은(Ag) 함유량(%)**, "PP량" = 무게(**개당 g**).
|
||||
- 줄 오른쪽 ✕ = 지우기(`…/products/{code}/exclude`) — 목록·발주서 고르기에서 빠지고 제외 목록에 남는다. 아래 **제외 목록**에서 [되살리기](`…/restore`, 값은 빈칸).
|
||||
지난 발주서는 그대로.
|
||||
- **발주서**: 상품 정보가 하나라도 있으면 제품 검색·저장 확인이 상품 정보 기준(없는 코드 = "상품 정보에 없는 단품", 그 전에는 코드표).
|
||||
저장할 때 **그때 값의 사본**을 발주 품목에 남긴다(`_insert_line`) — 나중에 단가를 바꿔도 지난 발주서·메일은 그대로.
|
||||
고치기에서 새로 넣은 줄만 지금 값, 원래 있던 줄은 사본 유지. 004 전 발주서는 단가 칸이 "-".
|
||||
- **금액** = 수량 × 단가(`store.line_amount`), 합계는 단가 있는 줄만(없는 줄 수 표시), PP 총량(kg) = Σ 무게 × 수량, 은 총량(g) = Σ 무게 × % × 수량
|
||||
(`store.order_totals`, 개당 은 g 를 반올림하기 전 값으로 곱함).
|
||||
- **발주 메일 본문**(6-1)에 발주 금액·PP 총량·은(Ag) 총량 줄과 품목 표 **단가(원)·금액(원)·PP(g/개)·은(Ag) 함유량(% (g))**, 합계 줄.
|
||||
- 004 미적용이면 탭에 "마이그레이션 004 필요" 안내, 발주서는 예전처럼 코드표에서(`products_ready`).
|
||||
|
||||
## 7. 테스트
|
||||
|
||||
```bash
|
||||
python -m pytest tests/test_inout_store.py tests/test_inout_mail_photo.py tests/test_inout_web.py # DB 없이(상태·검사·메일 본문·Gmail·사진)
|
||||
INOUT_TEST_DB_URL=postgresql://inout_app:<pw>@127.0.0.1:5432/inout_db \
|
||||
python -m pytest tests/test_inout_db.py tests/test_inout_web.py # 로컬 테스트 DB(초기화 SQL 적용, 앱 계정 — 권한도 확인)
|
||||
```
|
||||
|
||||
DB 테스트: 분할 입고·완료, 초과 확인, 미입고·종결·풀기·취소, 고치기(입고 품목 보호), 입고 지우기, 동시 발주번호, 담당자·공장,
|
||||
시각 KST, 상품 정보(불러오기 유지·이름 갱신·제외·되살리기, 발주 품목 값 사본 — 끝나면 테스트 단품을 지워 목록을 처음 상태로).
|
||||
화면 흐름 테스트: 옵션 → 발주 담당 발주(코드표 아닌 제품 거부) → 입고 담당 분할·초과 확인 → 미입고 현황 → 종결, 권한별 403,
|
||||
상품 정보(관리자만·저장 검사·다시 불러와도 값 유지·지우기) → 단가로 발주 → 금액·PP·은 화면·메일 → 입고 담당은 이름·발주 수량만.
|
||||
@@ -378,7 +378,7 @@
|
||||
머리글 이름 그대로 `metrics`(JSONB). 광고 계정 이름·ID 는 넣지 않음. 직접 입력으로 광고비를 고쳐도 ROAS·상세는 그대로.
|
||||
- **네이버 머리글 클릭** → 지금 보는 기간의 일자별 보고서 표(`GET /api/ad-spend/naver/details?from=&to=`, `ad_spend.detail_table`):
|
||||
열 = 파일 머리글 순서, 맨 아래 합계(숫자 항목은 합, 클릭률 = 클릭수 ÷ 노출수, 광고수익률 = 총비용 가중 평균). `DETAIL_CHANNELS`.
|
||||
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007) — 아래 "광고 API 연동". 메타는 아직 직접 입력.
|
||||
- **구글 = 구글 광고 API**(2026-10-15, 마이그레이션 007)·**메타 = 메타 마케팅 API**(2026-10-16, 새 마이그레이션 없음) — 아래 "광고 API 연동".
|
||||
- **광고 API 연동**(2026-10-15) — 구조: `ad_sources/`(채널 하나 = 파일 하나 + `registry.py` 한 줄, 쇼핑몰 어댑터와 같은 입력칸·연결 테스트 모양,
|
||||
돌려주는 것은 날짜별 `AdDay`(금액·ROAS·항목)) + `ad_sync.py`(가져오기·저장·상태, 같은 채널 동시 실행 차단).
|
||||
- **인증정보**: 실적 설정 → **광고 API 연동** 카드 [설정](관리자). 쇼핑몰과 같은 마스터 키·AES-256-GCM, 표만 따로
|
||||
@@ -397,6 +397,38 @@
|
||||
ROAS = 전환 가치 ÷ 비용(부가세 별도) × 100(소수 둘째, 구글 화면 값 그대로), 항목에 광고비(부가세 포함)·비용(부가세 별도) 둘 다,
|
||||
항목 `metrics` = 비용·노출수·클릭수·클릭률(%)·전환수·전환 가치·ROAS(%) → 구글 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
|
||||
통화가 KRW 가 아니면 저장 안 함. 구글 오류 코드는 고칠 곳 안내를 붙여 보여 줌(`_HINTS`: 권한 없음·토큰 미승인 등), 404 = API 버전 종료 안내.
|
||||
- **메타 광고**(`ad_sources/meta_ads.py`, 2026-10-16): 입력 = 광고 계정 ID(여러 개 — 줄바꿈·쉼표, `act_` 있어도 됨, 30개까지, 비밀 아님 여러 줄) ·
|
||||
액세스 토큰(비밀 — `ads_read` 권한, 비즈니스 설정 → 시스템 사용자 토큰 권장(만료 없음), 토큰 주인을 각 광고 계정에 배정) ·
|
||||
앱 시크릿(비밀, 선택 — 앱에서 "API 호출에 앱 시크릿 필요"를 켰을 때만, `appsecret_proof` = HMAC-SHA256(토큰)) · API 버전(기본 `v26.0`).
|
||||
조회 = `GET graph.facebook.com/{버전}/act_{계정}/insights` `level=account`·`time_increment=1`·`time_range`, 계정마다 `paging.next` 따라감
|
||||
(다음 쪽 주소가 graph.facebook.com 이 아니면 중단 — 토큰을 다른 곳에 보내지 않음). 토큰은 메타 문서대로 `access_token` 매개변수
|
||||
(주소에 들어가므로 오류 문구에 주소를 넣지 않고, httpx INFO 요청 로그는 켜지 않는다). 여러 계정은 날짜별로 더함, 날짜는 광고 계정 시간대.
|
||||
기여(어트리뷰션)는 메타가 광고 관리자 설정을 따른다(2025-06 부터 API 기여 매개변수 무시) — 광고 관리자 화면 값과 같음.
|
||||
금액 = 지출 금액(`spend`) 그대로 원 반올림 — **메타 지출 금액은 이미 부가세 포함**(2026-10-16 사용자 확인, × 1.1 은 구글만), ROAS = 구매 전환값 ÷ 지출 금액 × 100
|
||||
(= 광고 관리자 "구매 ROAS"). 구매 전환값·구매수 = `action_values`·`actions` 에서 `omni_purchase` → `purchase` → 픽셀 구매 순서로 처음 있는 것 하나
|
||||
(메타가 같은 구매를 여러 종류에 같은 값으로 겹쳐 주므로 더하지 않음). 항목 `metrics` = 지출 금액(부가세 포함 = 광고비)·노출수·클릭수·
|
||||
클릭률(%)·링크 클릭·구매수·구매 전환값·ROAS(%) → 메타 머리글 클릭 = 일자별 표(`DETAIL_CHANNELS`).
|
||||
**외화 계정**(2026-10-16, 사용자 요청 — USD 계정 1314634672357695): 원화가 아닌 계정은 지출 금액·구매 전환값을 **그날 환율로 원화 환산**한 뒤
|
||||
다른 계정과 더한다(`fx.py` `krw_rates` — Frankfurter v2 `https://api.frankfurter.dev/v2/rates?base=USD"es=KRW&from=&to=`, API 키 없음,
|
||||
여러 중앙은행 고시 환율 종합(blended)이라 주말 포함 매일 있음, 서울외국환중개 매매기준율과는 조금 다를 수 있음). 그날 값이 없으면 앞 10일 안 가장 가까운 날 값,
|
||||
그래도 없거나 환율 서버 장애면 그 회차는 저장하지 않음(일부만 환산 금지, 오류 안내). 통화마다 기간 한 번 요청, 2일 이상 지난 날 환율은 프로세스 안 캐시.
|
||||
광고비 = 지출 × 환율(메타 지출은 부가세 포함), ROAS 는 비율이라 환율과 무관. 계정 탭에 `지출 금액(USD)`·`적용 환율(원)`(합계 줄 = 광고비 가중 평균).
|
||||
오류 코드 안내(`_HINTS`): 190 = 토큰 만료·무효(상태 "Token 만료"), 200·10 = 권한(ads_read·계정 배정),
|
||||
100·803 = 계정 ID, 4·17·613·80000·80004 = 호출 한도, 2635 = 버전 종료. 연결 테스트 = 계정마다 이름·통화·시간대·상태.
|
||||
**권한 오류 진단**(2026-10-16, 실제로 `(#200) Ad account owner has NOT grant ads_management or ads_read permission` 발생): 연결 테스트가
|
||||
권한 오류를 받으면 메타에 ① `debug_token`(같은 토큰 — 앱·만료·`scopes`·`granular_scopes.target_ids`, 안 되면 `me/permissions`)
|
||||
② `me/adaccounts`(이 토큰으로 보이는 계정)를 물어 원인 하나를 짚는다(`_diagnose`): ads_read 없음 → 토큰 재발급 /
|
||||
입력한 계정이 안 보임 → 시스템 사용자 [자산 할당]에서 광고 계정 배정 후 토큰 재발급 / 권한이 다른 계정에만 → 대상 포함해 재발급 /
|
||||
다 맞음 → 앱 쪽(비즈니스에 앱 연결·Marketing API 제품·제한 액세스면 토큰 주인이 앱 관리자·개발자인지). 진단 조회 실패는 무시(덧붙이는 정보).
|
||||
**상세보기 계정별 탭**(2026-10-16): 메타 머리글 상세보기 = [합계 | 계정…] 탭. 가져올 때 그날 메타 행 `metrics` 에 계정별 값을
|
||||
예약 키 `_accounts`(`ad_sources.base.ACCOUNTS_KEY` — `{계정 ID: {name, amount, roas, metrics}}`, 이름 = insights `account_name`)로 함께 저장
|
||||
(새 마이그레이션 없음). `ad_spend.detail_table` 은 `_` 로 시작하는 키를 표 열·합계·화면 값에서 뺀다. `ad_spend.detail_tabs` = 합계 탭 +
|
||||
계정 탭(그 계정이 광고를 낸 날만, 이름 = 가장 최근 날 이름, 순서 = 기간 광고비 큰 계정부터) + `accounts_missing`(계정별 값 없이 광고비만 있는 날 —
|
||||
계정별 저장 전에 가져온 날, 다시 불러오면 생김, 화면 안내). 계정마다 따로 반올림해 계정 광고비 합이 합계와 1원 다를 수 있다.
|
||||
계정별 값이 없는 채널(네이버·구글)은 `tabs: []` → 예전 그대로 표 하나.
|
||||
광고비 탭 불러오기에서 난 권한 오류엔 "[연결 테스트]가 원인을 진단" 안내를 붙인다(`_DIAG_HINT`).
|
||||
연결 테스트 문구는 **[진단]을 맨 앞에**, 메타 원문은 짧게(긴 안내 주소 뺌) 뒤에. 광고 연동 오류 문구 길이 한도는 `ad_sync.AD_MESSAGE_MAX`(1200자,
|
||||
비밀값 가린 뒤) — 예전엔 공용 기본 300자에서 잘려 진단이 "[진…" 으로 끊겼다.
|
||||
- **저장**(`db.replace_ad_api_range`, 한 트랜잭션): API 가 준 날은 `source='api'` 로 덮어씀(직접 입력·업로드 값이 있던 날도),
|
||||
기간 안에서 API 가 안 준 날(광고 없음)은 **예전 API 값만** 지움 — 직접 입력·업로드 값은 그대로. 화면 초록 숫자 = API 값.
|
||||
- **언제**: 광고비 탭 **[구글 광고 불러오기]**(설정된 연동만 보임, 지금 보는 기간 → 오늘까지, 모듈 권한자 92일·관리자 366일,
|
||||
@@ -408,7 +440,7 @@
|
||||
[총매출|수수료|수수료 차감 매출] 전환(서버가 세 값을 다 그리고 CSS 로 전환, 선택은 localStorage), 일별 추이·쇼핑몰 비중(SVG),
|
||||
월 누적(비중), 연간 누적(월별, 지나지 않은 달 빈칸). 금액 클릭 → 주문 상세(`GET /api/events`, 31일 이내).
|
||||
- **설정** `/performance/settings` — 사용/매출 집계 토글, 수수료율(적용 시작일·이력), API 설정 창, 연결 상태
|
||||
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고 —
|
||||
(정상/미설정/인증 실패/Token 만료/API 오류/연동 준비 중/사용 중지, 마지막 테스트·동기화, 최근 오류), **광고 API 연동**(구글 광고·메타 광고 —
|
||||
설정·연결 테스트·연결 상태·마지막 가져오기, 관리자), 마스터 키 상태·재암호화, 테스트 데이터 생성/삭제(`is_sample`).
|
||||
|
||||
## 8. 테스트
|
||||
@@ -421,3 +453,6 @@ python -m app.modules.performance.tests.test_performance # 또는 pytest
|
||||
동기화 격리·가리기·중복 방지·매출 기준일, 모의 데이터를 DB/네트워크 없이 검증한다.
|
||||
`tests/test_google_ads.py` — 구글 광고 입력 검사, 토큰 교환·머리글·GAQL 기간·버전, 금액 반올림·ROAS·항목 변환, 오류 안내(권한·버전·통화·키),
|
||||
광고 인증정보 AAD 이름 공간, 가져오기 저장·상태·비밀값 가림·동시 실행 차단, 불러오기 API(오늘까지 자름·92일 권한·미설정)를 가짜 구글 서버로 검증.
|
||||
`tests/test_meta_ads.py` — 메타 광고 입력 검사(계정 ID 여러 개·토큰·버전), 요청 매개변수(기간·level·appsecret_proof·버전), 여러 계정 날짜별 합산·
|
||||
쪽 넘김(메타 밖 주소 거부), 구매 값 겹침 처리·광고비 = 지출 그대로(× 1.1 없음)·ROAS·항목, 외화 환율·366일, 오류 코드 안내·토큰 미노출, 연결 테스트 문구,
|
||||
실제 fetch_days → AdSyncService 저장·상태·토큰 가림을 가짜 메타 서버로 검증.
|
||||
|
||||
@@ -25,6 +25,21 @@
|
||||
`project.css`의 `--pj-font`만 변경하므로 다른 ERP 화면은 영향을 받지 않으며 아이콘·코드 고정폭 폰트는 유지한다.
|
||||
폰트는 `static/vendor/project-fonts/`에 원본·저작권/OFL을 함께 보관하고 `project-fonts.css`에서 선언한다(외부 CDN 없음).
|
||||
저장 시 400/700 글꼴 로딩을 확인하고, 실패하면 이전 설정과 열린 창을 유지해 재시도할 수 있다.
|
||||
2026-10-16 설정 창 개편 — 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정, 아래 [기본값으로]·취소·저장(한꺼번에 저장).
|
||||
- **일반(폰트)** — 모두에게 보이고 **이 브라우저에만** 저장(`localStorage.pj_font`).
|
||||
- **프로젝트 화면·보드** — 수퍼관리자·Admin(템플릿 `pj_admin` = `access.is_project_admin`)에게만 보이고, **서버에 저장해 모든 사용자에게 적용**
|
||||
(`project_db.project_options`, 마이그레이션 029, 키 하나 = 행 하나, 값 JSONB). 키: `default_view`(왼쪽에서 프로젝트를 열 때 첫 탭
|
||||
board/list/calendar/timeline/dashboard, 기본 board) · `board_cover`(보드 카드 표지 = 설명의 첫 이미지, 기본 켬).
|
||||
허용 키·값·기본값은 `store.PROJECT_OPTION_DEFAULTS`·`normalize_project_options`(읽기 — 이상한 값은 기본값)·`validate_project_options`(쓰기 — 400) 한 곳.
|
||||
API: `GET /project/api/options`(모듈 권한자 누구나, `can_edit`) · `PUT /project/api/options`(Admin 이상, 보낸 키만, 029 미적용 503).
|
||||
프로젝트 화면(`/project/p/{id}`)은 서버가 `pj_options` → 루트 `data-default-view`·`data-board-cover` 로 넣고 `project.js` 가 쓴다
|
||||
(읽기 실패·029 미적용이면 기본값 — 화면은 늘 열린다). 달력 월 이동 `?y=&m=` 은 마지막 뷰 `pj_view` 복원, `?scope=all` 은 대시보드, `?embed=1` 은 보드 그대로.
|
||||
창은 열 때 서버 최신값을 읽고(못 읽으면 시스템 칸 잠금·폰트만 저장), 저장은 바뀐 키만 PUT → 성공해야 폰트도 적용(실패 시 창 유지·사유 표시).
|
||||
저장하면 `pj-options-change` 이벤트로 보던 보드에 바로 반영, 다른 사용자는 다음에 화면을 열 때부터.
|
||||
- **관리자(긴급 공지)** — 수퍼관리자만(`user.is_super_admin` — 공지 화면이 수퍼관리자 전용).
|
||||
- 각 분류 제목 옆 배지로 적용 범위 표시(이 브라우저에만 / 모든 사용자에게). 새 옵션도 이 창의 분류·패널로 추가한다.
|
||||
- 모달 대화창(`showModal`) 안의 말풍선은 공용 말풍선이 popover(top layer)로 띄운다(`initHoverTips` — 안 그러면 대화창 뒤에 가려짐).
|
||||
테스트: `tests/test_project_options_api.py`, jsdom `project_ui.test.js`(렌더 `project_admin_render.html`·`project_super_render.html`).
|
||||
**멤버 이름 표기** — 이메일 아이디의 첫 글자만 대문자(king → King). JS 는 `idOf(email)`/`capName(s)`,
|
||||
템플릿은 `{{ nm[:1]|upper }}{{ nm[1:] }}` 로 화면에 그릴 때만 바꾼다(API `id`·DB 값은 그대로 — 멘션·검색은 이메일 기준).
|
||||
**프로젝트 색상·아이콘(아사나식)** — 색상표는 32색(`store.COLOR_PALETTE`, 8칸×4줄 — 위 2줄은 아사나 프로젝트 16색, 아래 2줄은 같은 열의 진한 색. 진한 칸은 체크를 흰색 `.is-dark`. 새 프로젝트
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
| 쿠팡 밀크런 | 쿠팡 출고 일정 관리 (`app/modules/cupang/`) — 월간 달력 / 출고 묶음(헤더+라인) / 상자 입수량 자동계산 / 로켓 매출 관리 / 엑셀 내보내기. 상품은 `itemcode_db` 읽기 전용 참조 |
|
||||
| 휴가 (준비중) | 연차/반차/특별휴가 신청·잔여일수 관리 |
|
||||
| 말레이시아 재고 | 말레이시아 창고 재고관리 (`app/modules/malaysia/`) — 낱개 입출고/조정, 세트 BOM, 일일 재고조사(세트 분해 자동 반영), 현재고 현황. 상품명은 `itemcode_db` 읽기 전용 참조 |
|
||||
| 입출고 관리 | 본사 → 공장 제품 제작 발주, 물류 입고(여러 번 나눠), 발주 대비 미입고·초과 입고 관리 (`app/modules/inout/`, `inout_db`) — 발주 담당·입고 담당·공장은 모듈 옵션에서 지정, 제품은 `itemcode_db` 단품 읽기 전용. `docs/INOUT_MODULE.md` |
|
||||
| 긴급 공지 | 수퍼관리자가 정한 시각에 전체/고른 사람의 ERP 화면 정가운데에 띄우는 공지(`app/modules/notice/`, project_db 024) — [확인] 전까지 다시 뜸, 확인 현황. `docs/NOTICE_MODULE.md` |
|
||||
| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
|
||||
|
||||
@@ -36,6 +37,7 @@
|
||||
| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) |
|
||||
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
|
||||
| `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 |
|
||||
| `inout` | 접근 | 입출고 관리 조회. 발주·입고 입력은 모듈 옵션의 발주 담당·입고 담당(ERP 관리자는 둘 다 + 옵션) |
|
||||
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
|
||||
|
||||
`admin` 역할은 모든 권한 자동 부여. 신규 사용자는 관리자 페이지(`/admin`)에서 이메일만으로 등록 가능.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 마이그레이션 002 — 공장 담당자·연락처 분리(2026-10-16)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열 추가만, 삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
|
||||
--
|
||||
-- 왜(사용자 요청): 공장 옵션의 "담당자·연락처" 한 칸을 담당자 / 연락처 두 칸으로.
|
||||
-- inout_factories.manager(담당자) 를 추가하고 contact 는 연락처만 담는다.
|
||||
-- 예전 한 칸에 숫자 없이 이름만 들어 있던 값(예: "이석준")은 담당자로 옮긴다 — 숫자가 있으면 연락처로 보고 그대로 둔다.
|
||||
-- (manager 가 비어 있는 행만 — 다시 실행해도 같다.)
|
||||
-- 되돌리기: 백업에서 inout_factories 만 복원(열은 남아도 앱은 동작).
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS manager TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN inout_factories.manager IS '공장 담당자 이름(연락처는 contact)';
|
||||
|
||||
UPDATE inout_factories
|
||||
SET manager = contact, contact = ''
|
||||
WHERE manager = '' AND contact <> '' AND contact !~ '[0-9]';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'inout_db 002 factory manager ready' AS status;
|
||||
@@ -0,0 +1,63 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 마이그레이션 003 — 공장 이메일 · 발주 메일(Gmail) · 입고증 사진(2026-10-16)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열·표 추가만, 기존 값 변경·삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
|
||||
--
|
||||
-- 왜(사용자 요청):
|
||||
-- ① 옵션에서 공장 담당자 이메일 입력 → 발주서를 저장한 뒤 발주 내용 요약을 발주 담당자 본인 Gmail 로 공장에 보낸다
|
||||
-- (보내기는 사람이 [메일 발송]을 눌러야 함). Gmail 은 사람마다 한 번 [Gmail 연결](OAuth, gmail.send 범위만)
|
||||
-- → 갱신 토큰을 APP_ENCRYPTION_KEY 로 암호화해 저장(원문은 DB 에 없음). 보낸 기록을 남긴다.
|
||||
-- ② 입고 등록 때 공장이 보낸 입고증 사진 첨부 — 사진은 DB(bytea)에(백업에 함께 들어가고 디스크 정리가 없음).
|
||||
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
-- ① 공장 이메일(여러 개면 쉼표로)
|
||||
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN inout_factories.email IS '발주 메일 받는 주소(여러 개는 쉼표)';
|
||||
|
||||
-- ② 사람별 Gmail 연결 — 갱신 토큰 암호문만(v{키버전}:… AES-256-GCM, AAD = inout:gmail:{email})
|
||||
CREATE TABLE IF NOT EXISTS inout_gmail_tokens (
|
||||
email TEXT PRIMARY KEY,
|
||||
refresh_token_enc TEXT NOT NULL,
|
||||
scopes TEXT NOT NULL DEFAULT '',
|
||||
connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_used_at TIMESTAMPTZ NULL,
|
||||
last_error TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
COMMENT ON TABLE inout_gmail_tokens IS '입출고 — 발주 메일 보낼 Gmail 연결(사람별, 토큰은 암호문)';
|
||||
|
||||
-- ③ 발주 메일 보낸 기록
|
||||
CREATE TABLE IF NOT EXISTS inout_order_mails (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
|
||||
sent_by TEXT NOT NULL,
|
||||
to_addrs TEXT NOT NULL,
|
||||
cc_addrs TEXT NOT NULL DEFAULT '',
|
||||
subject TEXT NOT NULL,
|
||||
gmail_id TEXT NOT NULL DEFAULT '',
|
||||
sent_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_order_mails_order ON inout_order_mails (order_id, sent_at);
|
||||
COMMENT ON TABLE inout_order_mails IS '입출고 — 발주 메일 보낸 기록';
|
||||
|
||||
-- ④ 입고증 사진
|
||||
CREATE TABLE IF NOT EXISTS inout_receipt_photos (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL DEFAULT '',
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
|
||||
data BYTEA NOT NULL,
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_receipt_photos_receipt ON inout_receipt_photos (receipt_id, id);
|
||||
COMMENT ON TABLE inout_receipt_photos IS '입출고 — 입고증 사진(공장 → 물류)';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_gmail_tokens, inout_order_mails, inout_receipt_photos TO inout_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'inout_db 003 mail photos ready' AS status;
|
||||
@@ -0,0 +1,44 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 마이그레이션 004 — 상품 정보(단가·무게·은 함유량) · 제외 목록 · 발주 품목 값 사본(2026-10-16)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 표·열 추가만, 기존 값 변경·삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
|
||||
--
|
||||
-- 왜(사용자 요청):
|
||||
-- 옵션 → 상품 정보: 코드표(itemcode_db.single_items) 단품을 불러와 단가·무게(개당 g = PP량)·은(Ag) 함유량(%)을 직접 입력.
|
||||
-- 값을 넣은 상품은 다시 불러와도 그대로, 필요 없는 단품은 지우면 제외 목록에 남아 다음 불러오기에서 빠진다.
|
||||
-- 발주 메일 본문에 금액(수량 × 단가)·PP량·은 함유량 — 발주 품목에는 그때의 값 사본(나중에 단가를 바꿔도 지난 발주는 그대로).
|
||||
-- 은 함량(g/개) = 무게 × 은 함유량(%) ÷ 100 — 저장하지 않고 계산한다.
|
||||
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products (
|
||||
item_code TEXT PRIMARY KEY CHECK (char_length(item_code) BETWEEN 1 AND 64),
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
unit_price NUMERIC(14,2) NULL CHECK (unit_price IS NULL OR unit_price >= 0), -- 단가(원)
|
||||
weight_g NUMERIC(12,2) NULL CHECK (weight_g IS NULL OR weight_g >= 0), -- 무게(개당 g, PP량)
|
||||
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products IS '입출고 — 상품 정보(코드표 단품 + 단가·무게·은 함유량 수기 입력)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products_excluded (
|
||||
item_code TEXT PRIMARY KEY,
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
excluded_by TEXT NOT NULL DEFAULT '',
|
||||
excluded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products_excluded IS '입출고 — 상품 정보에서 지운 단품(다음 불러오기에서 뺌)';
|
||||
|
||||
-- 발주 품목 — 발주 당시 값 사본(없으면 NULL)
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS unit_price NUMERIC(14,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS weight_g NUMERIC(12,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS silver_pct NUMERIC(9,4) NULL;
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_products, inout_products_excluded TO inout_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'inout_db 004 products ready' AS status;
|
||||
@@ -0,0 +1,229 @@
|
||||
-- =====================================================================
|
||||
-- inout_db 초기화 스크립트 (PostgreSQL) — 입출고 관리 모듈(2026-10-16)
|
||||
-- =====================================================================
|
||||
-- 본사 → 공장 제품 제작 발주, 공장 → 물류 입고(여러 번 나눠 입고) 기록, 발주 대비 미입고·초과 관리.
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다. DROP/TRUNCATE 없음.
|
||||
--
|
||||
-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db, 백업 먼저):
|
||||
--
|
||||
-- 1) DB / 역할 / 테이블 생성 (superuser 로 1회)
|
||||
-- read -s -p "inout_app password: " APP_PWD; echo
|
||||
-- docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/inout_db_init.sql
|
||||
--
|
||||
-- 2) main-app .env 에 연결 정보 등록
|
||||
-- INOUT_DB_URL=postgresql://inout_app:<APP_PWD>@postgres-db:5432/inout_db
|
||||
--
|
||||
-- 3) main-app 재기동
|
||||
-- cd /opt/www/main && docker compose up -d --build web
|
||||
--
|
||||
-- 제품(단품)은 itemcode_db.single_items 를 읽기 전용으로 고른다(ITEMCODE_DB_URL 재사용) — 여기엔 코드·이름 사본만 둔다.
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
SELECT 'CREATE DATABASE inout_db ENCODING ''UTF8'' TEMPLATE template0'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'inout_db')
|
||||
\gexec
|
||||
|
||||
SELECT 'CREATE ROLE inout_app LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'inout_app')
|
||||
\gexec
|
||||
|
||||
SELECT 'ALTER ROLE inout_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
\gexec
|
||||
|
||||
GRANT CONNECT ON DATABASE inout_db TO inout_app;
|
||||
|
||||
\connect inout_db
|
||||
|
||||
CREATE OR REPLACE FUNCTION inout_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at := now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 1) 공장(발주처) — 옵션에서 추가·수정, 쓰지 않으면 숨김(발주 기록이 있으면 지우지 않는다)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_factories (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 100),
|
||||
manager TEXT NOT NULL DEFAULT '', -- 담당자 이름(002)
|
||||
contact TEXT NOT NULL DEFAULT '', -- 연락처
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_inout_factories_name ON inout_factories (lower(name));
|
||||
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS manager TEXT NOT NULL DEFAULT ''; -- 002 이전에 만든 DB 도 같게
|
||||
DROP TRIGGER IF EXISTS trg_inout_factories_updated ON inout_factories;
|
||||
CREATE TRIGGER trg_inout_factories_updated BEFORE UPDATE ON inout_factories
|
||||
FOR EACH ROW EXECUTE FUNCTION inout_set_updated_at();
|
||||
COMMENT ON TABLE inout_factories IS '입출고 — 공장(발주처) 목록';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 2) 담당자 — 옵션에서 지정. order = 발주 담당(발주서 작성·수정·종결), receive = 입고 담당(입고 수량 입력)
|
||||
-- ERP 관리자는 지정 없이도 둘 다 할 수 있다(앱에서 판단).
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_roles (
|
||||
email TEXT NOT NULL,
|
||||
role TEXT NOT NULL CHECK (role IN ('order', 'receive')),
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (email, role)
|
||||
);
|
||||
COMMENT ON TABLE inout_roles IS '입출고 — 발주 담당(order)·입고 담당(receive)';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3) 발주서(헤더) — 상태는 줄의 입고 합계로 앱이 계산(closed_at = 잔량 종결, cancelled_at = 취소)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_orders (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_no TEXT NOT NULL UNIQUE, -- PO-YYMMDD-NN (발주일 기준 순번)
|
||||
factory_id INTEGER NOT NULL REFERENCES inout_factories(id),
|
||||
order_date DATE NOT NULL,
|
||||
due_date DATE NULL, -- 입고 예정일(납기)
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
closed_at TIMESTAMPTZ NULL, -- 종결: 남은 미입고를 더 기다리지 않음
|
||||
closed_by TEXT NOT NULL DEFAULT '',
|
||||
close_reason TEXT NOT NULL DEFAULT '',
|
||||
cancelled_at TIMESTAMPTZ NULL, -- 취소(입고 기록이 없을 때만)
|
||||
cancelled_by TEXT NOT NULL DEFAULT '',
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_orders_date ON inout_orders (order_date DESC, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_orders_factory ON inout_orders (factory_id);
|
||||
DROP TRIGGER IF EXISTS trg_inout_orders_updated ON inout_orders;
|
||||
CREATE TRIGGER trg_inout_orders_updated BEFORE UPDATE ON inout_orders
|
||||
FOR EACH ROW EXECUTE FUNCTION inout_set_updated_at();
|
||||
COMMENT ON TABLE inout_orders IS '입출고 — 공장 제품 제작 발주서';
|
||||
|
||||
-- 발주 품목 — 제품은 itemcode_db.single_items(단품)의 코드·이름 사본(발주 당시 이름)
|
||||
CREATE TABLE IF NOT EXISTS inout_order_lines (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
|
||||
line_no INTEGER NOT NULL,
|
||||
item_code TEXT NOT NULL CHECK (char_length(item_code) BETWEEN 1 AND 64),
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
qty INTEGER NOT NULL CHECK (qty > 0),
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
UNIQUE (order_id, item_code)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_order_lines_item ON inout_order_lines (item_code);
|
||||
COMMENT ON TABLE inout_order_lines IS '입출고 — 발주 품목(단품 코드·발주 수량)';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 4) 입고 — 한 번 들어온 것(날짜) = 입고 1건, 그 안에 품목별 수량. 한 발주에 여러 번 나눠 입고 가능.
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_receipts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
|
||||
receipt_date DATE NOT NULL,
|
||||
memo TEXT NOT NULL DEFAULT '',
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_receipts_order ON inout_receipts (order_id, receipt_date);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_receipt_lines (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE,
|
||||
order_line_id BIGINT NOT NULL REFERENCES inout_order_lines(id) ON DELETE CASCADE,
|
||||
qty INTEGER NOT NULL CHECK (qty > 0),
|
||||
UNIQUE (receipt_id, order_line_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_receipt_lines_line ON inout_receipt_lines (order_line_id);
|
||||
COMMENT ON TABLE inout_receipts IS '입출고 — 물류 입고(한 번 들어온 것)';
|
||||
COMMENT ON TABLE inout_receipt_lines IS '입출고 — 입고 품목별 수량';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 5) 공장 이메일 · Gmail 연결 · 발주 메일 기록 · 입고증 사진 (= 마이그레이션 003, 새로 만들 때도 같게)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- ① 공장 이메일(여러 개면 쉼표로)
|
||||
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN inout_factories.email IS '발주 메일 받는 주소(여러 개는 쉼표)';
|
||||
|
||||
-- ② 사람별 Gmail 연결 — 갱신 토큰 암호문만(v{키버전}:… AES-256-GCM, AAD = inout:gmail:{email})
|
||||
CREATE TABLE IF NOT EXISTS inout_gmail_tokens (
|
||||
email TEXT PRIMARY KEY,
|
||||
refresh_token_enc TEXT NOT NULL,
|
||||
scopes TEXT NOT NULL DEFAULT '',
|
||||
connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_used_at TIMESTAMPTZ NULL,
|
||||
last_error TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
COMMENT ON TABLE inout_gmail_tokens IS '입출고 — 발주 메일 보낼 Gmail 연결(사람별, 토큰은 암호문)';
|
||||
|
||||
-- ③ 발주 메일 보낸 기록
|
||||
CREATE TABLE IF NOT EXISTS inout_order_mails (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
|
||||
sent_by TEXT NOT NULL,
|
||||
to_addrs TEXT NOT NULL,
|
||||
cc_addrs TEXT NOT NULL DEFAULT '',
|
||||
subject TEXT NOT NULL,
|
||||
gmail_id TEXT NOT NULL DEFAULT '',
|
||||
sent_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_order_mails_order ON inout_order_mails (order_id, sent_at);
|
||||
COMMENT ON TABLE inout_order_mails IS '입출고 — 발주 메일 보낸 기록';
|
||||
|
||||
-- ④ 입고증 사진
|
||||
CREATE TABLE IF NOT EXISTS inout_receipt_photos (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL DEFAULT '',
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
|
||||
data BYTEA NOT NULL,
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_inout_receipt_photos_receipt ON inout_receipt_photos (receipt_id, id);
|
||||
COMMENT ON TABLE inout_receipt_photos IS '입출고 — 입고증 사진(공장 → 물류)';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 6) 상품 정보 · 제외 목록 · 발주 품목 값 사본 (= 마이그레이션 004)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS inout_products (
|
||||
item_code TEXT PRIMARY KEY CHECK (char_length(item_code) BETWEEN 1 AND 64),
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
unit_price NUMERIC(14,2) NULL CHECK (unit_price IS NULL OR unit_price >= 0), -- 단가(원)
|
||||
weight_g NUMERIC(12,2) NULL CHECK (weight_g IS NULL OR weight_g >= 0), -- 무게(개당 g, PP량)
|
||||
silver_pct NUMERIC(9,4) NULL CHECK (silver_pct IS NULL OR (silver_pct >= 0 AND silver_pct <= 100)), -- 은(Ag) 함유량 %
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products IS '입출고 — 상품 정보(코드표 단품 + 단가·무게·은 함유량 수기 입력)';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS inout_products_excluded (
|
||||
item_code TEXT PRIMARY KEY,
|
||||
item_name TEXT NOT NULL DEFAULT '',
|
||||
excluded_by TEXT NOT NULL DEFAULT '',
|
||||
excluded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE inout_products_excluded IS '입출고 — 상품 정보에서 지운 단품(다음 불러오기에서 뺌)';
|
||||
|
||||
-- 발주 품목 — 발주 당시 값 사본(없으면 NULL)
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS unit_price NUMERIC(14,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS weight_g NUMERIC(12,2) NULL;
|
||||
ALTER TABLE inout_order_lines ADD COLUMN IF NOT EXISTS silver_pct NUMERIC(9,4) NULL;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 권한 — 앱 계정은 읽기·쓰기만(스키마 변경 없음)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO inout_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON
|
||||
inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines,
|
||||
inout_gmail_tokens, inout_order_mails, inout_receipt_photos, inout_products, inout_products_excluded
|
||||
TO inout_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
|
||||
|
||||
SELECT 'inout_db ready' AS status;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 029 — Project 옵션(시스템 전체 설정)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-16 사용자 요청): Project 옵션 창에서 "일반"(폰트)은 브라우저별(localStorage) 그대로 두고,
|
||||
-- 수퍼관리자·Admin 이 바꾸는 "프로젝트 화면"(처음 여는 탭)·"보드"(카드 표지 이미지)는 모든 사용자에게 반영한다.
|
||||
-- 키 하나 = 설정 하나(값은 JSONB). 허용 키·값 검사와 기본값은 앱(store.normalize_project_options) 한 곳에서 한다.
|
||||
-- 행이 없으면 기본값(처음 여는 탭 = 보드, 카드 표지 = 켬) — 이 파일은 기본 행을 넣지 않는다.
|
||||
-- 미적용이면: 화면은 기본값으로 동작하고, 옵션 저장만 503 안내.
|
||||
-- 되돌리기: DROP TABLE project_options; (사용자 확인 후 — 저장한 시스템 설정만 사라지고 기본값으로 돌아감)
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS project_options (
|
||||
key TEXT PRIMARY KEY CHECK (char_length(key) BETWEEN 1 AND 64),
|
||||
value JSONB NOT NULL,
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE project_options IS 'Project 옵션 — 시스템 전체 설정(수퍼관리자·Admin 수정, 모든 사용자에게 적용). 키: default_view, board_cover';
|
||||
|
||||
COMMIT;
|
||||
@@ -28,6 +28,17 @@ async function env(file) {
|
||||
return { columns: ["총비용", "노출수", "클릭률(%)", "구매완료 광고수익률(%)"], total: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 },
|
||||
rows: [{ date: "2026-10-03", amount: 300000, roas: 250.5, values: { "총비용": 300000, "노출수": 30043, "클릭률(%)": 1.53, "구매완료 광고수익률(%)": 250.5 } }] }; } };
|
||||
}
|
||||
if (/^\/performance\/api\/ad-spend\/meta\/details/.test(url)) { // 메타 — [합계 | 계정…] 탭(2026-10-16)
|
||||
const tbl = function (amount, roas) {
|
||||
return { columns: ["광고비(부가세 포함)", "ROAS(%)"], total: { "광고비(부가세 포함)": amount, "ROAS(%)": roas },
|
||||
rows: [{ date: "2026-10-03", amount: amount, roas: roas, values: { "광고비(부가세 포함)": amount, "ROAS(%)": roas } }] };
|
||||
};
|
||||
return { ok: true, status: 200, json: async function () {
|
||||
return Object.assign(tbl(165001, 400), { accounts_missing: e.metaMissing || 0, tabs: [
|
||||
Object.assign({ key: "total", label: "합계" }, tbl(165001, 400)),
|
||||
Object.assign({ key: "111", label: "본계정", account_id: "111" }, tbl(110000, 450)),
|
||||
Object.assign({ key: "222", label: "서브<계정>", account_id: "222" }, tbl(55001, 300))] }); } };
|
||||
}
|
||||
if (/^\/performance\/api\/ad-spend\/upload/.test(url)) {
|
||||
return { ok: true, status: 200, json: async function () {
|
||||
return { ok: true, saved: 12, name: "쿠팡(로켓)", total: 2636494, from: "2026-10-01", to: "2026-10-12", empty_days: e.uploadEmpty || [] }; } };
|
||||
@@ -225,7 +236,7 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
const hb = e.d.querySelector('.perf-main thead [data-detail-channel="naver"]');
|
||||
const detailChans = Array.from(e.d.querySelectorAll(".perf-main thead [data-detail-channel]")).map(function (b) { return b.dataset.detailChannel; });
|
||||
// 구글도 광고 API 로 가져온 보고서 항목이 있어 상세 보기(2026-10-15) — 그 밖의 채널은 아님
|
||||
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글만)", !!hb && detailChans.sort().join(",") === "google,naver", detailChans);
|
||||
check("[네이버] 머리글 = 상세 보기 버튼(네이버·구글·메타만)", !!hb && detailChans.sort().join(",") === "google,meta,naver", detailChans);
|
||||
hb.click(); await settle();
|
||||
const call = e.calls.find(function (c) { return /\/details/.test(c.url); });
|
||||
check("[네이버] 지금 기간으로 상세 요청", call && call.url === "/performance/api/ad-spend/naver/details?from=2026-10-01&to=2026-10-31", e.calls);
|
||||
@@ -235,6 +246,24 @@ function gross(td) { return td.querySelector(".v-gross").textContent.trim(); }
|
||||
check("[네이버] 상세 표 = 날짜 + 보고서 항목(파일 순서), 날짜 mm/dd(요일)", ths.join(",") === "날짜,총비용,노출수,클릭률(%),구매완료 광고수익률(%)" &&
|
||||
row.join(",") === "10/03(토),300,000,30,043,1.53,250.50", [ths, row]);
|
||||
check("[네이버] 맨 아래 합계 줄", /합계/.test(modal.querySelector("tfoot").textContent) && /30,043/.test(modal.querySelector("tfoot").textContent));
|
||||
check("[네이버] 계정 탭 없음(탭 자료 없는 채널)", !modal.querySelector(".perf-detail-tabs"));
|
||||
}
|
||||
// ── 메타 — 상세보기 [합계 | 계정…] 탭(2026-10-16) ──
|
||||
{
|
||||
const e = await env("perf_ads.html");
|
||||
e.metaMissing = 2;
|
||||
e.d.querySelector('.perf-main thead [data-detail-channel="meta"]').click(); await settle();
|
||||
const modal = e.d.querySelector(".perf-modal");
|
||||
const tabs = Array.from(modal.querySelectorAll(".perf-detail-tabs [data-tab]"));
|
||||
const foot = function () { return modal.querySelector(".perf-detail-tab-body tfoot").textContent; };
|
||||
check("[메타] 탭 = 합계 + 계정(이름은 글자 그대로, 계정 ID 는 말풍선)", tabs.map(function (b) { return b.textContent; }).join("|") === "합계|본계정|서브<계정>" &&
|
||||
tabs[1].getAttribute("title") === "act_111" && !tabs[0].hasAttribute("title"), tabs.map(function (b) { return b.outerHTML; }));
|
||||
check("[메타] 처음엔 합계 탭", tabs[0].classList.contains("is-active") && tabs[0].getAttribute("aria-selected") === "true" && /165,001/.test(foot()) &&
|
||||
modal.querySelectorAll(".perf-detail-tab-body table").length === 1);
|
||||
tabs[2].click();
|
||||
check("[메타] 계정 탭 누르면 그 계정 표", tabs[2].classList.contains("is-active") && !tabs[0].classList.contains("is-active") &&
|
||||
/55,001/.test(foot()) && /1원 다를 수/.test(modal.textContent));
|
||||
check("[메타] 계정별 자료 없는 날 안내", /2일은 계정별 자료가 없어/.test(modal.textContent) && modal.textContent.indexOf("[메타 광고 불러오기]") >= 0);
|
||||
}
|
||||
// ── 설정: 수동 입력 토글 ──
|
||||
{
|
||||
|
||||
@@ -16,6 +16,7 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
|
||||
const superHtml = fs.readFileSync(path.join(__dirname, ".out", "project_super_render.html"), "utf8");
|
||||
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
|
||||
const mytasksHtml = fs.readFileSync(path.join(__dirname, ".out", "mytasks_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
@@ -538,6 +539,119 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
check("[옵션] 폰트 로딩 실패는 이전 설정 유지·재시도 가능", dialog.open && !d.getElementById("pj-options-error").hidden && !select.disabled && w.localStorage.getItem("pj_font") === "pretendard");
|
||||
}
|
||||
|
||||
// 옵션 — 일반(폰트)은 이 브라우저, 프로젝트 화면·보드는 서버(시스템 전체, 수퍼관리자·Admin 만 수정).
|
||||
// 가짜 서버: GET/PUT /project/api/options. 화면 값은 project.html 이 data-default-view·data-board-cover 로 넣는다.
|
||||
function optionRoutes(env, state) {
|
||||
env.route("GET", /\/project\/api\/options$/, function () {
|
||||
if (state.getFail) return { status: 500, body: { detail: "DB 오류" } };
|
||||
return { body: { options: Object.assign({}, state.options), can_edit: true } };
|
||||
});
|
||||
env.route("PUT", /\/project\/api\/options$/, function (url, body) {
|
||||
if (state.putFail) return { status: 503, body: { detail: "DB 마이그레이션 029(Project 옵션)가 아직 적용되지 않았습니다." } };
|
||||
Object.assign(state.options, body);
|
||||
return { body: { options: Object.assign({}, state.options) } };
|
||||
});
|
||||
}
|
||||
function withCover(d) {
|
||||
const seed = JSON.parse(d.getElementById("pj-data").textContent);
|
||||
seed.tasks.find(function (t) { return t.id === 101; }).description = '<p>표지</p><img src="/project/attachments/1/a.png">';
|
||||
d.getElementById("pj-data").textContent = JSON.stringify(seed);
|
||||
}
|
||||
function pageOptions(d, view, coverOn) {
|
||||
const root = d.querySelector(".pj-project-view");
|
||||
root.dataset.defaultView = view; root.dataset.boardCover = coverOn ? "1" : "0";
|
||||
}
|
||||
const optCalls = function (env, method) { return env.calls.filter(function (c) { return c.method === method && /\/project\/api\/options$/.test(c.url); }); };
|
||||
|
||||
// 수퍼관리자 — 분류 탭, 서버 값 불러오기, 표지 끄기(보던 보드에 바로)·첫 탭 저장, 바뀐 키만 PUT, 기본값으로, 실패 처리.
|
||||
{
|
||||
const env = makeEnv(superHtml); baseRoutes(env); const d = env.d, w = env.w;
|
||||
const state = { options: { default_view: "board", board_cover: true } }; optionRoutes(env, state);
|
||||
withCover(d); await boot(env);
|
||||
const dialog = d.getElementById("pj-options-dialog"), cover = d.getElementById("pj-options-cover");
|
||||
const coverImg = function () { return d.querySelector('.pj-card[data-task-id="101"] .pj-card-cover img'); };
|
||||
const pane = function (n) { return d.querySelector('.pj-options-pane[data-pane="' + n + '"]'); };
|
||||
const checkedView = function () { return dialog.querySelector('input[name="default_view"]:checked').value; };
|
||||
check("[옵션 표지] 기본은 설명 첫 이미지를 카드 표지로", !!coverImg() && coverImg().getAttribute("src") === "/project/attachments/1/a.png");
|
||||
state.options = { default_view: "calendar", board_cover: true }; // 다른 관리자가 그 사이 바꿈 — 창은 서버 최신값
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
check("[옵션] 열면 일반 분류부터·서버 값(캘린더) 불러옴", dialog.open && !pane("general").hidden && pane("board").hidden && optCalls(env, "GET").length === 1 && cover.checked && checkedView() === "calendar" && !cover.disabled);
|
||||
check("[옵션] 적용 범위 표시 — 일반=이 브라우저, 보드=모든 사용자", /이 브라우저/.test(pane("general").querySelector(".pj-options-badge").textContent) && /모든 사용자/.test(pane("board").querySelector(".pj-options-badge.is-global").textContent));
|
||||
d.getElementById("pj-opt-tab-board").click();
|
||||
check("[옵션] 분류 탭 전환", pane("general").hidden && !pane("board").hidden && d.getElementById("pj-opt-tab-board").getAttribute("aria-selected") === "true");
|
||||
cover.checked = false; dialog.querySelector('input[name="default_view"][value="list"]').checked = true;
|
||||
d.getElementById("pj-options-cancel").click(); await settle();
|
||||
check("[옵션] 취소는 서버에 저장하지 않음", !dialog.open && optCalls(env, "PUT").length === 0 && !!coverImg());
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
check("[옵션] 다시 열면 취소한 값은 되돌림", cover.checked && checkedView() === "calendar");
|
||||
cover.checked = false; dialog.querySelector('input[name="default_view"][value="timeline"]').checked = true;
|
||||
d.getElementById("pj-options-save").click(); await settle();
|
||||
const put = optCalls(env, "PUT")[0];
|
||||
check("[옵션 시스템] 저장은 바뀐 키만 서버로(PUT)", !dialog.open && optCalls(env, "PUT").length === 1 && JSON.stringify(put.body) === JSON.stringify({ default_view: "timeline", board_cover: false }));
|
||||
check("[옵션 시스템] 브라우저(localStorage)에는 시스템 옵션을 쓰지 않음", !w.localStorage.getItem("pj_board_cover") && !w.localStorage.getItem("pj_default_view"));
|
||||
check("[옵션 표지] 끄고 저장하면 보던 보드에서 표지가 바로 사라짐", !coverImg() && !d.querySelector('.pj-card[data-task-id="101"]').classList.contains("has-cover"));
|
||||
check("[옵션 첫 탭] 저장해도 지금 보던 탭은 그대로", !d.querySelector('.pj-view[data-view="board"]').hidden);
|
||||
d.getElementById("pj-options-btn").click(); await settle(); d.getElementById("pj-options-font").value = "pretendard";
|
||||
d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션] 폰트만 바꾸면 서버에 쓰지 않음", optCalls(env, "PUT").length === 1 && w.localStorage.getItem("pj_font") === "pretendard");
|
||||
d.getElementById("pj-options-btn").click(); await settle(); d.getElementById("pj-options-reset").click();
|
||||
check("[옵션] 기본값으로 — 창 안의 값만 처음으로(저장 전)", cover.checked && checkedView() === "board" && d.getElementById("pj-options-font").value === "system" && optCalls(env, "PUT").length === 1);
|
||||
d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션 표지] 다시 켜면 표지 복귀", JSON.stringify(optCalls(env, "PUT")[1].body) === JSON.stringify({ default_view: "board", board_cover: true }) && !!coverImg() && w.localStorage.getItem("pj_font") === "system");
|
||||
// 서버 저장 실패(029 미적용 등) — 창 유지·오류 안내, 폰트도 적용하지 않음(전부 아니면 전무)
|
||||
state.putFail = true;
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
cover.checked = false; d.getElementById("pj-options-font").value = "nanum-square";
|
||||
d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션 시스템] 저장 실패 — 창 유지·사유 표시·폰트 미적용·다시 시도 가능", dialog.open && /029/.test(d.getElementById("pj-options-error").textContent) && !d.getElementById("pj-options-error").hidden &&
|
||||
w.localStorage.getItem("pj_font") === "system" && !!coverImg() && !cover.disabled && !d.getElementById("pj-options-save").disabled);
|
||||
d.getElementById("pj-options-cancel").click();
|
||||
// 서버 값 읽기 실패 — 시스템 칸 잠금, 폰트는 저장됨, PUT 없음
|
||||
state.getFail = true; state.putFail = false;
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
check("[옵션 시스템] 불러오기 실패 — 시스템 칸 잠금·안내", cover.disabled && /폰트만 저장/.test(d.getElementById("pj-options-error").textContent));
|
||||
const putsBefore = optCalls(env, "PUT").length; // 위의 실패한 PUT 도 기록에 있다
|
||||
d.getElementById("pj-options-font").value = "nanum-square"; d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션 시스템] 불러오기 실패해도 폰트는 저장, 서버엔 쓰지 않음", !dialog.open && w.localStorage.getItem("pj_font") === "nanum-square" && optCalls(env, "PUT").length === putsBefore);
|
||||
}
|
||||
// 시스템 첫 탭(서버 값) — 누구든 그 탭으로 시작, 이상한 값은 보드
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const d = env.d;
|
||||
pageOptions(d, "list", true); await boot(env);
|
||||
check("[옵션 첫 탭] 일반 사용자도 시스템 첫 탭(목록)으로 시작", !d.querySelector('.pj-view[data-view="list"]').hidden && d.querySelector('.pj-view[data-view="board"]').hidden && d.querySelector('#pj-view-tabs .pj-tab.is-active').dataset.view === "list");
|
||||
}
|
||||
{
|
||||
const env = makeEnv(superHtml); baseRoutes(env); const d = env.d;
|
||||
pageOptions(d, "garbage", true); await boot(env);
|
||||
check("[옵션 첫 탭] 이상한 값이면 보드", !d.querySelector('.pj-view[data-view="board"]').hidden);
|
||||
}
|
||||
// Admin — 프로젝트 화면·보드는 보이고 수정 가능, 관리자(긴급 공지)는 수퍼관리자만이라 없음.
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env); const d = env.d;
|
||||
const state = { options: { default_view: "board", board_cover: false } }; optionRoutes(env, state);
|
||||
await boot(env);
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
check("[옵션 Admin] 일반·프로젝트 화면·보드 분류, 관리자 분류는 없음, 서버 값 표시",
|
||||
Array.from(d.querySelectorAll("#pj-options-dialog .pj-options-nav [role=tab]")).map(function (t) { return t.dataset.pane; }).join(",") === "general,view,board" &&
|
||||
!d.getElementById("pj-opt-pane-admin") && !d.getElementById("pj-options-cover").checked && !d.getElementById("pj-options-cover").disabled);
|
||||
d.getElementById("pj-options-cover").checked = true; d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션 Admin] 저장하면 서버로", JSON.stringify((optCalls(env, "PUT")[0] || {}).body) === JSON.stringify({ board_cover: true }));
|
||||
}
|
||||
// 일반 사용자 — 폰트만 보이고 서버 옵션은 읽지도 쓰지도 않음, 시스템 표지 끔은 그대로 적용.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
|
||||
optionRoutes(env, { options: { default_view: "board", board_cover: true } });
|
||||
withCover(d); pageOptions(d, "board", false); await boot(env);
|
||||
const dialog = d.getElementById("pj-options-dialog");
|
||||
check("[옵션 일반 사용자] 시스템 표지 끔이 적용 — 표지 없음", !!d.querySelector('.pj-card[data-task-id="101"]') && !d.querySelector('.pj-card[data-task-id="101"] .pj-card-cover'));
|
||||
d.getElementById("pj-options-btn").click(); await settle();
|
||||
check("[옵션 일반 사용자] 분류는 일반(폰트)만·서버 옵션 안 읽음", dialog.open && dialog.querySelectorAll(".pj-options-nav [role=tab]").length === 1 &&
|
||||
dialog.querySelectorAll(".pj-options-pane").length === 1 && !d.getElementById("pj-options-cover") && !dialog.querySelector('input[name="default_view"]') && !d.getElementById("pj-opt-pane-admin") && optCalls(env, "GET").length === 0);
|
||||
d.getElementById("pj-options-reset").click(); d.getElementById("pj-options-font").value = "pretendard";
|
||||
d.getElementById("pj-options-save").click(); await settle();
|
||||
check("[옵션 일반 사용자] 폰트만 이 브라우저에 저장 — 서버엔 안 씀", !dialog.open && w.localStorage.getItem("pj_font") === "pretendard" && optCalls(env, "PUT").length === 0);
|
||||
}
|
||||
|
||||
// 카드 완료 체크 — 상세창과 분리, 중복 요청·실패 복구·읽기 전용.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); const d = env.d, w = env.w;
|
||||
|
||||
@@ -50,8 +50,9 @@ def main() -> None:
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
|
||||
render_one(env, name, admin)
|
||||
for name, admin, sup in (("project_render.html", False, False), ("project_admin_render.html", True, False),
|
||||
("project_super_render.html", True, True)):
|
||||
render_one(env, name, admin, sup)
|
||||
render_inbox(env)
|
||||
render_mytasks(env)
|
||||
|
||||
@@ -102,9 +103,9 @@ def render_inbox(env) -> None:
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
def render_one(env, name: str, admin: bool) -> None:
|
||||
def render_one(env, name: str, admin: bool, sup: bool = False) -> None:
|
||||
html = env.get_template("project/project.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True,
|
||||
user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True,
|
||||
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
|
||||
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
|
||||
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""입출고 저장소 — 실제 PostgreSQL(로컬 테스트 DB 전용, INOUT_TEST_DB_URL 이 localhost 일 때만).
|
||||
|
||||
INOUT_TEST_DB_URL=postgresql://inout_app:<pw>@127.0.0.1:5432/inout_db python -m pytest tests/test_inout_db.py
|
||||
scripts/sql/inout_db_init.sql 을 적용한 DB 에 앱 계정(inout_app)으로 붙는다 — 권한(GRANT)도 함께 확인된다.
|
||||
가상의 공장·발주만 만든다(이름에 무작위 꼬리표).
|
||||
"""
|
||||
import os
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from datetime import date
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DSN = os.getenv("INOUT_TEST_DB_URL", "")
|
||||
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
|
||||
@unittest.skipUnless(ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
class InoutDbTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
|
||||
cls.st = InoutDBStore(DSN)
|
||||
cls.tag = uuid.uuid4().hex[:6]
|
||||
cls.fid = cls.st.save_factory(factory_id=None, name=f"테스트공장-{cls.tag}", manager="김공장", contact="010-1234")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.st.close()
|
||||
|
||||
def order(self, lines, **over):
|
||||
from app.modules.inout import store
|
||||
|
||||
data = store.validate_order(factory_id=over.get("factory_id", self.fid), order_date=over.get("order_date", "2026-10-16"),
|
||||
due_date=over.get("due_date", "2026-10-30"), memo="",
|
||||
codes=[c for c, _q in lines], quantities=[str(q) for _c, q in lines])
|
||||
names = {c: f"{c} 이름" for c, _q in lines}
|
||||
return self.st.create_order(data, names, by="Boss@Test.local")
|
||||
|
||||
def line_ids(self, oid):
|
||||
return {ln["item_code"]: ln["id"] for ln in self.st.get_order(oid)["lines"]}
|
||||
|
||||
def test_partial_receipts_until_done(self):
|
||||
o = self.order([("MT-A", 100), ("MT-B", 50)])
|
||||
self.assertRegex(o["order_no"], r"^PO-261016-\d{2,}$") # 100번째부터는 세 자리
|
||||
head = self.st.get_order(o["id"])
|
||||
self.assertEqual((head["factory_manager"], head["factory_contact"]), ("김공장", "010-1234")) # 담당자·연락처 따로(002)
|
||||
ids = self.line_ids(o["id"])
|
||||
self.assertEqual(self.st.get_order(o["id"])["status"], "open")
|
||||
self.st.add_receipt(o["id"], {ids["MT-A"]: "60"}, receipt_date="2026-10-20", memo="1차", confirm_over=False, by="w@x")
|
||||
got = self.st.get_order(o["id"])
|
||||
self.assertEqual((got["status"], got["summary"]["received"], got["summary"]["remaining"]), ("partial", 60, 90))
|
||||
a = next(x for x in got["lines"] if x["item_code"] == "MT-A")
|
||||
self.assertEqual((a["received"], a["remaining"], a["status"]), (60, 40, "partial"))
|
||||
self.st.add_receipt(o["id"], {ids["MT-A"]: "40", ids["MT-B"]: "50"}, receipt_date="2026-10-22", memo="",
|
||||
confirm_over=False, by="w@x")
|
||||
got = self.st.get_order(o["id"])
|
||||
self.assertEqual((got["status"], got["summary"]["remaining"], len(got["receipts"])), ("done", 0, 2))
|
||||
self.assertEqual([r["total"] for r in got["receipts"]], [60, 90])
|
||||
# 진행 중 목록에서 빠지고 완료 목록에
|
||||
self.assertNotIn(o["id"], [x["id"] for x in self.st.list_orders(status="active", factory_id=self.fid)])
|
||||
self.assertIn(o["id"], [x["id"] for x in self.st.list_orders(status="done", factory_id=self.fid)])
|
||||
|
||||
def test_over_receipt_needs_confirm(self):
|
||||
from app.modules.inout.db import OverReceipt
|
||||
|
||||
o = self.order([("MT-C", 10)])
|
||||
ids = self.line_ids(o["id"])
|
||||
with self.assertRaises(OverReceipt) as ctx:
|
||||
self.st.add_receipt(o["id"], {ids["MT-C"]: "12"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x")
|
||||
self.assertEqual(ctx.exception.over[0]["over"], 2)
|
||||
self.assertEqual(self.st.get_order(o["id"])["summary"]["received"], 0) # 확인 전엔 아무것도 저장 안 함
|
||||
self.st.add_receipt(o["id"], {ids["MT-C"]: "12"}, receipt_date="2026-10-20", memo="", confirm_over=True, by="w@x")
|
||||
got = self.st.get_order(o["id"])
|
||||
self.assertEqual((got["status"], got["lines"][0]["over"]), ("over", 2))
|
||||
self.assertEqual([r["item_code"] for r in self.st.outstanding(factory_id=self.fid)["over"]
|
||||
if r["order_id"] == o["id"]], ["MT-C"])
|
||||
|
||||
def test_outstanding_close_reopen_cancel(self):
|
||||
o = self.order([("MT-D", 30), ("MT-E", 5)])
|
||||
ids = self.line_ids(o["id"])
|
||||
self.st.add_receipt(o["id"], {ids["MT-D"]: "10"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x")
|
||||
pend = [r for r in self.st.outstanding(factory_id=self.fid)["pending"] if r["order_id"] == o["id"]]
|
||||
self.assertEqual({r["item_code"]: r["remaining"] for r in pend}, {"MT-D": 20, "MT-E": 5})
|
||||
self.assertTrue(self.st.outstanding(q="MT-E")["pending"])
|
||||
self.st.set_closed(o["id"], closed=True, reason="공장 단종", by="boss@x")
|
||||
self.assertEqual(self.st.get_order(o["id"])["status"], "closed")
|
||||
self.assertFalse([r for r in self.st.outstanding(factory_id=self.fid)["pending"] if r["order_id"] == o["id"]])
|
||||
with self.assertRaisesRegex(ValueError, "종결"):
|
||||
self.st.add_receipt(o["id"], {ids["MT-E"]: "1"}, receipt_date="2026-10-21", memo="", confirm_over=False, by="w@x")
|
||||
self.st.set_closed(o["id"], closed=False, by="boss@x")
|
||||
self.assertEqual(self.st.get_order(o["id"])["status"], "partial")
|
||||
with self.assertRaisesRegex(ValueError, "입고 기록이 있는"):
|
||||
self.st.cancel_order(o["id"], by="boss@x")
|
||||
o2 = self.order([("MT-F", 1)])
|
||||
self.st.cancel_order(o2["id"], by="boss@x")
|
||||
self.assertEqual(self.st.get_order(o2["id"])["status"], "cancelled")
|
||||
self.assertIn(o2["id"], [x["id"] for x in self.st.list_orders(status="closed", factory_id=self.fid)])
|
||||
|
||||
def test_update_order_keeps_received_lines(self):
|
||||
from app.modules.inout import store
|
||||
|
||||
o = self.order([("MT-G", 10), ("MT-H", 10)])
|
||||
ids = self.line_ids(o["id"])
|
||||
self.st.add_receipt(o["id"], {ids["MT-G"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x")
|
||||
drop_g = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="",
|
||||
codes=["MT-H"], quantities=["10"])
|
||||
with self.assertRaisesRegex(ValueError, "MT-G"):
|
||||
self.st.update_order(o["id"], drop_g, {}, by="boss@x")
|
||||
change = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="2026-11-05", memo="수정",
|
||||
codes=["MT-G", "MT-I"], quantities=["3", "7"])
|
||||
self.st.update_order(o["id"], change, {"MT-I": "새 제품"}, by="boss@x")
|
||||
got = self.st.get_order(o["id"])
|
||||
self.assertEqual([(x["item_code"], x["qty"], x["received"]) for x in got["lines"]], [("MT-G", 3, 4), ("MT-I", 7, 0)])
|
||||
self.assertEqual(got["lines"][0]["status"], "over") # 수량을 입고보다 줄이면 초과로 보임
|
||||
self.assertEqual((got["memo"], str(got["due_date"])), ("수정", "2026-11-05"))
|
||||
|
||||
def test_delete_receipt_restores_remaining(self):
|
||||
o = self.order([("MT-J", 10)])
|
||||
ids = self.line_ids(o["id"])
|
||||
r = self.st.add_receipt(o["id"], {ids["MT-J"]: "10"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x")
|
||||
self.st.delete_receipt(o["id"], r["id"], by="w@x")
|
||||
got = self.st.get_order(o["id"])
|
||||
self.assertEqual((got["status"], got["summary"]["remaining"], got["receipts"]), ("open", 10, []))
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.delete_receipt(o["id"], r["id"], by="w@x")
|
||||
|
||||
def test_order_numbers_per_day_and_concurrent(self):
|
||||
nos = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def make():
|
||||
n = self.order([("MT-K", 1)], order_date="2026-03-03")["order_no"]
|
||||
with lock:
|
||||
nos.append(n)
|
||||
|
||||
threads = [threading.Thread(target=make) for _ in range(5)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
self.assertEqual(len(set(nos)), 5) # 동시에 만들어도 번호 겹치지 않음
|
||||
self.assertTrue(all(n.startswith("PO-260303-") for n in nos))
|
||||
|
||||
def test_roles_and_factories(self):
|
||||
self.st.set_role_members("order", ["Boss@Test.local", " a@x "], by="admin@x")
|
||||
self.st.set_role_members("receive", ["w@x"], by="admin@x")
|
||||
self.assertEqual(self.st.list_roles()["order"], ["a@x", "boss@test.local"])
|
||||
self.assertEqual(self.st.roles_of("BOSS@test.local"), {"order"})
|
||||
self.st.set_role_members("order", ["a@x"], by="admin@x") # 통째로 바꿈
|
||||
self.assertEqual(self.st.list_roles()["order"], ["a@x"])
|
||||
with self.assertRaisesRegex(ValueError, "같은 이름"):
|
||||
self.st.save_factory(factory_id=None, name=f"테스트공장-{self.tag}".upper())
|
||||
with self.assertRaisesRegex(ValueError, "발주 기록"):
|
||||
self.order([("MT-L", 1)])
|
||||
self.st.delete_factory(self.fid)
|
||||
fid2 = self.st.save_factory(factory_id=None, name=f"빈공장-{self.tag}")
|
||||
self.st.delete_factory(fid2)
|
||||
self.assertNotIn(fid2, [f["id"] for f in self.st.list_factories(include_inactive=True)])
|
||||
off = self.st.save_factory(factory_id=None, name=f"숨김공장-{self.tag}", is_active=False)
|
||||
self.assertNotIn(off, [f["id"] for f in self.st.list_factories()])
|
||||
with self.assertRaisesRegex(ValueError, "사용하지 않는 공장"):
|
||||
self.order([("MT-M", 1)], factory_id=off)
|
||||
|
||||
# ── 003: 입고증 사진 · 공장 이메일 · Gmail 연결 · 메일 기록 ──
|
||||
def test_receipt_photos_atomic_limit_delete(self):
|
||||
from app.modules.inout import store
|
||||
|
||||
jpeg = b"\xff\xd8\xff\xe0" + b"1" * 100
|
||||
o = self.order([("MT-P", 10)])
|
||||
ids = self.line_ids(o["id"])
|
||||
photos = store.validate_photos([("a.jpg", jpeg), ("b.jpg", jpeg)])
|
||||
r = self.st.add_receipt(o["id"], {ids["MT-P"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False,
|
||||
by="w@x", photos=photos)
|
||||
self.assertEqual(r["photos"], 2)
|
||||
got = self.st.get_order(o["id"])
|
||||
ph = got["receipts"][0]["photos"]
|
||||
self.assertEqual([(p["filename"], p["content_type"], p["size_bytes"]) for p in ph], [("a.jpg", "image/jpeg", 104), ("b.jpg", "image/jpeg", 104)])
|
||||
self.assertNotIn("data", ph[0]) # 목록엔 내용 없음
|
||||
one = self.st.get_photo(ph[0]["id"])
|
||||
self.assertEqual((bytes(one["data"]), one["order_id"]), (jpeg, o["id"]))
|
||||
# 초과 확인 전에 막히면 사진도 저장 안 됨(한 트랜잭션)
|
||||
from app.modules.inout.db import OverReceipt
|
||||
with self.assertRaises(OverReceipt):
|
||||
self.st.add_receipt(o["id"], {ids["MT-P"]: "99"}, receipt_date="2026-10-21", memo="", confirm_over=False, by="w@x",
|
||||
photos=store.validate_photos([("c.jpg", jpeg)]))
|
||||
self.assertEqual(sum(len(x["photos"]) for x in self.st.get_order(o["id"])["receipts"]), 2)
|
||||
# 나중에 더하기 — 10장 한도는 이미 있는 장수와 합쳐서
|
||||
rid = got["receipts"][0]["id"]
|
||||
self.assertEqual(self.st.add_receipt_photos(o["id"], rid, [("d.jpg", jpeg)] * 8, by="w@x"), 8)
|
||||
with self.assertRaisesRegex(ValueError, "10장"):
|
||||
self.st.add_receipt_photos(o["id"], rid, [("e.jpg", jpeg)], by="w@x")
|
||||
with self.assertRaisesRegex(ValueError, "찾을 수 없"):
|
||||
self.st.add_receipt_photos(o["id"], 999999, [("e.jpg", jpeg)], by="w@x")
|
||||
self.st.delete_receipt_photo(o["id"], ph[0]["id"])
|
||||
self.assertIsNone(self.st.get_photo(ph[0]["id"]))
|
||||
o2 = self.order([("MT-Q", 1)])
|
||||
with self.assertRaisesRegex(ValueError, "찾을 수 없"): # 다른 발주서의 사진 id 로는 못 지운다
|
||||
self.st.delete_receipt_photo(o2["id"], ph[1]["id"])
|
||||
self.st.delete_receipt(o["id"], rid, by="w@x") # 입고를 지우면 사진도 함께
|
||||
self.assertIsNone(self.st.get_photo(ph[1]["id"]))
|
||||
|
||||
def test_factory_email_gmail_tokens_and_mail_log(self):
|
||||
fid = self.st.save_factory(factory_id=None, name=f"메일공장-{self.tag}", manager="박과장", email="a@x.com; b@y.co.kr")
|
||||
f = next(x for x in self.st.list_factories() if x["id"] == fid)
|
||||
self.assertEqual(f["email"], "a@x.com, b@y.co.kr")
|
||||
with self.assertRaisesRegex(ValueError, "공장 이메일 형식"):
|
||||
self.st.save_factory(factory_id=fid, name=f"메일공장-{self.tag}", email="not-an-email")
|
||||
o = self.order([("MT-M", 3)], factory_id=fid)
|
||||
self.assertEqual(self.st.get_order(o["id"])["factory_email"], "a@x.com, b@y.co.kr")
|
||||
me = f"Buyer-{self.tag}@X.com"
|
||||
self.assertIsNone(self.st.gmail_token(me))
|
||||
self.st.save_gmail_token(me, refresh_token_enc="v1:enc1", scopes="openid email gmail.send")
|
||||
self.st.save_gmail_token(me, refresh_token_enc="v1:enc2", scopes="openid email gmail.send") # 다시 연결 = 덮어씀
|
||||
tok = self.st.gmail_token(me.upper())
|
||||
self.assertEqual((tok["email"], tok["refresh_token_enc"]), (me.lower(), "v1:enc2"))
|
||||
self.st.mark_gmail(me, error="Gmail 오류")
|
||||
self.assertEqual(self.st.gmail_token(me)["last_error"], "Gmail 오류")
|
||||
self.st.mark_gmail(me)
|
||||
tok = self.st.gmail_token(me)
|
||||
self.assertEqual(tok["last_error"], "")
|
||||
self.assertIsNotNone(tok["last_used_at"])
|
||||
self.st.add_order_mail(o["id"], sent_by=me, to=["a@x.com"], cc=["c@z.com"], subject="[발주] x", gmail_id="18f")
|
||||
mails = self.st.get_order(o["id"])["mails"]
|
||||
self.assertEqual([(m["to_addrs"], m["cc_addrs"], m["gmail_id"]) for m in mails], [("a@x.com", "c@z.com", "18f")])
|
||||
self.st.delete_gmail_token(me)
|
||||
self.assertIsNone(self.st.gmail_token(me))
|
||||
|
||||
|
||||
def test_times_are_kst(self):
|
||||
"""TIMESTAMPTZ 는 한국 시각으로 읽힌다(화면·메일에 찍는 입력·보낸 시각) — DB 서버 시간대와 무관."""
|
||||
from datetime import timedelta
|
||||
|
||||
o = self.order([("MT-K", 1)])
|
||||
self.assertEqual(self.st.get_order(o["id"])["created_at"].utcoffset(), timedelta(hours=9))
|
||||
|
||||
def test_products_import_keep_exclude_snapshot(self):
|
||||
"""004 — 불러오기(값 있는 상품은 그대로·없는 상품은 새 이름·지운 단품은 건너뜀), 지우기·되살리기, 발주 품목 값 사본.
|
||||
끝나면 테스트 단품을 지워 상품 정보 목록을 처음 상태로 둔다(다른 테스트는 빈 목록 = 코드표를 가정할 수 있음)."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
from app.modules.inout import store
|
||||
|
||||
if not self.st.products_ready():
|
||||
self.skipTest("inout_db 004 미적용")
|
||||
T = self.tag.upper()
|
||||
A, B, C = f"ZT-{T}-A", f"ZT-{T}-B", f"ZT-{T}-C"
|
||||
items = [{"code": A.lower(), "name": "가"}, {"code": B, "name": "나"}, {"code": C, "name": "다"}]
|
||||
before = self.st.catalog_count()
|
||||
try:
|
||||
r = self.st.import_products(items, by="Boss@Test.local")
|
||||
self.assertEqual(r["added"], 3)
|
||||
self.assertEqual(self.st.catalog_count(), before + 3)
|
||||
self.st.save_products([{"code": A, **store.validate_product_values({"unit_price": "1,500", "weight_g": "24.5",
|
||||
"silver_pct": "0.5"})}], by="b@x")
|
||||
with self.assertRaisesRegex(ValueError, "상품 정보에 없는"):
|
||||
self.st.save_products([{"code": "ZT-NOPE-" + T, "unit_price": None, "weight_g": None, "silver_pct": None}], by="b@x")
|
||||
# 이름이 바뀌어 다시 불러오기 — A(값 있음)는 그대로, B(값 없음)는 새 이름
|
||||
r = self.st.import_products([{"code": A, "name": "가2"}, {"code": B, "name": "나2"}, {"code": C, "name": "다"}], by="b@x")
|
||||
self.assertEqual((r["added"], r["kept"], r["renamed"], r["same"]), (0, 1, 1, 1))
|
||||
got = self.st.catalog_lookup([A, B])
|
||||
self.assertEqual((got[A]["item_name"], got[A]["unit_price"]), ("가", D("1500.00")))
|
||||
self.assertEqual(got[B]["item_name"], "나2")
|
||||
# 지우기 → 목록·검색에서 빠지고 다음 불러오기에서도 건너뜀 → 되살리기
|
||||
self.st.exclude_product(C, by="b@x")
|
||||
self.assertNotIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertIn(C, [x["item_code"] for x in self.st.list_excluded()])
|
||||
self.assertEqual(self.st.import_products(items, by="b@x")["excluded"], 1)
|
||||
self.assertNotIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertEqual([x["item_code"] for x in self.st.catalog_search(f"ZT-{T}")], [A, B])
|
||||
self.assertEqual([x["item_code"] for x in self.st.catalog_search("가", limit=500) if x["item_code"].startswith("ZT-" + T)], [A])
|
||||
self.st.restore_product(C, by="b@x")
|
||||
self.assertIn(C, self.st.catalog_lookup([C]))
|
||||
self.assertNotIn(C, [x["item_code"] for x in self.st.list_excluded()])
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.restore_product(C, by="b@x")
|
||||
# 발주 품목 = 발주할 때의 값(사본) — 나중에 단가가 바뀌어도 지난 발주서는 그대로
|
||||
data = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="",
|
||||
codes=[A, B], quantities=["100", "3"])
|
||||
specs = self.st.catalog_lookup([A, B])
|
||||
o = self.st.create_order(data, {A: "가", B: "나2"}, by="b@x", specs=specs)
|
||||
self.st.save_products([{"code": A, **store.validate_product_values({"unit_price": "2000"})}], by="b@x")
|
||||
lines = {x["item_code"]: x for x in self.st.get_order(o["id"])["lines"]}
|
||||
self.assertEqual((lines[A]["unit_price"], lines[A]["weight_g"], lines[A]["silver_pct"]), (D("1500.00"), D("24.50"), D("0.5000")))
|
||||
self.assertIsNone(lines[B]["unit_price"])
|
||||
t = store.order_totals(list(lines.values()))
|
||||
self.assertEqual((t["amount"], t["missing_price"], t["silver_g"]), (D("150000.00"), 1, D("12.2500")))
|
||||
# 고칠 때 새로 넣은 줄만 지금 값, 원래 있던 줄은 사본 그대로
|
||||
data2 = store.validate_order(factory_id=self.fid, order_date="2026-10-16", due_date="", memo="",
|
||||
codes=[A, C], quantities=["120", "1"])
|
||||
self.st.update_order(o["id"], data2, {C: "다"}, by="b@x", specs=self.st.catalog_lookup([C]))
|
||||
lines = {x["item_code"]: x for x in self.st.get_order(o["id"])["lines"]}
|
||||
self.assertEqual((lines[A]["qty"], lines[A]["unit_price"]), (120, D("1500.00")))
|
||||
self.assertEqual(set(lines), {A, C})
|
||||
finally:
|
||||
for code in (A, B, C):
|
||||
try:
|
||||
self.st.exclude_product(code, by="cleanup@x")
|
||||
except ValueError:
|
||||
pass
|
||||
self.assertEqual(self.st.catalog_count(), before)
|
||||
|
||||
|
||||
def test_delete_order_cascades(self):
|
||||
"""수퍼관리자 발주 삭제 — 품목·입고 기록·입고증 사진·메일 기록까지 함께 지워진다."""
|
||||
o = self.order([("MT-D", 10), ("MT-E", 5)])
|
||||
ids = self.line_ids(o["id"])
|
||||
rid = self.st.add_receipt(o["id"], {ids["MT-D"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False, by="w@x")
|
||||
if isinstance(rid, dict):
|
||||
rid = rid.get("receipt_id") or rid.get("id")
|
||||
r = self.st.delete_order(o["id"])
|
||||
self.assertEqual((r["order_no"], r["receipts"]), (o["order_no"], 1))
|
||||
self.assertIsNone(self.st.get_order(o["id"]))
|
||||
with self.st._pool.connection() as conn:
|
||||
left = conn.execute("SELECT (SELECT count(*) FROM inout_order_lines WHERE order_id=%s) + "
|
||||
"(SELECT count(*) FROM inout_receipts WHERE order_id=%s) AS n", (o["id"], o["id"])).fetchone()["n"]
|
||||
self.assertEqual(left, 0)
|
||||
with self.assertRaises(LookupError):
|
||||
self.st.delete_order(o["id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""입출고 003 — 발주 메일(본문·받는 주소·Gmail 연결 검사·토큰·보내기)과 입고증 사진 검사. DB·구글 없이(가짜 구글 서버)."""
|
||||
import base64
|
||||
import email
|
||||
import json
|
||||
import unittest
|
||||
from datetime import date
|
||||
from email import policy
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
|
||||
from app.modules.inout import gmail
|
||||
from app.modules.inout import store as s
|
||||
|
||||
JPEG = b"\xff\xd8\xff\xe0" + b"0" * 64
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
|
||||
|
||||
|
||||
def _order(**over):
|
||||
o = {"order_no": "PO-261016-01", "factory_name": "엘리화학", "factory_manager": "이석준", "order_date": date(2026, 10, 16),
|
||||
"due_date": date(2026, 10, 30), "memo": "박스당 24개<포장>",
|
||||
"lines": [{"item_code": "MT-0320", "item_name": "미라클 통 320ml", "qty": 5000, "memo": ""},
|
||||
{"item_code": "MT-0500", "item_name": "<b>뚜껑</b>", "qty": 1200, "memo": "흰색"}]}
|
||||
o.update(over)
|
||||
return o
|
||||
|
||||
|
||||
class MailContentTests(unittest.TestCase):
|
||||
def test_parse_emails(self):
|
||||
self.assertEqual(s.parse_emails("a@x.com, B@y.co.kr; a@X.com\nc@z.kr"), ["a@x.com", "B@y.co.kr", "c@z.kr"])
|
||||
self.assertEqual(s.parse_emails(""), [])
|
||||
for bad in ("abc", "a@b", "a@@b.com", "a b@c.com"):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
s.parse_emails(bad)
|
||||
with self.assertRaisesRegex(ValueError, "입력하세요"):
|
||||
s.parse_emails(" ", label="받는 사람", required=True)
|
||||
with self.assertRaisesRegex(ValueError, "10개"):
|
||||
s.parse_emails(",".join(f"u{i}@x.com" for i in range(11)))
|
||||
|
||||
def test_order_mail_summary_and_escaping(self):
|
||||
m = s.order_mail(_order(), sender_name="King", sender_email="king@dbxcorp.co.kr")
|
||||
self.assertEqual(m["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml 외 1종")
|
||||
for part in ("이석준님, 안녕하세요.", "발주번호: PO-261016-01", "발주일: 2026.10.16(금)", "입고 예정일: 2026.10.30(금)", "2종 · 총 6,200개",
|
||||
"1. MT-0320 미라클 통 320ml — 5,000개", "(흰색)", "발주 담당: King (king@dbxcorp.co.kr)"):
|
||||
self.assertIn(part, m["text"])
|
||||
h = m["html"]
|
||||
self.assertIn("<b>뚜껑</b>", h) # 제품 이름·메모의 HTML 은 글자로
|
||||
self.assertIn("박스당 24개<포장>", h)
|
||||
self.assertNotIn("<b>뚜껑</b>", h)
|
||||
self.assertIn("6,200", h) and self.assertIn("5,000", h)
|
||||
m2 = s.order_mail(_order(due_date=None, factory_manager="", memo="", lines=_order()["lines"][:1]),
|
||||
sender_name="", sender_email="k@x.com")
|
||||
self.assertEqual(m2["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml")
|
||||
self.assertIn("입고 예정일: 협의", m2["text"])
|
||||
self.assertTrue(m2["text"].startswith("안녕하세요."))
|
||||
self.assertNotIn("요청 사항", m2["text"])
|
||||
|
||||
def test_build_message_utf8_and_alternative(self):
|
||||
raw = gmail.build_message(sender_name="킹", sender_email="king@dbxcorp.co.kr", to=["a@x.com", "b@y.com"], cc=["c@z.com"],
|
||||
subject="[발주] 테스트 · 한글", text="본문", html="<p>본문</p>")
|
||||
msg = email.message_from_bytes(raw, policy=policy.default)
|
||||
self.assertEqual(msg["Subject"], "[발주] 테스트 · 한글")
|
||||
self.assertEqual((msg["To"], msg["Cc"]), ("a@x.com, b@y.com", "c@z.com"))
|
||||
self.assertIn("king@dbxcorp.co.kr", msg["From"])
|
||||
self.assertEqual([p.get_content_type() for p in msg.iter_parts()], ["text/plain", "text/html"])
|
||||
|
||||
|
||||
class PhotoTests(unittest.TestCase):
|
||||
def test_sniff(self):
|
||||
self.assertEqual(s.sniff_image(JPEG), "image/jpeg")
|
||||
self.assertEqual(s.sniff_image(PNG), "image/png")
|
||||
self.assertEqual(s.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp")
|
||||
self.assertEqual(s.sniff_image(b"GIF89a..."), "image/gif")
|
||||
self.assertEqual(s.sniff_image(b"\x00\x00\x00\x18ftypheic...."), "image/heic")
|
||||
self.assertIsNone(s.sniff_image(b"%PDF-1.4"))
|
||||
self.assertIsNone(s.sniff_image(b"<svg xmlns=...")) # SVG(스크립트 가능)는 받지 않는다
|
||||
|
||||
def test_validate(self):
|
||||
out = s.validate_photos([("C:\\폰\\IMG_1.jpg", JPEG), ("empty.jpg", b""), ("b.png", PNG)])
|
||||
self.assertEqual([(x["filename"], x["content_type"]) for x in out], [("IMG_1.jpg", "image/jpeg"), ("b.png", "image/png")])
|
||||
with self.assertRaisesRegex(ValueError, "사진 파일"):
|
||||
s.validate_photos([("x.pdf", b"%PDF-1.4")])
|
||||
with self.assertRaisesRegex(ValueError, "너무 큽니다"):
|
||||
s.validate_photos([("big.jpg", JPEG + b"0" * s.MAX_PHOTO_BYTES)])
|
||||
with self.assertRaisesRegex(ValueError, "10장"):
|
||||
s.validate_photos([("a.jpg", JPEG)] * 3, existing=8)
|
||||
|
||||
|
||||
class GmailTests(unittest.TestCase):
|
||||
def test_check_grant(self):
|
||||
ok = {"userinfo": {"email": "King@dbxcorp.co.kr"}, "scope": f"openid email {gmail.GMAIL_SCOPE}", "refresh_token": "1//r"}
|
||||
self.assertEqual(gmail.check_grant(ok, expected_email="king@dbxcorp.co.kr"), ("1//r", ok["scope"]))
|
||||
with self.assertRaisesRegex(gmail.GmailError, "다른 구글 계정"):
|
||||
gmail.check_grant({**ok, "userinfo": {"email": "me@gmail.com"}}, expected_email="king@dbxcorp.co.kr")
|
||||
with self.assertRaisesRegex(gmail.GmailError, "gmail.send"):
|
||||
gmail.check_grant({**ok, "scope": "openid email"}, expected_email="king@dbxcorp.co.kr")
|
||||
with self.assertRaisesRegex(gmail.GmailError, "갱신 토큰"):
|
||||
gmail.check_grant({**ok, "refresh_token": ""}, expected_email="king@dbxcorp.co.kr")
|
||||
|
||||
def test_token_encryption_roundtrip_and_aad(self):
|
||||
env = {"APP_ENCRYPTION_KEY": "11" * 32, "APP_ENCRYPTION_KEY_VERSION": "1"}
|
||||
with patch.dict("os.environ", env):
|
||||
enc = gmail.encrypt_token("King@x.com", "1//refresh-secret")
|
||||
self.assertNotIn("refresh-secret", enc)
|
||||
self.assertEqual(gmail.decrypt_token("king@x.com", enc), "1//refresh-secret")
|
||||
with self.assertRaises(gmail.GmailNotConnected): # 남의 이메일 이름으로는 못 푼다(AAD)
|
||||
gmail.decrypt_token("other@x.com", enc)
|
||||
with patch.dict("os.environ", {"APP_ENCRYPTION_KEY": ""}), self.assertRaisesRegex(gmail.GmailError, "암호화 키"):
|
||||
gmail.encrypt_token("k@x.com", "r")
|
||||
|
||||
def _fake(self, handler):
|
||||
return patch.object(gmail, "_http", lambda: httpx.Client(transport=httpx.MockTransport(handler)))
|
||||
|
||||
def test_send_refreshes_and_posts_raw(self):
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req)
|
||||
if req.url.host == "oauth2.googleapis.com":
|
||||
return httpx.Response(200, json={"access_token": "ya29.A", "expires_in": 3600})
|
||||
return httpx.Response(200, json={"id": "18f-msg", "threadId": "t"})
|
||||
|
||||
with self._fake(handler), patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"}.get(k, d)):
|
||||
gid = gmail.send("1//r", b"Subject: x\r\n\r\nbody")
|
||||
self.assertEqual(gid, "18f-msg")
|
||||
form = dict(x.split("=", 1) for x in seen[0].content.decode().split("&"))
|
||||
self.assertEqual((form["grant_type"], form["refresh_token"], form["client_id"]), ("refresh_token", "1%2F%2Fr", "cid"))
|
||||
self.assertEqual(seen[1].headers["Authorization"], "Bearer ya29.A")
|
||||
self.assertEqual(base64.urlsafe_b64decode(json.loads(seen[1].content)["raw"]), b"Subject: x\r\n\r\nbody")
|
||||
|
||||
def test_errors(self):
|
||||
env = patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "c", "GOOGLE_CLIENT_SECRET": "s"}.get(k, d))
|
||||
revoked = lambda req: httpx.Response(400, json={"error": "invalid_grant", "error_description": "Token has been expired or revoked."}) # noqa: E731
|
||||
with self._fake(revoked), env, self.assertRaisesRegex(gmail.GmailNotConnected, "끊겼습니다"):
|
||||
gmail.send("1//r", b"x")
|
||||
|
||||
def no_api(req):
|
||||
if req.url.host == "oauth2.googleapis.com":
|
||||
return httpx.Response(200, json={"access_token": "a"})
|
||||
return httpx.Response(403, json={"error": {"message": "Gmail API has not been used in project 1 before or it is disabled."}})
|
||||
with self._fake(no_api), env, self.assertRaisesRegex(gmail.GmailError, "Gmail API 가 꺼져"):
|
||||
gmail.send("1//r", b"x")
|
||||
|
||||
def scope(req):
|
||||
if req.url.host == "oauth2.googleapis.com":
|
||||
return httpx.Response(200, json={"access_token": "a"})
|
||||
return httpx.Response(403, json={"error": {"message": "Request had insufficient authentication scopes."}})
|
||||
with self._fake(scope), env, self.assertRaises(gmail.GmailNotConnected):
|
||||
gmail.send("1//r", b"x")
|
||||
|
||||
def down(req):
|
||||
raise httpx.ConnectError("x")
|
||||
with self._fake(down), env, self.assertRaisesRegex(gmail.GmailError, "ConnectError"):
|
||||
gmail.send("1//r", b"x")
|
||||
|
||||
|
||||
class MailPriceTests(unittest.TestCase):
|
||||
"""004 — 메일 본문에 금액(수량 × 단가)·PP(g/개)·은(Ag) 함유량(%·g)과 합계."""
|
||||
|
||||
def test_order_mail_prices(self):
|
||||
from decimal import Decimal as D
|
||||
o = _order()
|
||||
o["lines"][0].update(unit_price=D("85.5"), weight_g=D("24.5"), silver_pct=D("0.5"))
|
||||
m = s.order_mail(o, sender_name="K", sender_email="k@x.com")
|
||||
for part in ("발주 금액: 427,500원 (단가 미입력 1종 제외)", "PP 총량: 122.5 kg", "은(Ag) 총량: 612.5 g",
|
||||
"단가 85.5 · 금액 427,500 · PP 24.5g · 은 0.5% (0.1225g)", "단가 - · 금액 - · PP - · 은 -"):
|
||||
self.assertIn(part, m["text"])
|
||||
h = m["html"]
|
||||
for part in ("단가(원)", "금액(원)", "PP(g/개)", "은(Ag) 함유량", "427,500", "0.5% (0.1225g)", "122.5 kg", "612.5 g"):
|
||||
self.assertIn(part, h)
|
||||
o2 = _order() # 단가가 하나도 없으면 금액 줄은 "-"
|
||||
t2 = s.order_mail(o2, sender_name="K", sender_email="k@x.com")["text"]
|
||||
self.assertNotIn("PP 총량", t2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""입출고 관리 — 상태 계산·입력 검사(순수 함수, DB 없음)."""
|
||||
import unittest
|
||||
from datetime import date
|
||||
|
||||
from app.modules.inout import store as s
|
||||
|
||||
|
||||
class StatusTests(unittest.TestCase):
|
||||
def test_line_status(self):
|
||||
self.assertEqual([s.line_status(10, r) for r in (0, 4, 10, 12)], ["none", "partial", "done", "over"])
|
||||
|
||||
def test_order_status(self):
|
||||
L = lambda *pairs: [{"qty": q, "received": r} for q, r in pairs] # noqa: E731
|
||||
self.assertEqual(s.order_status(L((10, 0), (5, 0))), "open")
|
||||
self.assertEqual(s.order_status(L((10, 10), (5, 0))), "partial") # 하나라도 남으면 부분입고
|
||||
self.assertEqual(s.order_status(L((10, 12), (5, 3))), "partial") # 초과가 있어도 남은 게 있으면 부분입고
|
||||
self.assertEqual(s.order_status(L((10, 10), (5, 5))), "done")
|
||||
self.assertEqual(s.order_status(L((10, 11), (5, 5))), "over")
|
||||
self.assertEqual(s.order_status(L((10, 3)), closed=True), "closed")
|
||||
self.assertEqual(s.order_status(L((10, 3)), closed=True, cancelled=True), "cancelled")
|
||||
self.assertEqual(s.order_status([]), "open")
|
||||
|
||||
def test_summarize_never_negative(self):
|
||||
out = s.summarize([{"qty": 10, "received": 12}, {"qty": 5, "received": 1}])
|
||||
self.assertEqual(out, {"ordered": 15, "received": 13, "remaining": 4, "over": 2, "pct": 87})
|
||||
self.assertEqual(s.summarize([{"qty": 1, "received": 5}])["pct"], 100) # 막대는 100% 에서 멈춤
|
||||
self.assertEqual(s.summarize([])["pct"], 0)
|
||||
|
||||
def test_date_format(self):
|
||||
"""날짜 서식 yyyy.mm.dd(요일) — 2026-10-17 요청."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
self.assertEqual(s.fmt_date(date(2026, 10, 17)), "2026.10.17(토)")
|
||||
self.assertEqual(s.fmt_date(date(2026, 10, 19)), "2026.10.19(월)")
|
||||
self.assertEqual(s.fmt_date(None), "")
|
||||
kst = timezone(timedelta(hours=9))
|
||||
self.assertEqual(s.fmt_datetime(datetime(2026, 10, 18, 9, 5, tzinfo=kst)), "2026.10.18(일) 09:05")
|
||||
self.assertEqual(s.fmt_datetime(None), "")
|
||||
|
||||
def test_all_received_label(self):
|
||||
"""모든 품목이 입고완료·초과입고면 '전체 입고 완료'."""
|
||||
self.assertEqual(s.ORDER_LABELS[s.ST_DONE], "전체 입고 완료")
|
||||
self.assertEqual(s.ORDER_LABELS[s.ST_OVER], "전체 입고 완료")
|
||||
|
||||
def test_order_no(self):
|
||||
self.assertEqual(s.order_no(date(2026, 10, 6), 3), "PO-261006-03")
|
||||
self.assertEqual(s.order_no(date(2026, 10, 6), 123), "PO-261006-123")
|
||||
|
||||
|
||||
class ValidateOrderTests(unittest.TestCase):
|
||||
def v(self, **over):
|
||||
args = dict(factory_id="1", order_date="2026-10-16", due_date="2026-10-30", memo=" 메모 ",
|
||||
codes=["mt-a ", "", "MT-B"], quantities=["1,200", "", "5"], line_memos=["a", "", ""])
|
||||
args.update(over)
|
||||
return s.validate_order(**args)
|
||||
|
||||
def test_ok_normalizes(self):
|
||||
d = self.v()
|
||||
self.assertEqual(d["factory_id"], 1)
|
||||
self.assertEqual(d["memo"], "메모")
|
||||
self.assertEqual([(x["item_code"], x["qty"], x["memo"]) for x in d["lines"]], [("MT-A", 1200, "a"), ("MT-B", 5, "")])
|
||||
|
||||
def test_errors_listed_together(self):
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
self.v(factory_id="", due_date="2026-10-01", codes=["MT-A", "mt-a", ""], quantities=["0", "3", "7"])
|
||||
msg = str(ctx.exception)
|
||||
for part in ("공장을 고르세요", "입고 예정일이 발주일보다 빠릅니다", "1 이상", "같은 제품이 두 줄", "3번째 줄: 제품을 고르세요"):
|
||||
self.assertIn(part, msg)
|
||||
|
||||
def test_empty_and_bad_values(self):
|
||||
with self.assertRaisesRegex(ValueError, "한 줄 이상"):
|
||||
self.v(codes=["", ""], quantities=["", ""])
|
||||
with self.assertRaisesRegex(ValueError, "정수"):
|
||||
self.v(codes=["MT-A"], quantities=["1.5"])
|
||||
with self.assertRaisesRegex(ValueError, "너무 큽니다"):
|
||||
self.v(codes=["MT-A"], quantities=[str(s.MAX_QTY + 1)])
|
||||
with self.assertRaisesRegex(ValueError, "발주일 형식"):
|
||||
self.v(order_date="16/10/2026")
|
||||
self.assertIsNone(self.v(due_date="")["due_date"])
|
||||
|
||||
|
||||
class ValidateReceiptTests(unittest.TestCase):
|
||||
LINES = [{"id": 1, "item_code": "MT-A", "item_name": "가", "qty": 10, "received": 8},
|
||||
{"id": 2, "item_code": "MT-B", "item_name": "나", "qty": 5, "received": 0}]
|
||||
|
||||
def test_partial_zero_and_over(self):
|
||||
d = s.validate_receipt(self.LINES, {1: "3", 2: "0"}, receipt_date="2026-10-20", memo="")
|
||||
self.assertEqual(d["items"], [{"order_line_id": 1, "qty": 3}]) # 0·빈칸은 이번에 안 들어온 것
|
||||
self.assertEqual(d["over"], [{"item_code": "MT-A", "item_name": "가", "ordered": 10, "after": 11, "over": 1}])
|
||||
d = s.validate_receipt(self.LINES, {1: "2", 2: ""}, receipt_date="2026-10-20", memo="")
|
||||
self.assertEqual(d["over"], []) # 딱 맞으면 초과 아님
|
||||
|
||||
def test_errors(self):
|
||||
with self.assertRaisesRegex(ValueError, "한 품목 이상"):
|
||||
s.validate_receipt(self.LINES, {1: "", 2: "0"}, receipt_date="2026-10-20", memo="")
|
||||
with self.assertRaisesRegex(ValueError, "없는 품목"):
|
||||
s.validate_receipt(self.LINES, {99: "1"}, receipt_date="2026-10-20", memo="")
|
||||
with self.assertRaisesRegex(ValueError, "입고일"):
|
||||
s.validate_receipt(self.LINES, {1: "1"}, receipt_date="", memo="")
|
||||
with self.assertRaisesRegex(ValueError, "0 이상"): # 입고는 0(이번에 안 옴)까지 허용
|
||||
s.validate_receipt(self.LINES, {1: "-1"}, receipt_date="2026-10-20", memo="")
|
||||
|
||||
|
||||
class ProductValueTests(unittest.TestCase):
|
||||
"""004 상품 정보 — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%), 은 g 은 무게 × % 로 계산."""
|
||||
|
||||
def test_fmt_num(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.fmt_num(D("1234.50")), "1,234.5")
|
||||
self.assertEqual(s.fmt_num(D("1500.00")), "1,500")
|
||||
self.assertEqual(s.fmt_num(D("0.12345"), 4), "0.1235") # 사사오입
|
||||
self.assertEqual(s.fmt_num(None), "")
|
||||
self.assertEqual(s.fmt_num(""), "")
|
||||
|
||||
def test_silver_and_amount(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.silver_g(D("24.5"), D("0.5")), D("0.1225"))
|
||||
self.assertIsNone(s.silver_g(None, D("0.5")))
|
||||
self.assertIsNone(s.silver_g(D("24.5"), None))
|
||||
self.assertEqual(s.line_amount(100, D("85.5")), D("8550.00"))
|
||||
self.assertIsNone(s.line_amount(100, None))
|
||||
|
||||
def test_order_totals(self):
|
||||
from decimal import Decimal as D
|
||||
t = s.order_totals([{"qty": 100, "unit_price": D("85.5"), "weight_g": D("24.5"), "silver_pct": D("0.5")},
|
||||
{"qty": 10, "unit_price": None, "weight_g": None, "silver_pct": None}])
|
||||
self.assertEqual((t["amount"], t["missing_price"], t["pp_kg"], t["silver_g"]), (D("8550.00"), 1, D("2.45"), D("12.25")))
|
||||
empty = s.order_totals([{"qty": 5}]) # 004 전 발주서(값 칸 없음)
|
||||
self.assertEqual((empty["amount"], empty["missing_price"], empty["pp_kg"], empty["silver_g"]), (None, 1, None, None))
|
||||
|
||||
def test_parse_and_validate(self):
|
||||
from decimal import Decimal as D
|
||||
self.assertEqual(s.parse_decimal("1,500", key="unit_price"), D("1500"))
|
||||
self.assertEqual(s.parse_decimal(" 0.5 % ", key="silver_pct"), D("0.5"))
|
||||
self.assertIsNone(s.parse_decimal("", key="weight_g")) # 빈칸 = 미입력
|
||||
self.assertEqual(s.parse_decimal("1.235", key="unit_price"), D("1.24")) # 소수 자리 넘치면 사사오입
|
||||
for key, bad in (("unit_price", "abc"), ("unit_price", "-1"), ("silver_pct", "101"), ("weight_g", "NaN")):
|
||||
with self.subTest(key=key, bad=bad), self.assertRaises(ValueError):
|
||||
s.parse_decimal(bad, key=key)
|
||||
v = s.validate_product_values({"unit_price": "1,500", "weight_g": "24.5", "silver_pct": ""})
|
||||
self.assertEqual(v, {"unit_price": D("1500"), "weight_g": D("24.5"), "silver_pct": None})
|
||||
with self.assertRaisesRegex(ValueError, "은 함유량"):
|
||||
s.validate_product_values({"silver_pct": "200"})
|
||||
self.assertTrue(s.has_values({"weight_g": D("1")}))
|
||||
self.assertFalse(s.has_values({"unit_price": None, "item_name": "x"}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,446 @@
|
||||
"""입출고 관리 — 실제 앱(메뉴·권한·화면·폼)을 격리된 하위 프로세스에서 확인.
|
||||
|
||||
1) 등록·미설정: 메뉴·관리자 권한 칩·"설정 필요" 화면(DB 없이 늘 실행)
|
||||
2) 전체 흐름(INOUT_TEST_DB_URL 이 localhost 일 때만): 옵션(공장·담당자) → 발주 담당 발주서 작성(코드표 단품만)
|
||||
→ 입고 담당 분할 입고 → 초과 입고 확인 → 미입고 현황 → 잔량 종결, 그리고 권한(조회만·담당 아님 403).
|
||||
코드표(itemcode_db)는 가짜 리더로 바꾼다. 운영 DSN·데이터는 쓰지 않는다.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DSN = os.getenv("INOUT_TEST_DB_URL", "")
|
||||
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
PRELUDE = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
|
||||
def U(email, role="user", inout=True):
|
||||
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False,
|
||||
"modules": {"inout": inout}}
|
||||
|
||||
who = {"u": None}
|
||||
users = []
|
||||
|
||||
class Items:
|
||||
enabled = True
|
||||
reason = ""
|
||||
NAMES = {"MT-A": "가 단품", "MT-B": "나 단품", "MT-C": "다 단품"}
|
||||
def search(self, q, limit=30):
|
||||
return [{"code": c, "name": n} for c, n in self.NAMES.items() if q.upper() in c or q in n]
|
||||
def lookup(self, codes):
|
||||
return {c: self.NAMES[c] for c in codes if c in self.NAMES}
|
||||
def list_all(self, limit=20000):
|
||||
return [{"code": c, "name": n} for c, n in self.NAMES.items()]
|
||||
|
||||
def run(body):
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
|
||||
patch.object(main.user_store, "list_all", side_effect=lambda: users):
|
||||
client = TestClient(main.app)
|
||||
body(client)
|
||||
'''
|
||||
|
||||
|
||||
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
env = dict(os.environ)
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
|
||||
"ITEMCODE", "EXPENSE", "INOUT"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-inout-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
|
||||
env.update(extra_env or {})
|
||||
with tempfile.TemporaryDirectory(prefix="inout-web-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=90)
|
||||
|
||||
|
||||
class InoutWebTests(unittest.TestCase):
|
||||
def test_registered_and_unconfigured(self):
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
admin = U("admin@test.local", role="admin")
|
||||
users.append(admin)
|
||||
who["u"] = admin
|
||||
def body(c):
|
||||
assert "inout" in MODULE_KEYS
|
||||
assert main.MODULE_LABELS["inout"] == "입출고 관리"
|
||||
assert any(x["key"] == "inout" and x["active"] for x in main.build_erp_nav(admin, active="inout"))
|
||||
assert "입출고 관리" in c.get("/admin").text # 관리자 화면 권한 칩
|
||||
r = c.get("/inout/")
|
||||
assert r.status_code == 503 and "INOUT_DB_URL" in r.text, r.status_code # DB 미설정 = 설정 필요 안내
|
||||
assert c.get("/inout/health").json() == {"status": "not_configured"}
|
||||
who["u"] = U("nobody@test.local", inout=False)
|
||||
assert c.get("/inout/").status_code == 403 # 모듈 권한 없음
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
def test_full_flow(self):
|
||||
res = _run('''
|
||||
import re, uuid
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
main.app.state.inout_store = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
|
||||
main.app.state.inout_items = Items()
|
||||
tag = uuid.uuid4().hex[:6]
|
||||
admin, buyer, wh, viewer = (U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag),
|
||||
U("wh-%s@t.local" % tag), U("viewer-%s@t.local" % tag))
|
||||
users.extend([admin, buyer, wh, viewer])
|
||||
|
||||
def body(c):
|
||||
# ── 옵션(톱니 팝업): 공장·담당자(관리자만) ──
|
||||
who["u"] = buyer
|
||||
assert c.get("/inout/settings?panel=1").status_code == 403
|
||||
assert 'id="io-options-btn"' not in c.get("/inout/").text # 관리자 아니면 톱니 없음
|
||||
who["u"] = admin
|
||||
lst = c.get("/inout/").text
|
||||
assert 'id="io-options-btn"' in lst and 'id="io-options"' in lst and ">옵션</a>" not in lst # 탭 대신 톱니 + 팝업
|
||||
r = c.get("/inout/settings", follow_redirects=False) # 예전 주소 = 목록으로 가서 팝업 열기
|
||||
assert r.status_code == 303 and r.headers["location"] == "/inout/?options=1"
|
||||
assert 'data-open="1"' in c.get("/inout/?options=1").text
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert buyer["email"] in panel and "발주 담당" in panel and "<html" not in panel.lower() # 팝업 안 내용만
|
||||
assert 'name="manager"' in panel and 'name="contact"' in panel # 담당자·연락처 따로
|
||||
H = {"X-Inout-Options": "1"}
|
||||
r = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "manager": "김공장", "contact": "010-1", "email": "factory-%s@x.com" % tag,
|
||||
"is_active": "1"}, headers=H)
|
||||
assert r.status_code == 200 and r.json() == {"ok": True, "message": "공장을 저장했습니다."}
|
||||
dup = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "is_active": "1"}, headers=H)
|
||||
assert dup.status_code == 400 and dup.json()["ok"] is False and "같은 이름" in dup.json()["message"]
|
||||
r = c.post("/inout/settings/factories", data={"name": "폼-" + tag, "is_active": "1"}, follow_redirects=False)
|
||||
assert r.status_code == 303 and r.headers["location"].startswith("/inout/?options=1&msg=") # 팝업이 아닌 제출 = 이동
|
||||
fid = next(f["id"] for f in main.app.state.inout_store.list_factories() if f["name"] == "공장-" + tag)
|
||||
f = next(x for x in main.app.state.inout_store.list_factories() if x["id"] == fid)
|
||||
assert (f["manager"], f["contact"]) == ("김공장", "010-1")
|
||||
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]},
|
||||
headers=H).json()["ok"]
|
||||
st = main.app.state.inout_store
|
||||
assert st.roles_of(buyer["email"]) == {"order"} and st.roles_of(wh["email"]) == {"receive"}
|
||||
|
||||
# ── 조회만 하는 사람 ──
|
||||
who["u"] = viewer
|
||||
assert c.get("/inout/").status_code == 200
|
||||
assert c.get("/inout/orders/new").status_code == 403
|
||||
assert "조회만 가능" in c.get("/inout/").text
|
||||
|
||||
# ── 발주 담당: 발주서(코드표 단품만) ──
|
||||
who["u"] = buyer
|
||||
form = c.get("/inout/orders/new").text
|
||||
assert "공장-" + tag in form and "새 발주서" in form
|
||||
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
|
||||
"item_code": ["MT-A", "ZZ-9"], "item_name": ["", ""], "qty": ["100", "5"], "line_memo": ["", ""]})
|
||||
assert bad.status_code == 400 and 'value="ZZ-9"' in bad.text
|
||||
assert "코드표 단품에 없는 제품입니다: ZZ-9" in bad.text or "상품 정보에 없는 단품입니다(옵션 → 상품 정보에서 불러오거나 되살리세요): ZZ-9" in bad.text
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
|
||||
"memo": "1차", "item_code": ["mt-a", "MT-B", ""], "item_name": ["", "", ""], "qty": ["1,00", "50", ""],
|
||||
"line_memo": ["", "포장 주의", ""]}, follow_redirects=False)
|
||||
assert r.status_code == 303, r.text[:300]
|
||||
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
detail = c.get(r.headers["location"]).text
|
||||
assert "김공장 · 010-1" in detail # 공장 담당자·연락처
|
||||
assert "가 단품" in detail and "포장 주의" in detail and "PO-261016-" in detail and "발주서 PO-261016-" in detail
|
||||
assert "이번 입고" not in detail # 발주 담당은 입고 칸이 없다
|
||||
assert c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17"}).status_code == 403
|
||||
|
||||
# ── 입고 담당: 분할 입고 → 초과 확인 ──
|
||||
who["u"] = wh
|
||||
detail = c.get("/inout/orders/%d" % oid).text
|
||||
ids = {code: lid for lid, code in re.findall(r'name="qty_(\\d+)"[^>]*?data-code="(MT-[AB])"', detail, re.S)}
|
||||
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17", "memo": "1차 트럭",
|
||||
"qty_" + ids["MT-A"]: "60"}, follow_redirects=False)
|
||||
assert r.status_code == 303
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert "부분입고" in page and "1차 트럭" in page
|
||||
over = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
|
||||
"qty_" + ids["MT-B"]: "50"})
|
||||
assert over.status_code == 409 and "초과 입고로 저장" in over.text and "+5" in over.text
|
||||
assert 'value="45"' in over.text # 넣은 숫자는 그대로
|
||||
assert st.get_order(oid)["summary"]["received"] == 60 # 확인 전엔 저장 안 됨
|
||||
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
|
||||
"qty_" + ids["MT-B"]: "50", "confirm_over": "1"}, follow_redirects=False)
|
||||
assert r.status_code == 303 and "%EC%B4%88%EA%B3%BC" in r.headers["location"] # "초과 입고 포함" 안내
|
||||
got = st.get_order(oid)
|
||||
assert (got["status"], got["summary"]["over"]) == ("over", 5)
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert "✓ 전체 입고 완료" in page and "초과 포함" in page # 모든 품목 입고완료·초과입고
|
||||
assert "2026.10.18(일)" in page and "2026.10.16(금)" in page # 날짜 서식(입고일·발주일)
|
||||
lst = c.get("/inout/?status=done").text
|
||||
assert got["order_no"] in lst and "✓ 전체 입고 완료" in lst and "2026.10.16(금)" in lst
|
||||
pend = c.get("/inout/pending").text
|
||||
assert "초과 입고" in pend and got["order_no"] in pend
|
||||
|
||||
# ── 두 번째 발주: 미입고 현황 → 잔량 종결 ──
|
||||
who["u"] = buyer
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-C"],
|
||||
"item_name": [""], "qty": ["30"], "line_memo": [""]}, follow_redirects=False)
|
||||
oid2 = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
pend = c.get("/inout/pending?q=MT-C").text
|
||||
assert "다 단품" in pend and "30" in pend
|
||||
assert "제품별 미입고 합계" in pend
|
||||
lst = c.get("/inout/?status=active&q=MT-C").text
|
||||
assert st.get_order(oid2)["order_no"] in lst
|
||||
c.post("/inout/orders/%d/close" % oid2, data={"reason": "단종"})
|
||||
assert st.get_order(oid2)["status"] == "closed"
|
||||
assert st.get_order(oid2)["order_no"] not in c.get("/inout/pending?q=MT-C").text
|
||||
assert st.get_order(oid2)["order_no"] in c.get("/inout/?status=closed&q=MT-C").text
|
||||
|
||||
# ── 003: 입고증 사진(입고와 함께 · 나중에 더하기 · 보기) ──
|
||||
JPEG = b"\\xff\\xd8\\xff\\xe0" + b"7" * 300
|
||||
who["u"] = wh
|
||||
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
|
||||
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
|
||||
assert o3.status_code == 403 # 입고 담당은 발주 못 함
|
||||
who["u"] = buyer
|
||||
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
|
||||
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
|
||||
assert "mail=1" in o3.headers["location"] # 새 발주서 → 메일 미리보기 바로
|
||||
oid3 = int(re.search(r"/inout/orders/(\\d+)", o3.headers["location"]).group(1))
|
||||
assert 'data-open="1"' in c.get(o3.headers["location"]).text
|
||||
who["u"] = wh
|
||||
page = c.get("/inout/orders/%d" % oid3).text
|
||||
assert 'enctype="multipart/form-data"' in page and 'name="photos"' in page and 'id="io-mail-btn"' not in page
|
||||
lid = re.search(r'name="qty_(\\d+)"', page).group(1)
|
||||
bad = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
|
||||
files=[("photos", ("doc.pdf", b"%PDF-1.4 x", "application/pdf"))])
|
||||
assert bad.status_code == 400 and "사진 파일" in bad.text and "다시 첨부" in bad.text
|
||||
assert st.get_order(oid3)["summary"]["received"] == 0 # 사진이 틀리면 입고도 저장 안 함
|
||||
r = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
|
||||
files=[("photos", ("입고증1.jpg", JPEG, "image/jpeg")), ("photos", ("입고증2.jpg", JPEG, "image/jpeg"))],
|
||||
follow_redirects=False)
|
||||
assert r.status_code == 303, r.text[:300]
|
||||
got = st.get_order(oid3)
|
||||
pids = [p["id"] for p in got["receipts"][0]["photos"]]
|
||||
assert len(pids) == 2 and got["summary"]["received"] == 3
|
||||
img = c.get("/inout/photos/%d" % pids[0])
|
||||
assert img.status_code == 200 and img.content == JPEG and img.headers["content-type"] == "image/jpeg"
|
||||
assert img.headers["x-content-type-options"] == "nosniff" and "sandbox" in img.headers["content-security-policy"]
|
||||
page = c.get("/inout/orders/%d" % oid3).text
|
||||
assert 'data-photo="%d"' % pids[0] in page and 'src="/inout/photos/%d"' % pids[0] in page
|
||||
rid3 = got["receipts"][0]["id"]
|
||||
r = c.post("/inout/orders/%d/receipts/%d/photos" % (oid3, rid3), files=[("photos", ("추가.png", b"\\x89PNG\\r\\n\\x1a\\n" + b"1" * 50, "image/png"))],
|
||||
follow_redirects=False)
|
||||
assert r.status_code == 303 and len(st.get_order(oid3)["receipts"][0]["photos"]) == 3
|
||||
who["u"] = viewer
|
||||
assert c.get("/inout/photos/%d" % pids[0]).status_code == 200 # 모듈 권한이면 보기는 됨
|
||||
assert c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0])).status_code == 403
|
||||
who["u"] = U("nobody-%s@t.local" % tag, inout=False)
|
||||
assert c.get("/inout/photos/%d" % pids[0]).status_code == 403
|
||||
who["u"] = wh
|
||||
c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0]))
|
||||
assert len(st.get_order(oid3)["receipts"][0]["photos"]) == 2
|
||||
|
||||
# ── 003: 발주 메일(발주 담당 본인 Gmail) ──
|
||||
import app.modules.inout.gmail as g
|
||||
sent = []
|
||||
g.send = lambda refresh, raw: (sent.append((refresh, raw)) or "gid-%d" % len(sent))
|
||||
who["u"] = viewer
|
||||
assert c.get("/inout/orders/%d/mail" % oid3).status_code == 403 # 발주 담당만
|
||||
who["u"] = buyer
|
||||
pv = c.get("/inout/orders/%d/mail" % oid3).json()
|
||||
assert pv["connected"] is False and pv["connect_url"].startswith("/inout/gmail/connect?next=")
|
||||
assert pv["callback_url"].endswith("/inout/gmail/callback") # 구글에 등록할 주소 안내
|
||||
assert pv["to"] == "factory-%s@x.com" % tag and pv["subject"].startswith("[발주] ") and "가 단품" in pv["html"]
|
||||
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
|
||||
assert r.status_code == 409 and r.json()["reconnect"] is True # 연결 전엔 못 보냄
|
||||
# 연결 — 구글 콜백(가짜): 다른 계정이면 거절, 같은 계정이면 저장(암호문)
|
||||
class FakeClient:
|
||||
token = None
|
||||
async def authorize_access_token(self, request):
|
||||
return self.token
|
||||
fake = FakeClient()
|
||||
g.oauth_client = lambda: fake
|
||||
fake.token = {"userinfo": {"email": "someone@gmail.com"}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//x"}
|
||||
r = c.get("/inout/gmail/callback", follow_redirects=False)
|
||||
assert r.status_code == 303 and "%EB%8B%A4%EB%A5%B8" in r.headers["location"] # "다른 구글 계정"
|
||||
assert st.gmail_token(buyer["email"]) is None
|
||||
fake.token = {"userinfo": {"email": buyer["email"]}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//buyer-refresh"}
|
||||
c.get("/inout/gmail/callback", follow_redirects=False)
|
||||
tok = st.gmail_token(buyer["email"])
|
||||
assert tok is not None and "1//buyer-refresh" not in tok["refresh_token_enc"] # 원문은 DB 에 없음
|
||||
assert c.get("/inout/orders/%d/mail" % oid3).json()["connected"] is True
|
||||
bad_to = c.post("/inout/orders/%d/mail" % oid3, json={"to": "nope"})
|
||||
assert bad_to.status_code == 400 and "받는 사람 형식" in bad_to.json()["detail"]
|
||||
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "cc": "boss@x.com"})
|
||||
assert r.status_code == 200 and r.json()["ok"], r.text
|
||||
refresh, raw = sent[-1]
|
||||
assert refresh == "1//buyer-refresh" and b"factory-" in raw and b"boss@x.com" in raw
|
||||
again = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
|
||||
assert again.status_code == 409 and again.json()["resend_needed"] is True and len(sent) == 1 # 실수로 두 번 안 감
|
||||
assert c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True}).json()["ok"] and len(sent) == 2
|
||||
detail = c.get("/inout/orders/%d" % oid3).text
|
||||
assert "모두 2번" in detail and "발주 메일 다시 보내기" in detail
|
||||
# 구글이 연결을 끊었으면(invalid_grant) 토큰을 지우고 다시 연결 안내
|
||||
def gone(refresh, raw):
|
||||
raise g.GmailNotConnected("Gmail 연결이 끊겼습니다 — 다시 연결하세요.")
|
||||
g.send = gone
|
||||
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True})
|
||||
assert r.status_code == 409 and r.json()["reconnect"] and st.gmail_token(buyer["email"]) is None
|
||||
|
||||
# ── 단품 검색 API ──
|
||||
assert c.get("/inout/api/items?q=MT-").json()["items"][0]["code"] == "MT-A"
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN, "APP_ENCRYPTION_KEY": "22" * 32, "GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
def test_products_prices_and_receiver_view(self):
|
||||
"""004 — 옵션 → 상품 정보(관리자), 발주서 단가·금액, 메일 본문 금액·PP·은, 입고 담당은 이름·발주 수량만."""
|
||||
res = _run('''
|
||||
import re, uuid
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
|
||||
assert st.products_ready(), "inout_db 004 미적용"
|
||||
main.app.state.inout_store = st
|
||||
items = Items()
|
||||
main.app.state.inout_items = items
|
||||
tag = uuid.uuid4().hex[:6]
|
||||
T = tag.upper()
|
||||
X1, X2 = "ZT-%s-1" % T, "ZT-%s-2" % T
|
||||
items.NAMES = dict(Items.NAMES, **{X1: "지울 단품 " + T, X2: "둘째 단품 " + T})
|
||||
admin, buyer, wh = U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag), U("wh-%s@t.local" % tag)
|
||||
users.extend([admin, buyer, wh])
|
||||
H = {"X-Inout-Options": "1"}
|
||||
|
||||
def body(c):
|
||||
who["u"] = admin
|
||||
assert c.post("/inout/settings/factories", data={"name": "공장P-" + tag, "email": "fp-%s@x.com" % tag, "is_active": "1"},
|
||||
headers=H).json()["ok"]
|
||||
fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장P-" + tag)
|
||||
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]}, headers=H).json()["ok"]
|
||||
|
||||
# ── 옵션 → 상품 정보: 관리자만 ──
|
||||
for u in (buyer, wh):
|
||||
who["u"] = u
|
||||
assert c.post("/inout/settings/products/import", headers=H).status_code == 403
|
||||
assert c.get("/inout/settings?panel=1").status_code == 403 # 입고 담당은 옵션을 못 봄
|
||||
who["u"] = admin
|
||||
r = c.post("/inout/settings/products/import", headers=H).json()
|
||||
assert r["ok"] and "단품을 불러왔습니다" in r["message"], r
|
||||
assert {"MT-A", X1, X2} <= {p["item_code"] for p in st.list_products()}
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'data-pane="products"' in panel and 'data-code="%s"' % X1 in panel and "단품 불러오기" in panel
|
||||
bad = c.post("/inout/settings/products/save", json={"rows": [{"code": X2, "unit_price": "abc"}]}, headers=H)
|
||||
assert bad.status_code == 400 and bad.json()["ok"] is False and X2 in bad.json()["message"]
|
||||
r = c.post("/inout/settings/products/save", headers=H, json={"rows": [
|
||||
{"code": "MT-A", "unit_price": "1,500", "weight_g": "24.5", "silver_pct": "0.5"},
|
||||
{"code": X2, "unit_price": "", "weight_g": "10", "silver_pct": ""}]}).json()
|
||||
assert r["ok"] and "2개" in r["message"], r
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'value="1,500"' in panel and ">0.1225<" in panel # 은 g = 무게 × % (자동)
|
||||
# 다시 불러와도 값은 그대로
|
||||
c.post("/inout/settings/products/import", headers=H)
|
||||
a = st.catalog_lookup(["MT-A"])["MT-A"]
|
||||
assert (str(a["unit_price"]), str(a["weight_g"]), str(a["silver_pct"])) == ("1500.00", "24.50", "0.5000")
|
||||
# 지우기 → 다음 불러오기에서도 빠짐 → 제외 목록에 보임
|
||||
assert c.post("/inout/settings/products/%s/exclude" % X1, headers=H).json()["ok"]
|
||||
c.post("/inout/settings/products/import", headers=H)
|
||||
assert X1 not in st.catalog_lookup([X1])
|
||||
panel = c.get("/inout/settings?panel=1").text
|
||||
assert 'data-restore="%s"' % X1 in panel and 'data-code="%s"' % X1 not in panel
|
||||
|
||||
# ── 발주 담당: 제품 고르기 = 상품 정보(지운 단품 빼고), 단가 함께 ──
|
||||
who["u"] = buyer
|
||||
found = c.get("/inout/api/items?q=" + T).json()
|
||||
assert found["source"] == "products" and [x["code"] for x in found["items"]] == [X2]
|
||||
mta = c.get("/inout/api/items?q=MT-A").json()["items"][0]
|
||||
assert (mta["code"], mta["unit_price"], mta["price"]) == ("MT-A", "1,500", 1500.0)
|
||||
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": [X1],
|
||||
"item_name": [""], "qty": ["5"], "line_memo": [""]})
|
||||
assert bad.status_code == 400 and "상품 정보에 없는 단품입니다" in bad.text
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A", X2],
|
||||
"item_name": ["", ""], "qty": ["100", "3"], "line_memo": ["", ""]}, follow_redirects=False)
|
||||
assert r.status_code == 303, r.text[:300]
|
||||
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
# 그 뒤 단가가 바뀌어도 이 발주서는 발주할 때 값
|
||||
who["u"] = admin
|
||||
c.post("/inout/settings/products/save", headers=H, json={"rows": [{"code": "MT-A", "unit_price": "2000", "weight_g": "24.5", "silver_pct": "0.5"}]})
|
||||
who["u"] = buyer
|
||||
detail = c.get("/inout/orders/%d" % oid).text
|
||||
for part in ("단가(원)", "금액(원)", "150,000", "단가 미입력 1종 제외", "2.48kg", "12.25g", "0.5%", "<th>제품 코드</th>"):
|
||||
assert part in detail, part
|
||||
assert "200,000" not in detail
|
||||
assert 'data-price="1500"' in c.get("/inout/orders/%d/edit" % oid).text or "1,500" in c.get("/inout/orders/%d/edit" % oid).text
|
||||
pv = c.get("/inout/orders/%d/mail" % oid).json()
|
||||
for part in ("150,000", "PP(g/개)", "은(Ag) 함유량", "0.5% (0.1225g)", "2.48 kg", "12.25 g"):
|
||||
assert part in pv["html"], part
|
||||
|
||||
# ── 입고 담당: 품목은 제품 이름·발주 수량(+ 이번 입고)만 ──
|
||||
who["u"] = wh
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert "가 단품" in page and "이번 입고" in page
|
||||
for hidden in ("<th>제품 코드</th>", "단가(원)", "금액(원)", "150,000", "PP(g/개)", ">미입고</th>", ">상태</th>"):
|
||||
assert hidden not in page, hidden
|
||||
lid = re.search(r'name="qty_(\\d+)"[^>]*data-code="MT-A"', page, re.S).group(1)
|
||||
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-20", "qty_" + lid: "40"}, follow_redirects=False)
|
||||
assert r.status_code == 303
|
||||
page = c.get("/inout/orders/%d" % oid).text
|
||||
assert '<span class="io-chip">가 단품 40</span>' in page # 입고 기록도 코드 없이 이름
|
||||
|
||||
# 정리 — 테스트 단품은 지운다(MT-A~C 는 남아도 다른 테스트에 영향 없음)
|
||||
who["u"] = admin
|
||||
c.post("/inout/settings/products/%s/exclude" % X2, headers=H)
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
def test_super_admin_deletes_order(self):
|
||||
"""발주 목록 🗑 — 수퍼관리자만(ERP 관리자·발주 담당은 403·버튼 없음), 지운 뒤 보던 목록으로."""
|
||||
res = _run('''
|
||||
import re, uuid
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
|
||||
main.app.state.inout_store = st
|
||||
main.app.state.inout_items = Items()
|
||||
tag = uuid.uuid4().hex[:6]
|
||||
admin = U("admin-%s@t.local" % tag, role="admin")
|
||||
boss = dict(U("boss-%s@t.local" % tag, role="admin"), is_super_admin=True)
|
||||
users.extend([admin, boss])
|
||||
|
||||
def body(c):
|
||||
who["u"] = admin
|
||||
H = {"X-Inout-Options": "1"}
|
||||
c.post("/inout/settings/factories", data={"name": "공장D-" + tag, "is_active": "1"}, headers=H)
|
||||
fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장D-" + tag)
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
|
||||
"item_name": [""], "qty": ["7"], "line_memo": [""]}, follow_redirects=False)
|
||||
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
no = st.get_order(oid)["order_no"]
|
||||
# ERP 관리자(수퍼 아님) — 버튼 없음, 직접 보내도 403
|
||||
assert 'action="/inout/orders/%d/delete"' % oid not in c.get("/inout/?status=all").text
|
||||
assert c.post("/inout/orders/%d/delete" % oid).status_code == 403
|
||||
assert st.get_order(oid) is not None
|
||||
# 수퍼관리자 — 목록에 🗑, 지우면 보던 목록(거르기 그대로)으로
|
||||
who["u"] = boss
|
||||
lst = c.get("/inout/?status=all&q=" + no).text
|
||||
assert 'action="/inout/orders/%d/delete"' % oid in lst and "완전히 삭제할까요?" in lst
|
||||
r = c.post("/inout/orders/%d/delete" % oid, data={"back": "/inout/?status=all&q=" + no}, follow_redirects=False)
|
||||
assert r.status_code == 303 and r.headers["location"].startswith("/inout/?status=all&q=" + no + "&msg="), r.headers["location"]
|
||||
assert st.get_order(oid) is None
|
||||
assert c.post("/inout/orders/%d/delete" % oid, data={"back": "https://evil.example/"}, follow_redirects=False).headers["location"].startswith("/inout/?msg=")
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Project 옵션(시스템 전체 — 처음 여는 탭·보드 카드 표지) API·검사. DB 없이 가짜 저장소로.
|
||||
|
||||
일반(폰트)은 브라우저 localStorage 라 서버에 없다. 수퍼관리자·Admin 만 저장, 읽기는 모듈 권한자 누구나.
|
||||
"""
|
||||
import importlib
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from psycopg.errors import UndefinedTable
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
store = importlib.import_module("app.modules.project.store")
|
||||
|
||||
ADMIN = {"email": "Boss@Test.local", "role": "admin"}
|
||||
USER = {"email": "me@test.local", "role": "user"}
|
||||
PRO = {"email": "pro@test.local", "role": "pro"}
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self, saved=None, *, missing=False, broken=False):
|
||||
self.saved = dict(saved or {})
|
||||
self.missing = missing # 029 미적용
|
||||
self.broken = broken # 읽기 자체가 실패(연결 끊김 등)
|
||||
self.writes = []
|
||||
|
||||
def get_project_options(self):
|
||||
if self.broken:
|
||||
raise RuntimeError("db down")
|
||||
return {} if self.missing else dict(self.saved)
|
||||
|
||||
def set_project_options(self, *, values, updated_by):
|
||||
if self.missing:
|
||||
raise UndefinedTable("project_options")
|
||||
self.writes.append((dict(values), updated_by))
|
||||
self.saved.update(values)
|
||||
|
||||
|
||||
class NormalizeTests(unittest.TestCase):
|
||||
def test_defaults_when_nothing_saved(self):
|
||||
self.assertEqual(store.normalize_project_options(None), {"default_view": "board", "board_cover": True})
|
||||
self.assertEqual(store.normalize_project_options({}), {"default_view": "board", "board_cover": True})
|
||||
|
||||
def test_bad_or_unknown_saved_values_fall_back(self):
|
||||
out = store.normalize_project_options({"default_view": "gantt", "board_cover": "no", "x": 1})
|
||||
self.assertEqual(out, {"default_view": "board", "board_cover": True})
|
||||
|
||||
def test_saved_values_used(self):
|
||||
out = store.normalize_project_options({"default_view": "timeline", "board_cover": False})
|
||||
self.assertEqual(out, {"default_view": "timeline", "board_cover": False})
|
||||
|
||||
def test_validate_keeps_only_sent_keys(self):
|
||||
self.assertEqual(store.validate_project_options({"board_cover": False}), {"board_cover": False})
|
||||
|
||||
def test_validate_rejects(self):
|
||||
for bad in ({}, None, [], {"default_view": "gantt"}, {"board_cover": 0}, {"board_cover": "false"}, {"font": "x"}):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
store.validate_project_options(bad)
|
||||
|
||||
|
||||
class OptionsApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def call(self, method, user, st, body=None):
|
||||
with patch.object(api, "_require_user", return_value=user), \
|
||||
patch.object(api, "_db_or_503", return_value=st):
|
||||
return self.client.request(method, "/project/api/options", json=body)
|
||||
|
||||
def test_anyone_with_module_reads_with_can_edit_flag(self):
|
||||
st = FakeStore({"default_view": "list"})
|
||||
out = self.call("GET", USER, st).json()
|
||||
self.assertEqual(out, {"options": {"default_view": "list", "board_cover": True}, "can_edit": False})
|
||||
self.assertTrue(self.call("GET", ADMIN, st).json()["can_edit"])
|
||||
|
||||
def test_admin_saves_only_sent_keys(self):
|
||||
st = FakeStore({"default_view": "calendar"})
|
||||
res = self.call("PUT", ADMIN, st, {"board_cover": False})
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertEqual(st.writes, [({"board_cover": False}, "Boss@Test.local")])
|
||||
self.assertEqual(res.json()["options"], {"default_view": "calendar", "board_cover": False})
|
||||
|
||||
def test_user_and_pro_cannot_save(self):
|
||||
for who in (USER, PRO):
|
||||
st = FakeStore()
|
||||
with self.subTest(role=who["role"]):
|
||||
self.assertEqual(self.call("PUT", who, st, {"board_cover": False}).status_code, 403)
|
||||
self.assertEqual(st.writes, [])
|
||||
|
||||
def test_invalid_payload_400_without_write(self):
|
||||
st = FakeStore()
|
||||
for body in ({"default_view": "gantt"}, {"board_cover": "yes"}, {}, {"font": "pretendard"}):
|
||||
with self.subTest(body=body):
|
||||
self.assertEqual(self.call("PUT", ADMIN, st, body).status_code, 400)
|
||||
self.assertEqual(st.writes, [])
|
||||
|
||||
def test_migration_missing_read_defaults_write_503(self):
|
||||
st = FakeStore(missing=True)
|
||||
self.assertEqual(self.call("GET", USER, st).json()["options"], {"default_view": "board", "board_cover": True})
|
||||
res = self.call("PUT", ADMIN, st, {"board_cover": False})
|
||||
self.assertEqual(res.status_code, 503)
|
||||
self.assertIn("029", res.json()["detail"])
|
||||
|
||||
def test_page_reader_never_fails(self):
|
||||
self.assertEqual(api._project_options(None), {"default_view": "board", "board_cover": True})
|
||||
self.assertEqual(api._project_options(FakeStore(broken=True)), {"default_view": "board", "board_cover": True})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user