feat(malaysia): 재고조사 확정 후 자동 비교 엑셀 다운로드 추가
마감재고 + 마감 다음날~오늘 일자별 순변동(IN-OUT±ADJUST±STOCKTAKE) = 계산값과 오늘 전산재고(current_stock)를 아이템별로 비교하는 엑셀(2시트: 비교/일자별순변동). 확정된 재고조사 상세 화면에 "자동 비교 엑셀 다운로드" 버튼으로 노출. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -432,6 +432,42 @@ class MalaysiaStockStore:
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def movement_net_totals_by_date(
|
||||
self, *, warehouse_code: str, date_from: str, date_to: str
|
||||
) -> list[dict[str, Any]]:
|
||||
"""기간 내 일자 × 낱개 아이템별 '부호 포함 순변동' 합계.
|
||||
|
||||
`current_stock()` 과 동일한 부호 규칙: IN=+, OUT=-, ADJUST/STOCKTAKE 는
|
||||
저장된 부호 그대로. 재고조사 확정 이후 순변동을 날짜별로 추적할 때 사용.
|
||||
반환: [{"movement_date": "2026-09-10", "item_code": "MT-0750", "net_qty": -3}, ...]
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT movement_date, item_code,
|
||||
SUM(CASE
|
||||
WHEN movement_type = 'IN' THEN qty
|
||||
WHEN movement_type = 'OUT' THEN -qty
|
||||
ELSE qty -- ADJUST/STOCKTAKE 는 부호 포함 저장
|
||||
END) AS net_qty
|
||||
FROM stock_movement
|
||||
WHERE warehouse_code = %s
|
||||
AND movement_date >= %s
|
||||
AND movement_date <= %s
|
||||
GROUP BY movement_date, item_code
|
||||
ORDER BY movement_date, item_code
|
||||
""",
|
||||
(warehouse_code, date_from, date_to),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"movement_date": str(r["movement_date"]),
|
||||
"item_code": r["item_code"],
|
||||
"net_qty": int(r["net_qty"] or 0),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def current_stock(self, *, warehouse_code: str) -> dict[str, int]:
|
||||
"""창고별 현재고(낱개 아이템 기준).
|
||||
|
||||
|
||||
@@ -790,6 +790,140 @@ async def stocktake_detail(request: Request, stocktake_id: int) -> HTMLResponse:
|
||||
return render_template(request, "malaysia/stocktake_detail.html", ctx)
|
||||
|
||||
|
||||
@router.get("/stocktakes/{stocktake_id:int}/export-compare")
|
||||
async def stocktake_export_compare(request: Request, stocktake_id: int) -> StreamingResponse:
|
||||
"""이 재고조사(마감) 이후 오늘까지 자동 비교 엑셀.
|
||||
|
||||
마감재고(재고조사 total_qty) + 마감 다음날부터 오늘까지의 순변동(IN-OUT±ADJUST±STOCKTAKE)을
|
||||
더한 "계산값"과 오늘 전산재고(current_stock)를 나란히 비교한다. 정상이면 두 값이 항상 같다
|
||||
(재고조사 확정 시 차이를 STOCKTAKE 이동으로 정확히 반영하는 구조이므로) — 다르면 이후 데이터
|
||||
보정/삭제 등으로 어긋난 것이니 원인 확인용.
|
||||
|
||||
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
|
||||
try:
|
||||
computed = st.compute_result(stocktake_id=stocktake_id, bom_map=_bom_map(request))
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="재고조사를 찾을 수 없습니다.")
|
||||
head = computed["stocktake"]
|
||||
wh = head["warehouse_code"]
|
||||
base_date = str(head["stocktake_date"])[:10]
|
||||
today = today_kst().isoformat()
|
||||
|
||||
baseline = {r["item_code"]: r["total_qty"] for r in computed["rows"]}
|
||||
d0 = _date.fromisoformat(base_date) + _timedelta(days=1)
|
||||
d1 = _date.fromisoformat(today)
|
||||
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=today)
|
||||
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"]
|
||||
|
||||
current = st.current_stock(warehouse_code=wh)
|
||||
|
||||
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(current)) - 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"마감재고({base_date})", "기간중순변동", "계산값", "오늘전산재고", "차이"]
|
||||
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 = current.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}_{base_date}_{today}.xlsx"
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="{fname}"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/stocktakes/{stocktake_id:int}/lines/bulk")
|
||||
async def stocktake_lines_bulk(
|
||||
request: Request, stocktake_id: int, user: dict[str, Any] = Depends(_require_user)
|
||||
|
||||
@@ -88,6 +88,10 @@
|
||||
{% include "malaysia/_i18n.html" %}
|
||||
<div class="erp-page-actions">
|
||||
<a class="erp-btn erp-btn-primary" href="/malaysia/stocktakes?wh={{ stocktake.warehouse_code }}">◀◀ 조사 목록</a>
|
||||
{% if stocktake.status=='finalized' %}
|
||||
<a class="erp-btn erp-btn-outline" href="/malaysia/stocktakes/{{ stocktake.id }}/export-compare"
|
||||
title="마감재고 + 이후 일자별 변동 = 오늘 전산재고 자동 비교 엑셀">자동 비교 엑셀 다운로드</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<form method="post" action="/malaysia/stocktakes/{{ stocktake.id }}/rack/bulk">
|
||||
|
||||
Reference in New Issue
Block a user