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 @@