diff --git a/app/modules/malaysia/router.py b/app/modules/malaysia/router.py index 5f16e47..c26004a 100644 --- a/app/modules/malaysia/router.py +++ b/app/modules/malaysia/router.py @@ -927,6 +927,8 @@ async def stocktake_detail(request: Request, stocktake_id: int) -> HTMLResponse: "missing_bom": computed["missing_bom"], "is_draft": is_draft, "has_prev_rack": has_prev_rack, + "upload_ok": request.query_params.get("upload_ok"), + "upload_skip": request.query_params.get("upload_skip"), } ) return render_template(request, "malaysia/stocktake_detail.html", ctx) @@ -1125,6 +1127,86 @@ def _parse_rack_form(form: Any) -> list[dict[str, Any]]: return entries +@router.post("/stocktakes/{stocktake_id:int}/lines/upload") +async def stocktake_lines_upload( + request: Request, stocktake_id: int, user: dict[str, Any] = Depends(_require_user) +) -> RedirectResponse: + """엑셀 업로드로 SKU별 수량 일괄 입력(랙 입력 대신). daily_stocktake_line 을 직접 갱신한다. + + 형식: 열 A=상품명(참고용, 무시) · B=자체상품코드 · C=수량 (2열짜리 코드·수량만도 허용). + 헤더 행이 섞여 있어도 코드가 등록된 아이템이 아니거나 수량이 숫자가 아니면 자동 스킵. + + 주의: 랙이 daily_stocktake_line 의 "단일 출처"로 설계돼 있어(replace_rack 이 랙 기준으로 + 라인을 통째로 재생성함), 업로드 뒤에 화면에서 랙 입력을 저장하면 이 값이 사라진다. + 업로드 후에는 랙을 건드리지 말고 화면의 "라인 기준 확정" 버튼으로 바로 확정할 것. + """ + st = _store(request) + if st is None: + raise HTTPException(status_code=503, detail="malaysia_stock_db 미설정") + head = st.get_stocktake(stocktake_id=stocktake_id, with_lines=False) + if head is None: + raise HTTPException(status_code=404, detail="재고조사를 찾을 수 없습니다.") + if head["status"] != "draft": + raise HTTPException(status_code=400, detail="작성중인 조사만 입력할 수 있습니다.") + + form = await request.form() + upload = form.get("file") + if upload is None or not getattr(upload, "filename", ""): + raise HTTPException(status_code=400, detail="엑셀 파일을 선택하세요.") + data = await upload.read() + if not data: + raise HTTPException(status_code=400, detail="빈 파일입니다.") + + import io # noqa: WPS433 + from urllib.parse import urlencode # noqa: WPS433 + + from openpyxl import load_workbook # noqa: WPS433 + + try: + wb = load_workbook(io.BytesIO(data), data_only=True, read_only=True) + ws = wb.active + except Exception as exc: # noqa: BLE001 + raise HTTPException(status_code=400, detail=f"엑셀 파일을 읽을 수 없습니다: {exc}") + + valid_codes = {i["item_code"] for i in st.list_items(kind="individual")} + valid_codes |= {i["item_code"] for i in st.list_items(kind="set")} + + applied = 0 + skipped: list[str] = [] + for row in ws.iter_rows(values_only=True): + if not row: + continue + cells = list(row) + if len(cells) >= 3: + code_cell, qty_cell = cells[1], cells[2] + elif len(cells) == 2: + code_cell, qty_cell = cells[0], cells[1] + else: + continue + code = str(code_cell or "").strip().upper() + if code not in valid_codes: + if code: + skipped.append(code) + continue + raw_q = qty_cell.replace(",", "").strip() if isinstance(qty_cell, str) else qty_cell + try: + qf = float(raw_q) + n = int(qf) + if qf != n: + raise ValueError("정수 아님") + except (TypeError, ValueError): + skipped.append(f"{code}(수량오류)") + continue + try: + st.upsert_line(stocktake_id=stocktake_id, sku_code=code, qty=n) + applied += 1 + except ValueError as exc: + skipped.append(f"{code}({exc})") + + qs = urlencode({"upload_ok": applied, "upload_skip": ",".join(skipped[:20])}) + return RedirectResponse(url=f"/malaysia/stocktakes/{stocktake_id}?{qs}", status_code=303) + + @router.post("/stocktakes/{stocktake_id:int}/rack/bulk") async def stocktake_rack_bulk( request: Request, stocktake_id: int, user: dict[str, Any] = Depends(_require_user) diff --git a/app/modules/malaysia/templates/malaysia/stocktake_detail.html b/app/modules/malaysia/templates/malaysia/stocktake_detail.html index 4c38d7b..d624857 100644 --- a/app/modules/malaysia/templates/malaysia/stocktake_detail.html +++ b/app/modules/malaysia/templates/malaysia/stocktake_detail.html @@ -94,6 +94,35 @@ {% endif %} + {% if upload_ok is not none %} +
+ 열 A=상품명(참고용) · B=자체상품코드 · C=수량 형식의 xlsx. 등록 안 된 코드·숫자 아닌 수량은 자동 건너뜀. + 업로드 후에는 위 랙 입력을 저장하지 말고 아래 "라인 기준 확정" 버튼으로 바로 확정하세요 + (랙을 저장하면 랙 기준으로 라인이 재생성되어 업로드 값이 사라집니다). +
+ + {% if is_admin %} + + {% endif %} +