feat(cupang): 확정 시 출고리스트 엑셀 생성, 센터 선택 드롭다운 제거
- ③ "센터를 고르면 바로 추가" 드롭다운 삭제(업로드가 센터를 자동 구성) - 확정 payload 에 상자 종류별 박스 수(box_summary, 예: 쿠팡상자41) 추가 → 출고 묶음의 outbound_summary 로 저장 - 센터입고일 = 출고일 + 1일로 저장(쿠팡 발주서 입고예정일과 일치) - GET /cupang/export.xlsx?date=YYYY-MM-DD — 쿠팡로켓 밀크런 출고리스트 양식 (제목/회사명/머리글 + 센터 단위 병합, 시트명 YYYYMMDD). 확정 직후 자동 다운로드 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,7 +16,7 @@ from fractions import Fraction
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from datetime import date as _date
|
||||
from datetime import date as _date, timedelta as _timedelta
|
||||
|
||||
from app.timezone import today_kst
|
||||
|
||||
@@ -236,6 +236,141 @@ async def index(request: Request) -> HTMLResponse:
|
||||
)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 출고리스트 엑셀 — 확정한 출고일 기준 (쿠팡로켓 밀크런 양식)
|
||||
# ════════════════════════════════════════════════════════════
|
||||
EXPORT_COMPANY = "㈜더블엑스코퍼레이션"
|
||||
EXPORT_WORKER = "핫프렌즈"
|
||||
EXPORT_DOW = ["월", "화", "수", "목", "금", "토", "일"]
|
||||
EXPORT_HEADERS = [
|
||||
"구분", "작성일", "출고일", "센터입고일", "입고센터", "출고방식",
|
||||
"제품코드", "제품명", "수량", "출고", "작업자",
|
||||
]
|
||||
|
||||
|
||||
def _export_workbook(ship_date: str, shipments: list[dict[str, Any]]) -> Any:
|
||||
"""출고 묶음 목록 → 스크린샷 양식의 워크북. 시트명은 출고일(YYYYMMDD)."""
|
||||
from openpyxl import Workbook # noqa: WPS433
|
||||
from openpyxl.styles import Alignment, Border, Font, Side # noqa: WPS433
|
||||
from openpyxl.utils import get_column_letter # noqa: WPS433
|
||||
|
||||
d = _date.fromisoformat(ship_date)
|
||||
tag = d.strftime("%Y%m%d")
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = tag
|
||||
|
||||
thin = Side(style="thin", color="000000")
|
||||
box = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||
center_align = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
left_align = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
|
||||
# 제목 (B2:L2)
|
||||
ws.merge_cells(start_row=2, start_column=2, end_row=2, end_column=12)
|
||||
title = ws.cell(row=2, column=2, value=f"{tag}({EXPORT_DOW[d.weekday()]}) 쿠팡로켓 밀크런 출고리스트")
|
||||
title.font = Font(size=16, bold=True)
|
||||
title.alignment = center_align
|
||||
|
||||
ws.cell(row=4, column=2, value=EXPORT_COMPANY).font = Font(size=11)
|
||||
|
||||
# 머리글 (B5:L5)
|
||||
for i, name in enumerate(EXPORT_HEADERS):
|
||||
c = ws.cell(row=5, column=2 + i, value=name)
|
||||
c.font = Font(bold=True)
|
||||
c.alignment = center_align
|
||||
c.border = box
|
||||
|
||||
row = 6
|
||||
seq = 0
|
||||
document_date = ""
|
||||
for sh in shipments:
|
||||
lines = sh.get("lines") or []
|
||||
if not lines:
|
||||
continue
|
||||
document_date = str(sh.get("document_date") or document_date)
|
||||
start = row
|
||||
for ln in lines:
|
||||
seq += 1
|
||||
ws.cell(row=row, column=2, value=seq) # 구분
|
||||
ws.cell(row=row, column=8, value=ln.get("product_code") or "") # 제품코드
|
||||
ws.cell(row=row, column=9, value=ln.get("product_name_snapshot") or "") # 제품명
|
||||
ws.cell(row=row, column=10, value=int(ln.get("quantity") or 0)) # 수량
|
||||
row += 1
|
||||
end = row - 1
|
||||
|
||||
# 센터 단위로 병합되는 칸들
|
||||
merged_cols = {
|
||||
3: str(sh.get("document_date") or ""),
|
||||
4: str(sh.get("ship_date") or ""),
|
||||
5: str(sh.get("center_arrival_date") or ""),
|
||||
6: sh.get("center_name_snapshot") or "",
|
||||
7: sh.get("ship_method") or "",
|
||||
11: sh.get("outbound_summary") or "",
|
||||
12: EXPORT_WORKER,
|
||||
}
|
||||
for col, value in merged_cols.items():
|
||||
if end > start:
|
||||
ws.merge_cells(start_row=start, start_column=col, end_row=end, end_column=col)
|
||||
ws.cell(row=start, column=col, value=value)
|
||||
|
||||
for r in range(start, end + 1):
|
||||
for col in range(2, 13):
|
||||
cell = ws.cell(row=r, column=col)
|
||||
cell.border = box
|
||||
cell.alignment = left_align if col == 9 else center_align
|
||||
|
||||
widths = {2: 6, 3: 12, 4: 12, 5: 12, 6: 11, 7: 10, 8: 12, 9: 26, 10: 8, 11: 12, 12: 11}
|
||||
for col, w in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = w
|
||||
ws.row_dimensions[2].height = 28
|
||||
|
||||
return wb
|
||||
|
||||
|
||||
@router.get("/export.xlsx")
|
||||
async def export_shipments_xlsx(request: Request, date: str = "") -> Any:
|
||||
"""출고일 기준 출고리스트 엑셀 다운로드. 시트명 = YYYYMMDD."""
|
||||
from io import BytesIO # noqa: WPS433
|
||||
|
||||
from fastapi.responses import StreamingResponse # noqa: WPS433
|
||||
|
||||
guard = _guard(request)
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, _user = guard
|
||||
|
||||
ship_date = (date or "").strip()
|
||||
try:
|
||||
_date.fromisoformat(ship_date)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="출고일자(date=YYYY-MM-DD)가 필요합니다.")
|
||||
|
||||
heads = [
|
||||
s for s in store.list_shipments(date_from=ship_date, date_to=ship_date)
|
||||
if s.get("status") != "취소"
|
||||
]
|
||||
shipments = []
|
||||
for h in sorted(heads, key=lambda x: (x.get("center_name_snapshot") or "")):
|
||||
full = store.get_shipment(shipment_id=h["id"])
|
||||
if full:
|
||||
shipments.append(full)
|
||||
if not shipments:
|
||||
raise HTTPException(status_code=404, detail="해당 출고일의 출고 묶음이 없습니다.")
|
||||
|
||||
wb = _export_workbook(ship_date, shipments)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
tag = ship_date.replace("-", "")
|
||||
filename = f"{tag}_cupang_milkrun.xlsx"
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 출고 묶음 — 등록 / 수정 / 상세
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -1242,6 +1377,7 @@ async def box_calc_confirm(
|
||||
rules = {r["product_code"]: r for r in store.list_box_rules()}
|
||||
known_centers = {str(c["id"]): c for c in store.list_centers(include_inactive=True)}
|
||||
today = today_kst().isoformat()
|
||||
arrival_date = (_date.fromisoformat(ship_date) + _timedelta(days=1)).isoformat()
|
||||
worker = str(user.get("name") or user.get("email") or "")
|
||||
|
||||
plans: list[dict[str, Any]] = []
|
||||
@@ -1296,7 +1432,10 @@ async def box_calc_confirm(
|
||||
except (TypeError, ValueError):
|
||||
boxes = 0
|
||||
pieces = sum(merged.values())
|
||||
summary = f"{boxes}박스 · {pieces}개" if boxes else f"{pieces}개"
|
||||
# 화면에서 고른 상자 종류별 박스 수(예: "쿠팡상자41"). 출고리스트 엑셀의 "출고" 칸.
|
||||
summary = str(raw.get("box_summary") or "").strip()
|
||||
if not summary:
|
||||
summary = f"{boxes}박스 · {pieces}개" if boxes else f"{pieces}개"
|
||||
|
||||
plans.append({"center": center, "method": method, "lines": lines, "summary": summary})
|
||||
|
||||
@@ -1312,8 +1451,8 @@ async def box_calc_confirm(
|
||||
header={
|
||||
"document_date": today,
|
||||
"ship_date": ship_date,
|
||||
# 센터입고일은 출고일과 같게 두고, 필요하면 출고 상세에서 고친다.
|
||||
"center_arrival_date": ship_date,
|
||||
# 센터입고일 = 출고일 다음 날(쿠팡 발주서의 입고예정일). 상세에서 고칠 수 있다.
|
||||
"center_arrival_date": arrival_date,
|
||||
"center_id": center["id"],
|
||||
"center_name_snapshot": center["name"],
|
||||
"ship_method": plan["method"],
|
||||
|
||||
@@ -111,16 +111,8 @@
|
||||
등록된 입고센터가 없습니다. <a href="/cupang/centers">입고센터 관리</a>에서 먼저 센터를 추가하세요.
|
||||
</p>
|
||||
{% else %}
|
||||
<div class="cpg-center-pick">
|
||||
<select class="erp-select" id="cpg-center-pick" aria-label="센터 추가">
|
||||
<option value="">— 센터를 고르면 바로 추가 —</option>
|
||||
{% for c in centers %}
|
||||
<option value="{{ c.id }}">{{ c.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="cpg-dist-list" id="cpg-dist-list"></div>
|
||||
<p class="erp-muted" id="cpg-dist-empty">추가한 센터가 여기에 표시됩니다.</p>
|
||||
<p class="erp-muted" id="cpg-dist-empty">발주 파일을 업로드하면 센터가 여기에 표시됩니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -1242,10 +1234,28 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
// 출고 엑셀 "출고" 칸 — 상자 종류별 박스 수 (예: 쿠팡상자41, 3호상자2)
|
||||
var byType = {};
|
||||
var order = [];
|
||||
rows.forEach(function (a) {
|
||||
var t;
|
||||
if (a.key.indexOf("m:") === 0) {
|
||||
t = mixTypeOf(a.key);
|
||||
} else {
|
||||
var code = a.key.slice(2);
|
||||
var hit = calc.results.filter(function (r) { return r.product_code === code; })[0];
|
||||
t = (hit && hit.box_name) || "쿠팡상자";
|
||||
}
|
||||
if (!(t in byType)) { byType[t] = 0; order.push(t); }
|
||||
byType[t] += a.count;
|
||||
});
|
||||
var boxSummary = order.map(function (t) { return t + byType[t]; }).join(", ");
|
||||
|
||||
return {
|
||||
center_id: cid,
|
||||
ship_method: methods[String(cid)] || "",
|
||||
boxes: boxes,
|
||||
box_summary: boxSummary,
|
||||
items: items
|
||||
};
|
||||
});
|
||||
@@ -1319,6 +1329,8 @@
|
||||
})
|
||||
.then(function (data) {
|
||||
var d = (data && data.ship_date) || picked;
|
||||
// 확정한 출고일의 출고리스트 엑셀을 내려받는다.
|
||||
window.location.href = "/cupang/export.xlsx?date=" + encodeURIComponent(d);
|
||||
// 업로드한 출고일이 여러 개면 남은 날짜 작업을 이어서 한다.
|
||||
var idx = dateOrder.indexOf(activeDate);
|
||||
if (idx >= 0 && dateOrder.length > 1) {
|
||||
@@ -1334,8 +1346,11 @@
|
||||
return;
|
||||
}
|
||||
var parts = d.split("-");
|
||||
// 달력으로 이동해 방금 만든 출고 묶음을 보여준다.
|
||||
window.location.href = "/cupang/?year=" + parts[0] + "&month=" + parseInt(parts[1], 10) + "&date=" + d;
|
||||
// 달력으로 이동해 방금 만든 출고 묶음을 보여준다(엑셀 저장 뒤).
|
||||
cfmMsg.textContent = "출고리스트 엑셀을 저장했습니다. 달력으로 이동합니다…";
|
||||
setTimeout(function () {
|
||||
window.location.href = "/cupang/?year=" + parts[0] + "&month=" + parseInt(parts[1], 10) + "&date=" + d;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(function (err) {
|
||||
cfmMsg.textContent = (err && err.message) || "확정 실패 — 다시 시도하세요.";
|
||||
|
||||
Reference in New Issue
Block a user