feat(malaysia): 재고조사에 엑셀 업로드 일괄 입력 추가 (랙 입력 대신)
랙 칸에 하나씩 입력하는 대신, 상품명/자체상품코드/수량 3열(또는 코드·수량
2열) xlsx 를 업로드하면 daily_stocktake_line 을 직접 채우는
/stocktakes/{id}/lines/upload 엔드포인트 추가. 등록 안 된 코드·숫자 아닌
수량은 자동 스킵하고 결과를 배너로 안내.
랙이 라인의 단일 출처로 설계돼 있어(rack/bulk 저장 시 라인 전체 재생성) 업로드
값이 랙 저장으로 덮어써질 수 있음 — 화면에 안내 문구 추가하고, 랙을 거치지
않고 바로 확정하는 "라인 기준 확정" 버튼(기존 /finalize 엔드포인트 재사용)을
별도로 노출.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -94,6 +94,35 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if upload_ok is not none %}
|
||||
<div class="erp-card" style="margin-bottom:12px;{% if upload_skip %}border-color:#f59e0b;background:#fffbeb;{% else %}border-color:#16a34a;background:#f0fdf4;{% endif %}">
|
||||
<strong>엑셀 업로드 완료</strong> — {{ upload_ok }}건 반영.
|
||||
{% if upload_skip %}<div style="color:#b45309;margin-top:4px;">건너뜀(코드 미등록/수량오류): {{ upload_skip }}</div>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if is_draft %}
|
||||
<div class="erp-card" style="margin-bottom:12px;">
|
||||
<div class="cpg-card-head"><h2>엑셀 업로드로 일괄 입력 (랙 대신)</h2></div>
|
||||
<p class="erp-muted" style="margin:4px 0 10px;">
|
||||
열 A=상품명(참고용) · B=자체상품코드 · C=수량 형식의 xlsx. 등록 안 된 코드·숫자 아닌 수량은 자동 건너뜀.
|
||||
<strong>업로드 후에는 위 랙 입력을 저장하지 말고</strong> 아래 "라인 기준 확정" 버튼으로 바로 확정하세요
|
||||
(랙을 저장하면 랙 기준으로 라인이 재생성되어 업로드 값이 사라집니다).
|
||||
</p>
|
||||
<form method="post" action="/malaysia/stocktakes/{{ stocktake.id }}/lines/upload" enctype="multipart/form-data"
|
||||
style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
|
||||
<input class="erp-input" type="file" name="file" accept=".xlsx" required />
|
||||
<button type="submit" class="erp-btn erp-btn-outline">업로드</button>
|
||||
</form>
|
||||
{% if is_admin %}
|
||||
<form method="post" action="/malaysia/stocktakes/{{ stocktake.id }}/finalize" style="margin-top:10px;"
|
||||
onsubmit="return confirm('현재 \'최종 계산\' 표에 있는 라인 데이터 그대로 확정합니다(랙 입력은 무시). 확정하면 전산 재고와의 차이가 STOCKTAKE 이동으로 기록되고 이후 수정 불가합니다. 계속?');">
|
||||
<button type="submit" class="erp-btn erp-btn-primary">라인 기준 확정 (랙 무시)</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="/malaysia/stocktakes/{{ stocktake.id }}/rack/bulk">
|
||||
<!-- 상단 정보 스트립 (한 줄) -->
|
||||
<div class="mys-info-bar">
|
||||
|
||||
Reference in New Issue
Block a user