diff --git a/CLAUDE.md b/CLAUDE.md index 4b5ae35..e4c826a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아 - 반품관리 - 외부 쇼핑몰 API 연동 (카페24, 네이버 스마트스토어, 사방넷 등) - 개인경비 (`app/modules/expense/`, `expense_db`) -- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/상자 계산, 상품은 `itemcode_db` 읽기 전용. 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트). 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일, 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷 — 혼합 상자 내용물·상자 종류 표시용) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 양식 생성은 `app/modules/cupang/export.py` 한 곳에서 만들어 xlsx·구글시트가 공유. `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시 확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip). 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트를 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제(문서에 시트가 하나뿐이면 내용만 비움). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 로켓 매출(`/cupang/sales`, `cupang_sales`·`cupang_sales_weekly`) — 발주 라인별 공급가·원가·물류비·마진 표. 기간/센터/유형/검색 조회, 행 CRUD, 구글 시트 양식 xlsx·csv 업로드(같은 발주번호+SKU+출고일+센터+수량은 덮어씀), 엑셀 다운로드. 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관하고 순마진은 화면에서 계산. 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 상자 계산·자동 배분 +- 쿠팡 밀크런 (`app/modules/cupang/`, `cupang_db`) — 출고 달력/상자 계산, 상품은 `itemcode_db` 읽기 전용. 설정(제품명)에서 제품별 포장무게(g, `cupang_products.weight_g`, 마이그레이션 007 + 시드) 입력·표시·정렬. 출고 묶음은 **상자 계산 화면의 [분배 확정] 으로만** 만든다(신규 등록 폼 없음, `/cupang/new` 는 상자 계산으로 리다이렉트). 확정 조건: 미배분 상자 0 + 담긴 센터마다 출고방식(택배/파렛트) 선택. 확정 시 센터마다 출고 묶음 1건(`status=출고준비`, 센터입고일=출고일+1일, 상자 구성은 `cupang_shipments.box_plan` JSONB 에 스냅샷 — 혼합 상자 내용물·상자 종류 표시용) + 출고리스트 엑셀 자동 다운로드(`GET /cupang/export.xlsx?date=`, 시트명 YYYYMMDD). 양식 생성은 `app/modules/cupang/export.py` 한 곳에서 만들어 xlsx·구글시트가 공유. `CUPANG_SHEET_ID` + 인증(사용자 OAuth `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 또는 서비스 계정 `GOOGLE_SHEETS_CREDENTIALS[_JSON]`) 설정 시 확정과 동시에 Google 스프레드시트에 출고일 시트를 생성/덮어쓰기(`app/integrations/google_sheets.py`, 미설정이면 조용히 skip). 출고 삭제(건별/날짜 전체) 시에도 같은 날짜 시트를 동기화 — 남은 출고가 있으면 다시 쓰고, 없으면 시트 삭제(문서에 시트가 하나뿐이면 내용만 비움). 작업 중 상태는 `cupang_box_calc_drafts` 에 이름 붙여 임시 저장/불러오기. 쿠팡 로켓 매출(`/cupang/sales`, `cupang_sales`·`cupang_sales_weekly`) — 발주 라인별 공급가·원가·물류비·마진 표. 기간/센터/유형/검색 조회, 행 CRUD, 구글 시트 양식 xlsx·csv 업로드(같은 발주번호+SKU+출고일+센터+수량은 덮어씀), 엑셀 다운로드. 광고비·할인 프로모션·장려금은 주차 단위(`cupang_sales_weekly`)로 보관하고 순마진은 화면에서 계산. 초기 데이터는 `scripts/sql/cupang_sales_seed.sql`. 쿠팡 발주 엑셀(xlsx) 다중 업로드 지원(`POST /cupang/api/box-calc/upload`, openpyxl) — F13 입고예정일의 하루 전 = 출고일, 22행부터 B=쿠팡상품코드·F=센터명·G=수량을 읽어 `cupang_products.coupang_item_code` 로 제품 매칭 후 센터별 합산 → 센터 단위로 상자 계산·자동 배분 - 휴가 관리 (`app/modules/vacation/`, `vacation_db`) — 월간 달력(구글식 bar)/연차·반차 신청/승인 워크플로/공휴일·연차 설정. 권한키 `vacation`·`vacation_approver` - 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia` - 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1상자=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1상자 묶음 기준 Package ID > Tracking ID > Order ID, 같은 상자 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md` diff --git a/app/modules/cupang/db.py b/app/modules/cupang/db.py index aaaa605..12aa539 100644 --- a/app/modules/cupang/db.py +++ b/app/modules/cupang/db.py @@ -36,10 +36,23 @@ class CupangDBStore: open=False, ) self._pool.open(wait=False) + self._weight_col: bool | None = None # 마이그레이션 007(weight_g) 적용 여부 — 한 번 확인되면 기억 def close(self) -> None: self._pool.close() + def weight_enabled(self) -> bool: + """cupang_products.weight_g(포장무게, 마이그레이션 007) 가 있는가. 있으면 기억(없으면 다음에 다시 확인).""" + if self._weight_col: + return True + with self._pool.connection() as conn: + row = conn.execute( + "SELECT 1 FROM information_schema.columns " + "WHERE table_name = 'cupang_products' AND column_name = 'weight_g'" + ).fetchone() + self._weight_col = row is not None + return self._weight_col + # ════════════════════════════════════════════════════════════ # 입고센터 (cupang_centers) # ════════════════════════════════════════════════════════════ @@ -300,32 +313,39 @@ class CupangDBStore: product_name: str, coupang_item_code: str | None = None, sort_order: int = 0, + weight_g: int | None = None, ) -> dict[str, Any]: """제품 등록/수정. coupang_item_code 가 None 이면 기존 값을 유지한다(빈 문자열은 지우기). + weight_g(포장무게 g) 가 None 이면 기존 값을 유지한다(수기 추가에서 비워 두면 그대로). 007 미적용이면 무시. """ code = (product_code or "").strip() name = (product_name or "").strip() cic = None if coupang_item_code is None else coupang_item_code.strip() if not code or not name: raise ValueError("제품코드와 제품명 모두 필요합니다.") + weight = self.weight_enabled() with self._pool.connection() as conn: row = conn.execute( """ INSERT INTO cupang_products - (product_code, product_name, coupang_item_code, sort_order) - VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s) + (product_code, product_name, coupang_item_code, sort_order""" + + (", weight_g" if weight else "") + """) + VALUES (%(code)s, %(name)s, COALESCE(%(cic)s, ''), %(sort)s""" + + (", %(w)s" if weight else "") + """) ON CONFLICT (product_code) DO UPDATE SET product_name = EXCLUDED.product_name, coupang_item_code = COALESCE( %(cic)s, cupang_products.coupang_item_code - ), + ),""" + + ("\n weight_g = COALESCE(%(w)s, cupang_products.weight_g)," if weight else "") + + """ sort_order = EXCLUDED.sort_order, active = TRUE RETURNING * """, - {"code": code, "name": name, "cic": cic, "sort": sort_order}, + {"code": code, "name": name, "cic": cic, "sort": sort_order, "w": weight_g}, ).fetchone() return self._product_serialize(row) @@ -345,8 +365,11 @@ class CupangDBStore: product_name: str, product_code: str, coupang_item_code: str = "", + weight_g: Any = ..., ) -> dict[str, Any]: - """등록된 제품 수정(제품명/제품코드/쿠팡상품코드). + """등록된 제품 수정(제품명/제품코드/쿠팡상품코드/포장무게). + + weight_g: 정수 g 또는 None(지움). 넘기지 않으면(...) 그대로 — 007 미적용이면 무시. 제품코드가 바뀌면 같은 코드로 연결돼 있던 상자 규칙(cupang_box_rules)의 product_code 도 함께 옮긴다(출고 라인은 과거 기록이라 스냅샷 유지). @@ -356,6 +379,7 @@ class CupangDBStore: cic = (coupang_item_code or "").strip() if not name or not code: raise ValueError("제품코드와 제품명 모두 필요합니다.") + set_weight = weight_g is not ... and self.weight_enabled() # 트랜잭션 밖에서 확인(연결을 겹쳐 잡지 않게) with self._pool.connection() as conn: with conn.transaction(): old = conn.execute( @@ -378,11 +402,12 @@ class CupangDBStore: UPDATE cupang_products SET product_name = %s, product_code = %s, - coupang_item_code = %s + coupang_item_code = %s""" + + (", weight_g = %s" if set_weight else "") + """ WHERE id = %s RETURNING * """, - (name, code, cic, product_id), + (name, code, cic) + ((weight_g,) if set_weight else ()) + (product_id,), ).fetchone() if code != old_code: # 새 코드로 된 규칙이 이미 있으면 옮기지 않는다(중복 방지). @@ -1081,6 +1106,8 @@ class CupangDBStore: out["active"] = bool(out.get("active", True)) out["sort_order"] = int(out.get("sort_order", 0)) out["coupang_item_code"] = (out.get("coupang_item_code") or "").strip() + w = out.get("weight_g") # 007 미적용이면 키 없음 → None + out["weight_g"] = int(w) if w is not None else None for k in ("created_at", "updated_at"): v = out.get(k) if isinstance(v, datetime): diff --git a/app/modules/cupang/router.py b/app/modules/cupang/router.py index e0e26e6..1f218db 100644 --- a/app/modules/cupang/router.py +++ b/app/modules/cupang/router.py @@ -22,7 +22,7 @@ from fastapi import APIRouter, Body, Depends, File, Form, HTTPException, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from .holidays import holiday_name, is_holiday -from .store import SHIP_METHODS +from .store import SHIP_METHODS, parse_weight_g router = APIRouter(prefix="/cupang", tags=["cupang"]) @@ -1349,6 +1349,8 @@ def products_page(request: Request) -> HTMLResponse: "page_subtitle": "왼쪽 itemcode_db 목록에서 선택해 등록하면 폼 드롭다운에 노출됩니다.", "products": store.list_products(include_inactive=True), "registered_codes": [p["product_code"] for p in store.list_products(include_inactive=True)], + # 포장무게(g) — 마이그레이션 007 적용 전이면 무게 칸을 숨긴다 + "weight_enabled": store.weight_enabled(), "search_enabled": bool(reader and reader.enabled), "search_reason": (reader.reason if reader else ""), }, @@ -1412,6 +1414,7 @@ def product_upsert( product_code: str = Form(...), product_name: str = Form(...), coupang_item_code: str = Form(""), + weight_g: str = Form(""), sort_order: int = Form(0), user: dict[str, Any] = Depends(_require_user), ) -> RedirectResponse: @@ -1422,9 +1425,10 @@ def product_upsert( store.upsert_product( product_code=product_code, product_name=product_name, - # 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드를 유지한다. + # 빈 값은 "미입력" 으로 보고 기존 쿠팡상품코드·포장무게를 유지한다. coupang_item_code=(coupang_item_code.strip() or None), sort_order=sort_order, + weight_g=parse_weight_g(weight_g), ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) @@ -1457,7 +1461,8 @@ def product_edit( payload: dict[str, Any] = Body(...), user: dict[str, Any] = Depends(_require_user), ) -> JSONResponse: - """등록된 제품 수정. body: {product_name, product_code, coupang_item_code}.""" + """등록된 제품 수정. body: {product_name, product_code, coupang_item_code, weight_g?}. + weight_g 키가 있으면 저장(빈 값 = 지움), 없으면 무게는 그대로.""" store = _store(request) if store is None: raise HTTPException(status_code=503, detail="cupang_db 미설정") @@ -1467,6 +1472,7 @@ def product_edit( product_name=str(payload.get("product_name") or ""), product_code=str(payload.get("product_code") or ""), coupang_item_code=str(payload.get("coupang_item_code") or ""), + weight_g=(parse_weight_g(payload.get("weight_g")) if "weight_g" in payload else ...), ) except KeyError: raise HTTPException(status_code=404, detail="제품을 찾을 수 없습니다.") diff --git a/app/modules/cupang/store.py b/app/modules/cupang/store.py index 5951628..dae9868 100644 --- a/app/modules/cupang/store.py +++ b/app/modules/cupang/store.py @@ -94,3 +94,32 @@ def compute_boxes(quantity: int, units_per_box: int | None) -> dict[str, Any]: "remainder_units": qty % upb, "required_boxes": math.ceil(qty / upb), } + + +# 제품 포장무게(g) — cupang_products.weight_g (마이그레이션 007). 0 ~ 1,000,000g, 정수. +WEIGHT_MAX_G = 1_000_000 + + +def parse_weight_g(value: Any) -> int | None: + """포장무게 입력 → 그램 정수. 빈 값은 None(미입력). + + "1,070" · " 1,070 " · "1070g" · "1070.0" 처럼 쉼표·공백·g 단위가 붙어도 읽는다. + 숫자가 아니거나 음수·소수(0.5g 등)·범위 밖이면 ValueError. + """ + if value is None: + return None + s = str(value).strip().replace(",", "").replace(" ", "") + if s.lower().endswith("g"): + s = s[:-1] + if not s: + return None + try: + f = float(s) + except ValueError: + raise ValueError(f"포장무게는 숫자(g)로 입력하세요: {value}") + if f != f or f < 0 or f != int(f): + raise ValueError(f"포장무게는 0 이상의 정수(g)로 입력하세요: {value}") + v = int(f) + if v > WEIGHT_MAX_G: + raise ValueError(f"포장무게가 너무 큽니다(최대 {WEIGHT_MAX_G:,}g): {value}") + return v diff --git a/app/modules/cupang/templates/cupang/box_calc.html b/app/modules/cupang/templates/cupang/box_calc.html index d00d33c..5ffb7b8 100644 --- a/app/modules/cupang/templates/cupang/box_calc.html +++ b/app/modules/cupang/templates/cupang/box_calc.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/cupang/templates/cupang/box_rules.html b/app/modules/cupang/templates/cupang/box_rules.html index 7ce499b..e181339 100644 --- a/app/modules/cupang/templates/cupang/box_rules.html +++ b/app/modules/cupang/templates/cupang/box_rules.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/cupang/templates/cupang/index.html b/app/modules/cupang/templates/cupang/index.html index d03a0bf..39fc937 100644 --- a/app/modules/cupang/templates/cupang/index.html +++ b/app/modules/cupang/templates/cupang/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
diff --git a/app/modules/cupang/templates/cupang/products.html b/app/modules/cupang/templates/cupang/products.html index 18d5df3..9ced99c 100644 --- a/app/modules/cupang/templates/cupang/products.html +++ b/app/modules/cupang/templates/cupang/products.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %}
@@ -34,6 +34,12 @@ + {% if weight_enabled %} + {# 포장무게(g) — 쉼표·g 붙여도 됨(1,070). 비워 두면 같은 제품코드의 기존 무게 유지 #} + + {% endif %} @@ -60,6 +66,7 @@ + {% if weight_enabled %}{% endif %} 상태 동작 @@ -68,10 +75,12 @@ {% for p in products %} {{ p.product_name }} {{ p.product_code }} {% if p.coupang_item_code %}{{ p.coupang_item_code }}{% else %}—{% endif %} + {% if weight_enabled %}{% if p.weight_g is not none %}{{ "{:,}".format(p.weight_g) }}g{% else %}—{% endif %}{% endif %} @@ -167,6 +184,7 @@ var elName = document.getElementById("cpg-edit-name"); var elCode = document.getElementById("cpg-edit-code"); var elCp = document.getElementById("cpg-edit-cpcode"); + var elW = document.getElementById("cpg-edit-weight"); // 마이그레이션 007 전이면 없음 var elMsg = document.getElementById("cpg-edit-msg"); var saveBtn = document.getElementById("cpg-edit-save"); var editingId = null; @@ -181,6 +199,10 @@ elName.value = row.getAttribute("data-name") || ""; elCode.value = row.getAttribute("data-code") || ""; elCp.value = row.getAttribute("data-cpcode") || ""; + if (elW) { + var w = row.getAttribute("data-weight") || ""; + elW.value = w ? Number(w).toLocaleString("ko-KR") : ""; + } elMsg.textContent = ""; dlg.hidden = false; elName.focus(); @@ -200,6 +222,12 @@ product_code: (elCode.value || "").trim(), coupang_item_code: (elCp.value || "").trim() }; + if (elW) { + // 포장무게 — 쉼표·g 는 서버가 읽는다. 숫자가 아니면 여기서 먼저 막는다(빈 값 = 지움) + var wv = (elW.value || "").trim(); + if (wv && !/^[0-9][0-9,]*\s*g?$/i.test(wv)) { elMsg.textContent = "포장무게는 숫자(g)로 입력하세요. 예: 1,070"; return; } + body.weight_g = wv; + } if (!body.product_name || !body.product_code) { elMsg.textContent = "제품명과 제품코드는 필수입니다."; return; } diff --git a/app/modules/cupang/templates/cupang/sales.html b/app/modules/cupang/templates/cupang/sales.html index a6a2da5..9c1a973 100644 --- a/app/modules/cupang/templates/cupang/sales.html +++ b/app/modules/cupang/templates/cupang/sales.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %} {# 쿠팡 로켓 매출 — 발주 라인별 공급가·원가·물류비·마진 #} diff --git a/app/modules/cupang/templates/cupang/view.html b/app/modules/cupang/templates/cupang/view.html index d9a9976..3ca95c2 100644 --- a/app/modules/cupang/templates/cupang/view.html +++ b/app/modules/cupang/templates/cupang/view.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {% block content %} {# 출고 묶음 보기 — 상자 계산 화면과 같은 3열 구성. 읽기 전용(수정 없음). #} diff --git a/app/static/cupang.css b/app/static/cupang.css index f7bba57..790da41 100644 --- a/app/static/cupang.css +++ b/app/static/cupang.css @@ -534,6 +534,7 @@ flex-wrap: wrap; } .cpg-prod-manual-row .erp-field { flex: 1 1 160px; min-width: 0; } +.cpg-prod-manual-row .cpg-weight-field { flex: 0 1 120px; } .cpg-prod-manual-row .erp-input { min-width: 0; width: 100%; } /* 상자 그림 안 박스 호수 라벨 (예: 2호) */ @@ -1009,16 +1010,21 @@ body.cpg-dragging { cursor: grabbing; user-select: none; } text-overflow: ellipsis; vertical-align: middle; } -/* 열 폭: 제품명 160 / 제품코드 96 / 상태 72 / 동작 104 고정, - 쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다. */ +/* 열 폭: 제품명 160 / 제품코드 96 / (포장무게 84) / 상태 72 / 동작 104 고정, + 쿠팡상품코드는 남는 폭을 흡수 → 다른 열이 지정 폭 그대로 유지된다. + 상태·동작은 끝에서부터 센다(포장무게 열이 있든 없든 — 마이그레이션 007 전이면 없음). */ .cpg-prod-right .erp-table th:nth-child(1), .cpg-prod-right .erp-table td:nth-child(1) { width: 160px; } .cpg-prod-right .erp-table th:nth-child(2), .cpg-prod-right .erp-table td:nth-child(2) { width: 96px; } -.cpg-prod-right .erp-table th:nth-child(4), -.cpg-prod-right .erp-table td:nth-child(4) { width: 72px; } -.cpg-prod-right .erp-table th:nth-child(5), -.cpg-prod-right .erp-table td:nth-child(5) { width: 104px; } +.cpg-prod-right .erp-table th.cpg-weight-col, +.cpg-prod-right .erp-table td.cpg-weight-col { width: 84px; text-align: right; font-variant-numeric: tabular-nums; } +.cpg-prod-right .erp-table th.cpg-weight-col .cpg-sort { margin-left: auto; } +.cpg-weight-unit { margin-left: 2px; font-size: 11px; color: var(--erp-muted, #8a8f98); } +.cpg-prod-right .erp-table th:nth-last-child(2), +.cpg-prod-right .erp-table td:nth-last-child(2) { width: 72px; } +.cpg-prod-right .erp-table th:nth-last-child(1), +.cpg-prod-right .erp-table td:nth-last-child(1) { width: 104px; } /* 제품코드·쿠팡상품코드는 mono 라 조금 더 좁게 */ .cpg-prod-right .erp-table td:nth-child(2), .cpg-prod-right .erp-table td:nth-child(3) { font-size: 12px; } diff --git a/docs/DATABASES.md b/docs/DATABASES.md index c827909..9922e2a 100644 --- a/docs/DATABASES.md +++ b/docs/DATABASES.md @@ -208,6 +208,8 @@ DDL: `scripts/sql/cupang_db_init.sql` (멱등). DB·역할(`cupang_app`)·테이 박스 계산은 서버(`store.compute_boxes`)에서 재계산: `required_boxes = ceil(quantity / units_per_box)`. 클라이언트 계산은 미리보기용. +제품 카탈로그 `cupang_products`(제품코드 UNIQUE·제품명·쿠팡상품코드·활성) — **포장무게 `weight_g`**(INTEGER g, NULL = 미입력, 0~1,000,000 CHECK)는 마이그레이션 `scripts/sql/cupang_db_007_product_weight.sql`, 초기 값 시드 `scripts/sql/cupang_products_weight_seed.sql`(무게가 비어 있는 행만 채움, 실행 전 값은 `_cpg_weight_seed_backup` 에 남김). 007 미적용이면 화면은 무게 칸을 숨기고 그대로 동작. + 임시 저장(`cupang_box_calc_drafts`)은 화면 상태 스냅샷만 담는다. 불러올 때 박스 수는 저장값을 쓰지 않고 서버에서 다시 계산하고, 그 위에 분배 내역을 얹는다(사라진 항목은 제외). 마이그레이션: `scripts/sql/cupang_db_003_box_calc_drafts.sql`. 상품은 `cupang_db` 에 복제 저장하지 않는다. 라인에는 `product_code` + `product_name_snapshot` 만 보존(과거 명칭 보존). 상품 검색은 `itemcode_db` **읽기 전용**(`ITEMCODE_DB_URL`, 미설정 시 수동 입력). diff --git a/scripts/sql/cupang_db_007_product_weight.sql b/scripts/sql/cupang_db_007_product_weight.sql new file mode 100644 index 0000000..3513743 --- /dev/null +++ b/scripts/sql/cupang_db_007_product_weight.sql @@ -0,0 +1,33 @@ +-- ===================================================================== +-- cupang_db 마이그레이션 007 — 제품 포장무게(g) +-- ===================================================================== +-- 멱등(idempotent). DROP TABLE/TRUNCATE/DELETE 없음 — 칸 하나와 CHECK 제약만 더한다. +-- +-- cupang_products.weight_g INTEGER NULL — 포장무게(그램). NULL = 아직 모름. +-- 설정(제품명) 화면의 수기 추가·수정 팝업에서 입력, 등록 목록에 표시. +-- 초기 값은 별도 시드 scripts/sql/cupang_products_weight_seed.sql (이 파일 다음에 실행). +-- +-- 미적용이어도 화면은 동작한다 — 무게 칸만 숨기고 저장하지 않는다(라우터/DB 가 칸 유무를 확인). +-- +-- 적용 (1회, 여러 번 돌려도 안전, 적용 전 cupang_db 백업): +-- docker exec -i postgres-db psql -U postgres -d cupang_db < scripts/sql/cupang_db_007_product_weight.sql +-- 확인: +-- docker exec -i postgres-db psql -U postgres -d cupang_db -c "\d cupang_products" +-- ===================================================================== + +\set ON_ERROR_STOP on +\connect cupang_db + +BEGIN; + +ALTER TABLE cupang_products ADD COLUMN IF NOT EXISTS weight_g INTEGER NULL; + +ALTER TABLE cupang_products DROP CONSTRAINT IF EXISTS cupang_products_weight_g_check; +ALTER TABLE cupang_products ADD CONSTRAINT cupang_products_weight_g_check + CHECK (weight_g IS NULL OR (weight_g >= 0 AND weight_g <= 1000000)); + +COMMENT ON COLUMN cupang_products.weight_g IS '포장무게(g). NULL = 미입력'; + +COMMIT; + +SELECT 'cupang_db 007 product weight ready' AS status; diff --git a/scripts/sql/cupang_products_weight_seed.sql b/scripts/sql/cupang_products_weight_seed.sql new file mode 100644 index 0000000..0b3c81d --- /dev/null +++ b/scripts/sql/cupang_products_weight_seed.sql @@ -0,0 +1,98 @@ +-- ===================================================================== +-- cupang_db 시드 — 등록된 제품에 포장무게(g) 채우기 +-- ===================================================================== +-- 사유: 사용자가 전달한 (물류코드, 포장무게 g) 39건(2026-10-02)을 cupang_products.weight_g 에 반영한다. +-- +-- 선행: scripts/sql/cupang_db_007_product_weight.sql 적용 필요. +-- +-- 안전: product_code 가 정확히 일치하고 **무게가 아직 비어 있는(NULL) 행만** UPDATE 한다. +-- (조건 없는 대량 UPDATE 아님. 삭제/DROP 없음. 화면에서 이미 입력·수정한 무게는 덮어쓰지 않는다) +-- 실행 전 현재 값을 _cpg_weight_seed_backup 테이블에 남긴다. 목록에 없는 제품은 건드리지 않는다. +-- 여러 번 실행해도 안전(두 번째부터는 비어 있는 행이 없어 바뀌지 않음). +-- +-- 실행: +-- docker exec -i postgres-db psql -U postgres -d cupang_db < scripts/sql/cupang_products_weight_seed.sql +-- +-- 되돌리기(백업 테이블이 남아 있을 때): +-- UPDATE cupang_products p SET weight_g = b.old_weight_g +-- FROM _cpg_weight_seed_backup b WHERE b.id = p.id; +-- ===================================================================== + +\set ON_ERROR_STOP on +\connect cupang_db + +BEGIN; + +CREATE TEMP TABLE _cpg_wseed (product_code TEXT, weight_g INTEGER); + +INSERT INTO _cpg_wseed (product_code, weight_g) VALUES + ('MT-0550', 265), + ('MS-9804', 450), + ('MS-9805', 580), + ('MS-9801', 200), + ('MS-9806', 650), + ('MS-9807', 870), + ('MT-1800', 340), + ('MS-9808', 780), + ('MS-9809', 1070), + ('MS-9810', 870), + ('MS-9811', 1200), + ('MT-3200', 400), + ('MS-9802', 1000), + ('MS-1001', 623), + ('MS-1002', 951), + ('MS-1003', 1124), + ('MS-1004', 866), + ('MS-1005', 730), + ('MS-1006', 1110), + ('MS-1007', 1190), + ('MS-9812', 645), + ('MS-9813', 713), + ('MS-9814', 835), + ('MS-9815', 1270), + ('MS-9816', 1845), + ('MS-9817', 2252), + ('MS-9818', 3000), + ('MT-4000', 410), + ('MT-4000_3', 830), + ('MT-4000_5', 1250), + ('MZ-0001', 450), + ('MZ-0002', 520), + ('MT-0001', 800), + ('MT-0001_3', 1900), + ('MT-0001_5', 3000), + ('MT-5000_2', 1000), + ('MT-5000_4', 1800), + ('MT-7000_2', 1060), + ('MW-7000_2', 1060); + +-- 변경 전 값 백업 (되돌리기용, 남겨둔다) +DROP TABLE IF EXISTS _cpg_weight_seed_backup; +CREATE TABLE _cpg_weight_seed_backup AS +SELECT p.id, p.product_code, p.weight_g AS old_weight_g, now() AS backed_up_at + FROM cupang_products p + JOIN _cpg_wseed s ON s.product_code = p.product_code; + +UPDATE cupang_products p + SET weight_g = s.weight_g + FROM _cpg_wseed s + WHERE p.product_code = s.product_code + AND p.weight_g IS NULL; + +-- 반영 결과 +SELECT count(*) AS "무게가 들어간 제품 수" + FROM cupang_products p JOIN _cpg_wseed s ON s.product_code = p.product_code + WHERE p.weight_g IS NOT NULL; + +-- 이미 다른 무게가 들어 있어 건너뛴 제품(화면에서 입력한 값 유지) +SELECT p.product_code AS "기존 무게 유지", p.weight_g AS "현재 무게", s.weight_g AS "시드 무게" + FROM cupang_products p JOIN _cpg_wseed s ON s.product_code = p.product_code + WHERE p.weight_g IS DISTINCT FROM s.weight_g; + +-- cupang_products 에 없는 제품코드 (설정 화면에서 등록한 뒤 수정 팝업으로 무게 입력, 또는 등록 후 이 시드 다시 실행) +SELECT s.product_code AS "미등록 제품코드", s.weight_g AS "포장무게(g)" + FROM _cpg_wseed s + WHERE NOT EXISTS (SELECT 1 FROM cupang_products p WHERE p.product_code = s.product_code) + ORDER BY s.product_code; + +COMMIT; diff --git a/tests/test_cupang_weight.py b/tests/test_cupang_weight.py new file mode 100644 index 0000000..a1fe79d --- /dev/null +++ b/tests/test_cupang_weight.py @@ -0,0 +1,123 @@ +"""쿠팡 밀크런 — 제품 포장무게(g) (마이그레이션 007). + +DB 없이 돈다: 입력 읽기(parse_weight_g)와, 가짜 연결로 등록·수정 SQL 이 무게 칸 유무에 맞게 +만들어지는지(열·자리표시자·값 개수) 확인한다. +""" +from __future__ import annotations + +import re +from typing import Any + +import pytest + +from app.modules.cupang.db import CupangDBStore +from app.modules.cupang.store import parse_weight_g + + +def test_parse_weight_g(): + assert parse_weight_g("1,070") == 1070 + assert parse_weight_g(" 1,070 ") == 1070 + assert parse_weight_g("1070g") == 1070 + assert parse_weight_g("1070 G") == 1070 + assert parse_weight_g("1070.0") == 1070 + assert parse_weight_g(450) == 450 + assert parse_weight_g("0") == 0 + for empty in ("", " ", None): + assert parse_weight_g(empty) is None + for bad in ("abc", "-5", "0.5", "1,000,001", "nan"): + with pytest.raises(ValueError): + parse_weight_g(bad) + + +class _Cur: + def __init__(self, row): + self._row = row + self.rowcount = 1 + + def fetchone(self): + return self._row + + +class _Conn: + def __init__(self, log, row): + self.log, self.row = log, row + + def execute(self, sql, params=None): + self.log.append((sql, params)) + if "information_schema" in sql: + return _Cur(None) + if sql.lstrip().startswith("SELECT 1 FROM cupang"): + return _Cur(None) # 제품코드 중복·상자 규칙 없음 + return _Cur(dict(self.row)) + + def transaction(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +class _Pool: + def __init__(self, row): + self.log: list[tuple[str, Any]] = [] + self.row = row + + def connection(self): + return _Conn(self.log, self.row) + + +ROW = {"id": 7, "product_code": "MS-9809", "product_name": "미라클통", "coupang_item_code": "", + "active": True, "sort_order": 0, "weight_g": 1070} + + +def _store(weight: bool) -> tuple[CupangDBStore, _Pool]: + st = CupangDBStore.__new__(CupangDBStore) + pool = _Pool(ROW if weight else {k: v for k, v in ROW.items() if k != "weight_g"}) + st._pool = pool + st._weight_col = weight or False + return st, pool + + +def _main_sql(pool: _Pool, verb: str) -> tuple[str, Any]: + return next((q, p) for q, p in pool.log if q.lstrip().startswith(verb)) + + +def test_upsert_with_weight(): + st, pool = _store(True) + out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070) + sql, params = _main_sql(pool, "INSERT") + assert "weight_g)" in sql and "%(w)s)" in sql + assert "weight_g = COALESCE(%(w)s, cupang_products.weight_g)" in sql # 비워 두면 기존 무게 유지 + assert params["w"] == 1070 + assert set(re.findall(r"%\((\w+)\)s", sql)) <= set(params) + assert out["weight_g"] == 1070 + + +def test_upsert_without_column_ignores_weight(): + st, pool = _store(False) + out = st.upsert_product(product_code="MS-9809", product_name="미라클통", weight_g=1070) + sql, _ = _main_sql(pool, "INSERT") + assert "weight_g" not in sql + assert out["weight_g"] is None + + +def test_update_weight_set_clear_keep(): + for weight_arg, expect_col, expect_val in ((950, True, 950), (None, True, None), (..., False, None)): + st, pool = _store(True) + st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809", + weight_g=weight_arg) + sql, params = _main_sql(pool, "UPDATE cupang_products") + assert ("weight_g = %s" in sql) is expect_col, weight_arg + assert sql.count("%s") == len(params) # 자리표시자 = 값 개수 + if expect_col: + assert params[-2] == expect_val and params[-1] == 7 + + +def test_update_without_column_ignores_weight(): + st, pool = _store(False) + st.update_product(product_id=7, product_name="미라클통", product_code="MS-9809", weight_g=950) + sql, params = _main_sql(pool, "UPDATE cupang_products") + assert "weight_g" not in sql and sql.count("%s") == len(params) == 4