From bac6392e54fcc709555e20a927919a7a0d011811 Mon Sep 17 00:00:00 2001 From: king Date: Sun, 20 Sep 2026 21:28:27 +0900 Subject: [PATCH] =?UTF-8?q?feat(malaysia):=20=EC=9E=AC=EA=B3=A0=EC=A1=B0?= =?UTF-8?q?=EC=82=AC=20=ED=99=95=EC=A0=95=20=EC=97=86=EC=9D=B4=20=EC=9E=84?= =?UTF-8?q?=EC=9D=98=20=EA=B8=B0=EC=A4=80=EC=9D=BC=20=EA=B8=B0=EC=A4=80=20?= =?UTF-8?q?=EC=9E=90=EB=8F=99=20=EB=B9=84=EA=B5=90=20=EC=97=91=EC=85=80=20?= =?UTF-8?q?=EB=8B=A4=EC=9A=B4=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 기존 자동 비교는 "확정된 재고조사"에 의존해 실제 최근 확정일(예: 2026-06-17)로만 동작했음 — 9/9처럼 확정을 안 거친 임의 기준일은 반영 불가했던 문제. movement 이력만으로 특정 일자까지의 누적재고를 재구성하는 current_stock_as_of() 추가, 신규 엔드포인트 /malaysia/movements/export-compare (쿼리: wh, date=기준일, to=종료일 기본 오늘)로 기준일재고 + 이후 일자별 순변동 + 종료일전산재고 + 차이를 엑셀 2시트로 제공. 재고관리 메인 화면(전산 재고 현황 카드)에 기준일/종료일 날짜 선택 + 다운로드 버튼으로 노출. 기존 재고조사 상세 화면의 확정 기준 비교 버튼은 그대로 유지. Co-Authored-By: Claude Sonnet 5 --- app/modules/malaysia/db.py | 25 ++++ app/modules/malaysia/router.py | 139 ++++++++++++++++++ .../malaysia/templates/malaysia/index.html | 28 +++- 3 files changed, 188 insertions(+), 4 deletions(-) diff --git a/app/modules/malaysia/db.py b/app/modules/malaysia/db.py index 6649285..90b3e36 100644 --- a/app/modules/malaysia/db.py +++ b/app/modules/malaysia/db.py @@ -468,6 +468,31 @@ class MalaysiaStockStore: for r in rows ] + def current_stock_as_of(self, *, warehouse_code: str, as_of_date: str) -> dict[str, int]: + """창고별 특정 일자(포함)까지 누적된 재고(낱개 아이템 기준). + + `current_stock()` 과 동일 부호 규칙(IN=+, OUT=-, ADJUST/STOCKTAKE 는 저장된 부호 그대로), + movement_date <= as_of_date 로만 제한. 재고조사 확정 여부와 무관하게 이동 이력만으로 + 특정 시점의 재고를 재구성할 때 사용. + 반환: { item_code: qty } + """ + with self._pool.connection() as conn: + rows = conn.execute( + """ + SELECT item_code, + SUM(CASE + WHEN movement_type = 'IN' THEN qty + WHEN movement_type = 'OUT' THEN -qty + ELSE qty -- ADJUST/STOCKTAKE 는 부호 포함 저장 + END) AS qty + FROM stock_movement + WHERE warehouse_code = %s AND movement_date <= %s + GROUP BY item_code + """, + (warehouse_code, as_of_date), + ).fetchall() + return {r["item_code"]: int(r["qty"] or 0) for r in rows} + def current_stock(self, *, warehouse_code: str) -> dict[str, int]: """창고별 현재고(낱개 아이템 기준). diff --git a/app/modules/malaysia/router.py b/app/modules/malaysia/router.py index b0d49c6..5f16e47 100644 --- a/app/modules/malaysia/router.py +++ b/app/modules/malaysia/router.py @@ -600,6 +600,145 @@ async def movements_export_daily(request: Request) -> StreamingResponse: ) +@router.get("/movements/export-compare") +async def movements_export_compare(request: Request) -> StreamingResponse: + """임의 기준일 대비 자동 비교 엑셀 — 재고조사 확정 여부와 무관하게 movement 이력만으로 계산. + + 기준일까지 누적재고(current_stock_as_of) + 기준일 다음날~종료일 일자별 순변동을 더한 + "계산값"과, 종료일 시점 누적재고를 비교한다. 이동 이력을 기간으로 쪼개 더한 것이므로 + 두 값은 항상 일치한다 — 어긋나면 이력 데이터 자체를 확인해야 한다. + + 쿼리: wh(창고), date(기준일 YYYY-MM-DD, 필수), to(종료일, 기본 오늘) + Sheet1 "비교": 아이템별 기준재고/기간중순변동/계산값/종료일전산재고/차이. + Sheet2 "일자별순변동": 아이템 × 날짜(기준일 다음날~종료일) 그리드. + """ + import io # noqa: WPS433 + from datetime import date as _date, timedelta as _timedelta # noqa: WPS433 + + guard = _guard(request) + if not isinstance(guard, tuple): + return guard # type: ignore[return-value] + st, _user = guard + wh = _selected_wh(request, st) + base_date = (request.query_params.get("date") or "").strip() + if not base_date: + raise HTTPException(status_code=400, detail="date 쿼리(기준일)가 필요합니다.") + to = (request.query_params.get("to") or today_kst().isoformat()).strip() + try: + db0 = _date.fromisoformat(base_date[:10]) + d1 = _date.fromisoformat(to[:10]) + except ValueError: + raise HTTPException(status_code=400, detail="날짜 형식은 YYYY-MM-DD 이어야 합니다.") + if d1 < db0: + raise HTTPException(status_code=400, detail="기준일이 종료일보다 늦습니다.") + + baseline = st.current_stock_as_of(warehouse_code=wh, as_of_date=db0.isoformat()) + d0 = db0 + _timedelta(days=1) + dates = [(d0 + _timedelta(days=i)).isoformat() for i in range((d1 - d0).days + 1)] if d1 >= d0 else [] + net_rows = ( + st.movement_net_totals_by_date(warehouse_code=wh, date_from=d0.isoformat(), date_to=d1.isoformat()) + if dates else [] + ) + grid: dict[str, dict[str, int]] = {} + period_total: dict[str, int] = {} + for r in net_rows: + grid.setdefault(r["item_code"], {})[r["movement_date"]] = r["net_qty"] + period_total[r["item_code"]] = period_total.get(r["item_code"], 0) + r["net_qty"] + + ending = st.current_stock_as_of(warehouse_code=wh, as_of_date=d1.isoformat()) + + reader = _reader(request) + names = reader.name_map() if reader else {} + item_names = st.item_name_map() + items = st.list_items(kind="individual") + codes = [it["item_code"] for it in items] + codes += sorted((set(baseline) | set(grid) | set(ending)) - set(codes)) + + def _name(code: str) -> str: + return names.get(code) or item_names.get(code) or code + + from openpyxl import Workbook # noqa: WPS433 + from openpyxl.styles import Alignment, Border, Font, PatternFill, Side # noqa: WPS433 + from openpyxl.utils import get_column_letter # noqa: WPS433 + + wb = Workbook() + ws1 = wb.active + ws1.title = "비교" + header1 = [ + "상품명", "자체상품코드", f"기준재고({db0.isoformat()})", "기간중순변동", + "계산값", f"{d1.isoformat()}전산재고", "차이", + ] + ws1.append(header1) + diff_rows: list[int] = [] + for code in codes: + base = baseline.get(code, 0) + period = period_total.get(code, 0) + calc = base + period + cur = ending.get(code, 0) + diff = calc - cur + ws1.append([_name(code), code, base, period, calc, cur, diff]) + if diff != 0: + diff_rows.append(ws1.max_row) + + fill1 = PatternFill(start_color="FF4472C4", end_color="FF4472C4", fill_type="solid") + head_font = Font(color="FFFFFFFF", bold=True) + center = Alignment(horizontal="center", vertical="center") + for col in range(1, len(header1) + 1): + cell = ws1.cell(row=1, column=col) + cell.fill = fill1 + cell.font = head_font + cell.alignment = center + bad_fill = PatternFill(start_color="FFFCE4E4", end_color="FFFCE4E4", fill_type="solid") + for row in diff_rows: + for col in range(1, len(header1) + 1): + ws1.cell(row=row, column=col).fill = bad_fill + for col in range(3, len(header1) + 1): + letter = get_column_letter(col) + for row in range(2, ws1.max_row + 1): + ws1.cell(row=row, column=col).alignment = center + ws1.column_dimensions[letter].width = 14 + longest = max((sum(2 if ord(ch) > 0x1100 else 1 for ch in _name(c)) for c in codes), default=8) + ws1.column_dimensions["A"].width = max(14, min(40, longest + 2)) + ws1.column_dimensions["B"].width = 16 + ws1.freeze_panes = "A2" + + ws2 = wb.create_sheet("일자별순변동") + header2 = ["상품명", "자체상품코드"] + [f"{d[5:7]}월 {d[8:10]}일" for d in dates] + ws2.append(header2) + for code in codes: + per = grid.get(code, {}) + ws2.append([_name(code), code] + [(per[d] if per.get(d) else None) for d in dates]) + fill2 = PatternFill(start_color="FF9B3C28", end_color="FF9B3C28", fill_type="solid") + thin = Side(style="thin", color="FFBFBFBF") + box = Border(left=thin, right=thin, top=thin, bottom=thin) + for col in range(1, len(header2) + 1): + cell = ws2.cell(row=1, column=col) + cell.fill = fill2 + cell.font = head_font + cell.alignment = center + for row in range(2, ws2.max_row + 1): + for col in range(1, len(header2) + 1): + cell = ws2.cell(row=row, column=col) + cell.border = box + if col >= 3: + cell.alignment = center + ws2.freeze_panes = "C2" + ws2.column_dimensions["A"].width = max(14, min(40, longest + 2)) + ws2.column_dimensions["B"].width = 16 + for col in range(3, len(header2) + 1): + ws2.column_dimensions[get_column_letter(col)].width = 11 + + buf = io.BytesIO() + wb.save(buf) + buf.seek(0) + fname = f"malaysia_compare_{wh}_{db0.isoformat()}_{d1.isoformat()}.xlsx" + return StreamingResponse( + buf, + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={"Content-Disposition": f'attachment; filename="{fname}"'}, + ) + + @router.get("/rack/export") async def rack_export(request: Request) -> StreamingResponse: """창고 랙 보기 데이터를 엑셀로 내보낸다. diff --git a/app/modules/malaysia/templates/malaysia/index.html b/app/modules/malaysia/templates/malaysia/index.html index 53d4d9b..acc71d1 100644 --- a/app/modules/malaysia/templates/malaysia/index.html +++ b/app/modules/malaysia/templates/malaysia/index.html @@ -27,10 +27,15 @@

전산 재고 현황 — 낱개 기준 ({{ rows|length }})

현재고 = 입고 − 출고 + 조정 + 재고조사반영 (콤보는 낱개로 분해 반영됨) - {% if latest_stocktake_finalized %} - 자동 비교 엑셀 다운로드 ({{ latest_stocktake_date }}) - {% endif %} +
+
+ 기준일 대비 자동 비교 엑셀 + + ~ + + + 기준일=그 날짜까지 누적재고, 종료일 비우면 오늘. 이동 이력만으로 계산(재고조사 확정 불필요)
@@ -97,6 +102,21 @@ + + {% if is_super %}

위험 구역 (슈퍼관리자)