Merge branch 'feat/inout-boxes-pallet-group-tab'

This commit is contained in:
2026-10-21 15:13:48 +09:00
16 changed files with 315 additions and 45 deletions
+12 -1
View File
@@ -62,7 +62,7 @@
## 상품 그룹·색상 (006, 2026-10-21)
- 옵션 → 상품 정보 위 **그룹** 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
- 옵션 **상품 그룹** 탭(2026-10-21 상품 정보 탭에서 분리) = 그룹 표(`inout_product_groups`: 이름·은 함유량·색상·순서, `POST /inout/settings/groups`·`…/{id}/delete`).
상품 줄 **그룹** 고르기 → 그 상품의 은 함유량·색상 = 그룹 값(자기 값 칸은 숨김·보존, 그룹 지우면 자기 값으로). 그룹 없는 상품은 상품마다.
계산은 `db._PRODUCT_SELECT_006`(silver_pct·color = 그룹 적용 값, own_* = 자기 값) 한 곳 — 목록·발주서 제품 고르기·발주 품목 사본이 같은 값.
- 색상 = 색없음·오렌지·파랑·회색·아이보리색(`store.COLORS` 키 none·orange·blue·gray·ivory → 이름·칸 색), 화면은 색 사각형 + 이름(`_macros.swatch`).
@@ -70,6 +70,15 @@
- 006 확인(`groups_ready`)은 연결을 열기 **전에** — 미적용이면 1분 기억(발주 저장 트랜잭션 안에서 두 번째 연결을 잡아 동시 발주에서 풀이 바닥났었다).
- 옵션 → 담당자 = 아이콘(구글 프로필 사진, 없으면 기본 아이콘) + 이름, 아래 이메일.
## 박스 입수·파렛트 (007, 2026-10-21)
- 옵션 → 상품 정보 **통 수량(박스)**·**뚜껑 수량(박스)** = 통·뚜껑이 한 박스에 몇 개(`inout_products.body_per_box`·`lid_per_box`, 1 이상 정수, 뚜껑 없으면 빈칸,
`store.validate_box_values`). 상품 정보 표 제목 행 = 가운데·굵게·13.2px(예전 12px × 110%).
- **새 발주서** 줄마다 "통·뚜껑 박스" 칸(`inout.js boxCell`) = 통 ⌈수량 ÷ 통 입수⌉박스 · 뚜껑 ⌈수량 ÷ 뚜껑 입수⌉박스, 힌트 = 통·뚜껑 입수의 **최소공배수**(둘 다 꽉 차는 수량 단위,
뚜껑 없으면 통 입수)와 지금 수량에 가까운 그 배수(누르면 수량 칸에), 배수면 "✓ 꽉 찹니다". 합계 줄 = 통·뚜껑·전체 박스 → **파렛트 ⌈전체 박스 ÷ 30⌉**(`store.PALLET_BOXES`) + 마지막 파렛트 박스 수.
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
## 오른쪽 달력 (2026-10-21)
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
@@ -78,6 +87,8 @@
- 프로젝트 달력 모양(일요일 시작·요일 줄 회색·오늘 검은 동그라미·토 파랑·일/공휴일 빨강 — 공휴일 표는 `project.store.holiday_name` 재사용).
공휴일 이름은 숫자 아래 한 줄(`.io-cal-hol`, 8.5px — 5글자까지 다 보임, 더 길면 … + 말풍선에 전체 이름).
- 날짜 칸 = 발주(발주일, 파랑)·입고(입고일, 초록) 건수(취소된 발주 제외), 누르면 그날 목록 팝업 → 발주서. 달 이동은 새로고침 없이 `GET /inout/api/calendar?month=YYYY-MM`(`db.calendar`).
- **메뉴를 옮겨도 달력은 다시 그리지 않음**(2026-10-21) — 마지막 달력(달·API 응답 글·칸 HTML)을 sessionStorage `io_cal_v1` 에 두고 `_calendar.html` 인라인 스크립트가 그리기 전에 붙임,
`inout.js` 는 서버 값을 다시 받아 **글이 달라졌을 때만** 다시 그린다(보던 달도 유지). `CAL_KEY` 는 `initCalendar` 안에 — 바깥 const 면 위에서 먼저 부를 때 TDZ 로 복원이 조용히 꺼진다.
## 시각 / 날짜
+25 -3
View File
@@ -25,9 +25,9 @@ from . import store
_SCAN_LIMIT = 20000 # 목록에서 상태 거르기 전에 읽는 발주서 상한
# 상품 정보 + 그룹(006) — 그룹 상품은 그룹의 은 함유량·색상, 그룹 없는 상품은 자기 값(own_*).
# p.* 다음에 같은 이름(silver_pct·color)을 다시 고르면 dict_row 는 뒤의 값(그룹 적용 값)을 쓴다. p.* 라 007 박스 입수 등 새 열도 따라온다.
_PRODUCT_SELECT_006 = (
"SELECT p.item_code, p.item_name, p.unit_price, p.weight_g, p.imported_at, p.updated_by, p.updated_at, "
"p.group_id, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
"SELECT p.*, g.name AS group_name, p.silver_pct AS own_silver_pct, COALESCE(p.color, 'none') AS own_color, "
"CASE WHEN g.id IS NULL THEN p.silver_pct ELSE g.silver_pct END AS silver_pct, "
"CASE WHEN g.id IS NULL THEN COALESCE(p.color, 'none') ELSE g.color END AS color "
"FROM inout_products p LEFT JOIN inout_product_groups g ON g.id = p.group_id"
@@ -607,7 +607,13 @@ class InoutDBStore:
006 이면 줄에 group_id·color(상품 자기 색상)도 — 그룹 상품의 은 함유량·색상은 그룹 값이 쓰인다."""
self._need_products()
grouped = self.groups_ready() and any("group_id" in r for r in rows)
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
with self._pool.connection() as conn, conn.transaction():
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
for r in rows:
if "body_per_box" in r:
conn.execute("UPDATE inout_products SET body_per_box=%s, lid_per_box=%s WHERE item_code=%s",
(r.get("body_per_box"), r.get("lid_per_box"), r["code"]))
if grouped:
known = {int(g["id"]) for g in conn.execute("SELECT id FROM inout_product_groups").fetchall()}
for r in rows:
@@ -670,7 +676,7 @@ class InoutDBStore:
_PRODUCT_SELECT_006 + " WHERE p.item_code ILIKE %(q)s OR p.item_name ILIKE %(q)s "
"ORDER BY (p.item_code ILIKE %(p)s) DESC, p.item_code LIMIT %(n)s", args).fetchall()
return conn.execute(
"SELECT item_code, item_name, unit_price, weight_g, silver_pct FROM inout_products "
"SELECT * FROM inout_products "
"WHERE item_code ILIKE %(q)s OR item_name ILIKE %(q)s "
"ORDER BY (item_code ILIKE %(p)s) DESC, item_code LIMIT %(n)s", args).fetchall()
@@ -708,6 +714,22 @@ class InoutDBStore:
self._groups_checked = time.monotonic()
return ok
def boxes_ready(self) -> bool:
"""007 이 적용됐나(상품 body_per_box·lid_per_box). groups_ready 와 같이 — 적용됐으면 계속, 아직이면 1분 기억, 연결 열기 전에 부른다."""
if getattr(self, "_boxes_ok", False):
return True
if time.monotonic() - getattr(self, "_boxes_checked", -1e9) < 60:
return False
if not self.products_ready():
return False
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
"AND column_name = 'lid_per_box') AS ok").fetchone()["ok"])
self._boxes_ok = ok
self._boxes_checked = time.monotonic()
return ok
def _need_groups(self) -> None:
if not self.groups_ready():
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
+9 -1
View File
@@ -259,10 +259,13 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
# 단가 — 이미 있던 품목은 발주 당시 값(사본), 새 품목은 지금 상품 정보 값(004). 금액은 화면이 수량 × 단가로 계산.
snap = {x["item_code"]: x.get("unit_price") for x in (order["lines"] if order else [])}
catalog = st.catalog_lookup([ln["code"] for ln in lines if ln["code"] and ln["code"] not in snap])
boxes = st.catalog_lookup([ln["code"] for ln in lines if ln["code"]]) if st.boxes_ready() else {}
for ln in lines:
price = snap[ln["code"]] if ln["code"] in snap else (catalog.get(ln["code"]) or {}).get("unit_price")
ln["price"] = float(price) if price is not None else None
ln["price_label"] = store.fmt_num(price) if price is not None else ""
bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음)
ln["body_per_box"], ln["lid_per_box"] = bx.get("body_per_box"), bx.get("lid_per_box")
reader = _items(request)
catalog_n = st.catalog_count()
return _render(request, "inout/order_form.html", user, {
@@ -270,6 +273,7 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
"factories": [f for f in st.list_factories(include_inactive=True)
if f["is_active"] or (order and f["id"] == order["factory_id"])],
"items_enabled": bool(reader is not None and reader.enabled) or catalog_n > 0, "from_catalog": catalog_n > 0,
"boxes_ready": st.boxes_ready(), "pallet_boxes": store.PALLET_BOXES,
}, status_code=status_code)
@@ -861,6 +865,7 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
"boxes_ready": st.boxes_ready(),
"fmt_num": store.fmt_num,
"factories": st.list_factories(include_inactive=True), "roles": roles, "role_labels": store.ROLE_LABELS,
"settings": st.get_settings(), "settings_ready": st.settings_ready(),
@@ -1016,6 +1021,8 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
code = str((r or {}).get("code") or "").strip().upper()
try:
row = {"code": code, **store.validate_product_values(r)}
if "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
row.update(store.validate_box_values(r))
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
gid = str(r.get("group_id") or "").strip()
if gid and not gid.isdigit():
@@ -1112,7 +1119,8 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
"price": float(r["unit_price"]) if r["unit_price"] is not None else None,
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
"color": r.get("color") or "none"} for r in rows]})
"color": r.get("color") or "none",
"body_per_box": r.get("body_per_box"), "lid_per_box": r.get("lid_per_box")} for r in rows]})
reader = _items(request)
if reader is None or not reader.enabled:
return JSONResponse({"items": [], "enabled": False,
+31 -2
View File
@@ -442,9 +442,38 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
def has_values(p: dict[str, Any]) -> bool:
"""단가·무게·은 함유량(·그룹·색상, 006) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
or (p.get("color") or "none") != "none")
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS))
# ════════════════════════════════════════════════════════════
# 박스 입수(2026-10-21, 마이그레이션 007) — 통·뚜껑이 한 박스에 몇 개. 뚜껑이 없는 상품은 빈칸.
# 새 발주서 화면이 수량 → 통·뚜껑 박스 수(올림)·전체 파렛트(1파렛트 = PALLET_BOXES 박스, 올림)를 계산한다(메일엔 안 넣음).
# ════════════════════════════════════════════════════════════
BOX_FIELDS = {"body_per_box": "통 수량(박스)", "lid_per_box": "뚜껑 수량(박스)"}
MAX_PER_BOX = 1_000_000
PALLET_BOXES = 30
def parse_per_box(raw: Any, *, key: str) -> int | None:
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
label = BOX_FIELDS[key]
s = str(raw if raw is not None else "").replace(",", "").strip()
if not s:
return None
if not s.isdigit():
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
n = int(s)
if n < 1:
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).")
if n > MAX_PER_BOX:
raise ValueError(f"{label}이(가) 너무 큽니다.")
return n
def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
# ════════════════════════════════════════════════════════════
@@ -16,5 +16,17 @@
<div class="io-cal-days" role="grid"></div>
</div>
</div>
{# 화면을 옮겨도 달력이 다시 그려지지 않게 — 마지막 달력(sessionStorage, inout.js 가 저장)을 그리기 전에 바로 붙인다.
inout.js 는 서버 값을 다시 받아 바뀐 게 있을 때만 다시 그린다. #}
<script>(function () {
try {
var c = JSON.parse(sessionStorage.getItem("io_cal_v1") || "null"), cal = document.getElementById("io-cal");
if (!c || !c.html || !c.month || !cal) return;
cal.dataset.month = c.month;
cal.dataset.restored = "1";
cal.querySelector(".io-cal-title").textContent = c.title;
cal.querySelector(".io-cal-days").innerHTML = c.html;
} catch (e) {}
})();</script>
<p class="io-cal-legend"><i class="io-cal-m is-order">n</i>발주 <i class="io-cal-m is-receipt">n</i>입고 <span class="io-sub">· 날짜를 누르면 목록</span></p>
</aside>
@@ -4,6 +4,7 @@
<div class="io-dlg-tabs" role="tablist" aria-label="옵션 분류">
<button type="button" role="tab" class="is-active" aria-selected="true" data-pane="roles">담당자</button>
<button type="button" role="tab" aria-selected="false" data-pane="factories" tabindex="-1">공장 <span class="io-dlg-count">{{ factories|length }}</span></button>
<button type="button" role="tab" aria-selected="false" data-pane="groups" tabindex="-1">상품 그룹 <span class="io-dlg-count">{{ groups|length }}</span></button>
<button type="button" role="tab" aria-selected="false" data-pane="products" tabindex="-1">상품 정보 <span class="io-dlg-count">{{ products|length }}</span></button>
<button type="button" role="tab" aria-selected="false" data-pane="logistics" tabindex="-1">물류센터</button>
</div>
@@ -85,20 +86,16 @@
</table>
</section>
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
{% if not products_ready %}
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
<section class="io-dlg-pane" data-pane="groups" role="tabpanel" hidden>
{% if not groups_ready %}
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
{% else %}
<p class="io-help">
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(그룹에서 한 번만 설정). 색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다.{% endif %}
그룹마다 <b>은(Ag) 함유량</b>·<b>색상</b>을 한 번만 넣습니다 — <b>상품 정보</b> 탭에서 상품마다 그룹을 고르면 그 상품은 그룹 값을 씁니다(그룹 없는 상품은 상품마다).
색상 있는 품목은 발주 메일 표에서 그 줄 배경이 그 색입니다. 그룹을 지우면 그 상품들은 그룹 없음(상품마다 값)으로 바뀝니다.
</p>
{% if groups_ready %}
{% for g in groups %}<form method="post" action="/inout/settings/groups" id="io-g{{ g.id }}" class="io-dlg-form io-group-form"><input type="hidden" name="id" value="{{ g.id }}" /></form>{% endfor %}
<form method="post" action="/inout/settings/groups" id="io-gnew" class="io-dlg-form io-group-form"></form>
<details class="io-groups" open>
<summary>그룹 {{ groups|length }}개 — 은 함유량·색상을 그룹마다 한 번만</summary>
<table class="io-dlg-table io-group-table">
<colgroup><col class="w-gname" /><col class="w-num" /><col class="w-color" /><col class="w-sort" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>그룹 이름</th><th class="io-r">은 함유량(%)</th><th>색상</th><th class="io-c">순서</th><th class="io-c">상품</th><th></th></tr></thead>
@@ -132,10 +129,19 @@
</tr>
</tbody>
</table>
</details>
{% else %}
<p class="io-error">상품 그룹·색상은 DB 마이그레이션 inout_db 006 적용 후 쓸 수 있습니다 — 관리자에게 알려 주세요.</p>
{% endif %}
</section>
<section class="io-dlg-pane" data-pane="products" role="tabpanel" hidden>
{% if not products_ready %}
<p class="io-error">DB 마이그레이션 inout_db 004(상품 정보)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
{% else %}
<p class="io-help">
코드표의 단품을 불러와 <b>단가</b>(원)·<b>무게</b>(개당 g = PP량)·<b>은(Ag) 함유량</b>(%)을 넣습니다 — 은 함량(g)은 무게 × %로 자동 계산.
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
</p>
<div class="io-prod-bar">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
<input type="search" class="io-in io-prod-search" id="io-prod-search" placeholder="코드·제품명 찾기" aria-label="상품 찾기" />
@@ -146,8 +152,8 @@
{% if products %}
<div class="io-prod-scroll">
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
<tbody>
{% for p in products %}
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
@@ -165,6 +171,10 @@
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
{% if boxes_ready %}
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
{% endif %}
{% if groups_ready %}
<td><span class="io-color io-own">{{ swatch(p.own_color, colors) }}<select class="io-in io-color-select" data-key="color" aria-label="{{ p.item_code }} 색상">
{% for key, c in colors.items() %}<option value="{{ key }}" data-hex="{{ c[1] }}" {% if p.own_color == key %}selected{% endif %}>{{ c[0] }}</option>{% endfor %}
+2 -2
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -71,4 +71,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021d" defer></script>{% endblock %}
@@ -20,7 +20,7 @@
</footer>
</dialog>
{%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021d" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
@@ -256,4 +256,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021d" defer></script>{% endblock %}
@@ -1,12 +1,12 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
<section class="io">
{% include "inout/_nav.html" %}
<form class="erp-card-block io-order-form" method="post" id="io-order-form"
<form class="erp-card-block io-order-form" method="post" id="io-order-form"{% if boxes_ready %} data-pallet-boxes="{{ pallet_boxes }}"{% endif %}
action="{% if order %}/inout/orders/{{ order.id }}/edit{% else %}/inout/orders/new{% endif %}">
<div class="erp-card-block-head">
<h2>{% if order %}발주서 고치기 · {{ order.order_no }}{% else %}새 발주서{% endif %}</h2>
@@ -30,11 +30,11 @@
<div class="erp-table-wrap">
<table class="erp-table io-table io-lines" id="io-lines">
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th><th>줄 메모</th><th class="io-col-del"></th></tr></thead>
<thead><tr><th class="io-col-no">#</th><th>제품(코드·이름으로 검색)</th><th class="io-col-qty">발주 수량</th><th class="io-col-money">단가(원)</th><th class="io-col-money">금액(원)</th>{% if boxes_ready %}<th class="io-col-box" title="통·뚜껑 박스 입수(옵션 → 상품 정보)로 계산 — 저장·메일에는 넣지 않습니다">통·뚜껑 박스</th>{% endif %}<th>줄 메모</th><th class="io-col-del"></th></tr></thead>
<tbody>
{% for ln in lines %}
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}">
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}"{% endif %}>
<td class="io-col-no"></td>
<td class="io-item-cell">
<input type="hidden" name="item_code" value="{{ ln.code }}" />
@@ -46,20 +46,29 @@
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="{{ ln.qty }}" placeholder="0" /></td>
<td class="io-col-money io-price">{{ ln.price_label or '-' }}</td>
<td class="io-col-money io-amount">-</td>
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
<td><input class="erp-input" type="text" name="line_memo" value="{{ ln.memo }}" maxlength="500" /></td>
<td class="io-col-del">{% if not received %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
<tfoot><tr><td colspan="7">
<tfoot><tr><td colspan="{{ 8 if boxes_ready else 7 }}">
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-add-line">+ 제품 줄 추가</button>
<span class="erp-muted io-total">합계 <b id="io-total-qty">0</b>개 · <b id="io-total-lines">0</b>종 · 금액 <b id="io-total-amount">0</b>원<span id="io-total-noprice"></span></span>
{% if boxes_ready %}
{# 박스·파렛트(2026-10-21) — 통·뚜껑 박스 수 합계 → 전체 파렛트(1파렛트 = {{ pallet_boxes }}박스, 올림). 화면 계산만(저장·메일 없음) #}
<div class="io-pallet" id="io-pallet" aria-live="polite">
<span>통 <b data-k="body">0</b>박스</span><span>뚜껑 <b data-k="lid">0</b>박스</span><span>전체 <b data-k="boxes">0</b>박스</span>
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
</div>
{% endif %}
</td></tr></tfoot>
</table>
</div>
<template id="io-line-tpl">
<tr class="io-line">
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box=""{% endif %}>
<td class="io-col-no"></td>
<td class="io-item-cell">
<input type="hidden" name="item_code" value="" />
@@ -69,6 +78,7 @@
<td class="io-col-qty"><input class="erp-input io-qty" type="text" inputmode="numeric" name="qty" value="" placeholder="0" /></td>
<td class="io-col-money io-price">-</td>
<td class="io-col-money io-amount">-</td>
{% if boxes_ready %}<td class="io-col-box io-box">-</td>{% endif %}
<td><input class="erp-input" type="text" name="line_memo" value="" maxlength="500" /></td>
<td class="io-col-del"><button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-del" aria-label="이 줄 지우기" title="이 줄 지우기">✕</button></td>
</tr>
@@ -83,4 +93,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021d" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n, ymd %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021d" />{% endblock %}
{% block content %}
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -91,4 +91,4 @@
{% include "inout/_calendar.html" %}
</div>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261021d" defer></script>{% endblock %}
+21 -3
View File
@@ -126,7 +126,7 @@
.io-factory-who { display: block; font-size: 12px; color: var(--color-midtone-gray); margin-top: 2px; }
/* 옵션 팝업 */
.io-dlg { width: min(1180px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
.io-dlg { width: min(1440px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
border-radius: 12px; box-shadow: 0 12px 40px rgba(0, 0, 0, .2); color: var(--color-rich-black); overflow: hidden; }
.io-dlg[open] { display: flex; flex-direction: column; }
.io-dlg:focus { outline: none; }
@@ -411,8 +411,6 @@
.io-swatch.is-none { background: #fff !important; border-style: dashed; border-color: #b9bdc3; }
.io-color { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.io-color .io-color-select { width: auto; min-width: 96px; }
.io-groups { margin: 12px 20px 0; border: 1px solid #e6e8eb; border-radius: 10px; padding: 8px 10px; background: #fbfbfc; }
.io-groups > summary { cursor: pointer; font-weight: 600; font-size: 13px; padding: 2px 0 6px; }
.io-group-table col.w-gname { width: auto; }
.io-group-table col.w-num { width: 120px; }
.io-group-table col.w-color { width: 170px; }
@@ -427,3 +425,23 @@
.io-prod-table tr.is-grouped .io-group-val { display: inline-flex; }
.io-prod-table tr.is-grouped .io-group-val.io-r { display: block; padding-right: 9px; font-variant-numeric: tabular-nums; }
.io-prod-table tr.is-grouped td:has(> .io-group-val) { background: #f6f8fb; }
/* ── 옵션 → 상품 정보: 제목 행 가운데·110%·굵게, 통·뚜껑 박스 입수 열(2026-10-21, 007). 그룹은 따로 "상품 그룹" 탭 ── */
.io-prod-table thead th, .io-prod-table thead th.io-r { text-align: center; font-size: 13.2px; /* 예전 제목 12px × 110% */ font-weight: 700; color: var(--color-rich-black, #1d1d1f); }
.io-prod-table col.w-box { width: 96px; }
.io-prod-table col.w-num { width: 108px; }
.io-prod-table col.w-group { width: 120px; }
.io-prod-table col.w-color { width: 140px; }
.io-dlg-pane[data-pane="groups"] .io-group-table { margin-top: 12px; }
/* ── 새 발주서: 통·뚜껑 박스·파렛트(2026-10-21, 007) — 화면 계산만 ── */
.io-lines .io-col-box { min-width: 190px; white-space: normal !important; font-size: 12.5px; }
.io-box-main b { font-variant-numeric: tabular-nums; }
.io-box-hint { margin-top: 2px; font-size: 11.5px; color: var(--color-midtone-gray, #666); display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
.io-box-ok { color: #1e7a34; font-weight: 600; }
.io-box-pick { border: 1px solid #cfe0fb; background: #f0f6ff; color: #1d4f91; border-radius: 6px; padding: 0 6px; height: 20px; font-size: 11.5px; cursor: pointer; }
.io-box-pick:hover { background: #dce9ff; }
.io-pallet { margin-top: 8px; display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; font-size: 13px; }
.io-pallet b { font-variant-numeric: tabular-nums; }
.io-pallet-main { font-size: 14px; font-weight: 600; }
.io-pallet-main b { font-size: 16px; color: #1d4f91; }
+81 -8
View File
@@ -52,8 +52,41 @@
const totalLines = document.getElementById("io-total-lines");
const totalAmount = document.getElementById("io-total-amount"), noPrice = document.getElementById("io-total-noprice");
// 박스·파렛트(2026-10-21, 007) — 통·뚜껑 박스 입수(상품 정보)로 줄마다 박스 수(올림), 합계 → 파렛트(1파렛트 = data-pallet-boxes, 올림).
// 힌트 = 통·뚜껑 입수의 최소공배수(둘 다 박스가 꽉 차는 수량 단위)와 지금 수량에 가까운 그 배수(누르면 수량 칸에 넣음).
const palletBoxes = parseInt(form.dataset.palletBoxes || "0", 10);
const pallet = document.getElementById("io-pallet");
const gcd = function (a, b) { while (b) { const t = a % b; a = b; b = t; } return a; };
const lcm = function (a, b) { return a / gcd(a, b) * b; };
function boxCell(tr, n, has) {
const cell = tr.querySelector(".io-box");
const body = parseInt(tr.dataset.bodyBox || "0", 10) || 0, lid = parseInt(tr.dataset.lidBox || "0", 10) || 0;
const out = { body: 0, lid: 0, unset: has && !body };
if (!cell) return out;
if (!has) { cell.innerHTML = "-"; return out; }
if (!body) { cell.innerHTML = '<span class="erp-muted" title="옵션 → 상품 정보에서 통 수량(박스)을 넣으면 계산합니다">박스 입수 미설정</span>'; return out; }
out.body = n ? Math.ceil(n / body) : 0;
out.lid = n && lid ? Math.ceil(n / lid) : 0;
const unit = lid ? lcm(body, lid) : body; // 통·뚜껑이 모두 꽉 차는 수량 단위
let html = '<div class="io-box-main">통 <b>' + fmt(out.body) + "</b>박스" +
(lid ? ' · 뚜껑 <b>' + fmt(out.lid) + "</b>박스" : ' · <span class="erp-muted">뚜껑 없음</span>') + "</div>";
const per = "통 " + fmt(body) + "개/박스" + (lid ? " · 뚜껑 " + fmt(lid) + "개/박스" : "");
let hint;
if (n && n % unit === 0) {
hint = '<span class="io-box-ok">✓ ' + (lid ? "통·뚜껑 박스가 모두 꽉 찹니다" : "박스가 꽉 찹니다") + "</span>";
} else {
const lo = Math.floor(n / unit) * unit, hi = (Math.floor(n / unit) + 1) * unit;
const picks = [lo, hi].filter(function (v) { return v > 0; }).map(function (v) {
return '<button type="button" class="io-box-pick" data-qty="' + v + '" title="수량을 ' + fmt(v) + '개로">' + fmt(v) + "</button>";
}).join("");
hint = "<span>" + (lid ? "공배수" : "박스 단위") + " <b>" + fmt(unit) + "</b>개" + (picks ? " ·" : "") + "</span>" + picks;
}
cell.innerHTML = html + '<div class="io-box-hint" title="' + per + '">' + hint + "</div>";
return out;
}
function renumber() {
let q = 0, k = 0, amount = 0, missing = 0;
let bodyBoxes = 0, lidBoxes = 0, unset = 0;
body.querySelectorAll(".io-line").forEach(function (tr, i) {
tr.querySelector(".io-col-no").textContent = String(i + 1);
const n = num(tr.querySelector(".io-qty").value);
@@ -63,7 +96,16 @@
// 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로
if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-";
if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; }
const bx = boxCell(tr, n, has);
bodyBoxes += bx.body; lidBoxes += bx.lid; if (bx.unset) unset++;
});
if (pallet && palletBoxes > 0) {
const all = bodyBoxes + lidBoxes, pallets = Math.ceil(all / palletBoxes), last = all % palletBoxes;
const set = function (key, v) { pallet.querySelector('[data-k="' + key + '"]').textContent = v; };
set("body", fmt(bodyBoxes)); set("lid", fmt(lidBoxes)); set("boxes", fmt(all)); set("pallets", fmt(pallets));
set("note", "1파렛트 = " + palletBoxes + "박스" + (all && last ? " · 마지막 파렛트 " + last + "박스(" + (palletBoxes - last) + "박스 더 실을 수 있음)" : "") +
(unset ? " · 박스 입수 미설정 " + unset + "종 제외" : ""));
}
totalQty.textContent = fmt(q);
totalLines.textContent = fmt(k);
if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR");
@@ -90,6 +132,14 @@
});
body.addEventListener("input", renumber); // 수량을 바꾸거나 제품 글을 고치면(고른 것 풀림) 다시 셈
body.addEventListener("io-chosen", renumber); // 검색 목록에서 제품을 고르면
body.addEventListener("click", function (e) { // 공배수 힌트 숫자 = 그 수량으로
const pick = e.target.closest(".io-box-pick");
if (!pick) return;
const qty = pick.closest(".io-line").querySelector(".io-qty");
qty.value = Number(pick.dataset.qty).toLocaleString("ko-KR");
renumber();
qty.focus();
});
body.querySelectorAll(".io-item-search").forEach(wireSearch);
if (!body.querySelector(".io-line")) { addLine(false); addLine(false); addLine(false); }
renumber();
@@ -174,8 +224,9 @@
if (!it) return;
codeEl.value = it.code;
const row = input.closest("tr");
if (row) { // 단가(상품 정보) — 금액 계산용
if (row) { // 단가(상품 정보) — 금액 계산용, 박스 입수(007) — 박스·파렛트 계산용
row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price);
if ("bodyBox" in row.dataset) { row.dataset.bodyBox = it.body_per_box || ""; row.dataset.lidBox = it.lid_per_box || ""; }
const pc = row.querySelector(".io-price");
if (pc) pc.textContent = it.unit_price || "-";
}
@@ -452,6 +503,7 @@
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
const row = { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
if (tr.querySelector('[data-key="group_id"]')) { row.group_id = v("group_id"); row.color = v("color"); } // 006
if (tr.querySelector('[data-key="body_per_box"]')) { row.body_per_box = v("body_per_box"); row.lid_per_box = v("lid_per_box"); } // 007
return row;
});
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
@@ -745,9 +797,23 @@
const calEl = document.getElementById("io-cal");
if (calEl) initCalendar(calEl);
// 화면을 옮길 때마다 달력이 새로 그려지지 않게(2026-10-21) — 마지막으로 그린 달력(달·API 응답·칸 HTML)을 sessionStorage 에 두고,
// _calendar.html 의 인라인 스크립트가 페이지를 그리기 전에 그대로 붙인다. 여기서는 서버 값을 다시 받아 **바뀐 게 있을 때만** 다시 그린다.
function initCalendar(cal) {
const CAL_KEY = "io_cal_v1"; // 함수 안에 — 위에서 initCalendar 를 먼저 부르므로 바깥 const 는 아직 못 읽는다(TDZ)
const daysEl = cal.querySelector(".io-cal-days"), titleEl = cal.querySelector(".io-cal-title");
let month = cal.dataset.month, data = null, pop = null, seq = 0;
let month = cal.dataset.month, data = null, pop = null, seq = 0, shown = "";
try {
const saved = JSON.parse(sessionStorage.getItem(CAL_KEY) || "null");
if (saved && saved.month && saved.json && cal.dataset.restored === "1") { // 인라인 스크립트가 이미 붙여 놓음
month = saved.month;
data = JSON.parse(saved.json);
shown = saved.json;
}
} catch (_) {}
function remember() {
try { sessionStorage.setItem(CAL_KEY, JSON.stringify({ month: month, json: shown, title: titleEl.textContent, html: daysEl.innerHTML })); } catch (_) {}
}
const pad = function (n) { return String(n).padStart(2, "0"); };
const isoOf = function (d) { return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); };
const escH = function (v) { const d = document.createElement("div"); d.textContent = v == null ? "" : String(v); return d.innerHTML; };
@@ -758,22 +824,29 @@
return d.getFullYear() + "-" + pad(d.getMonth() + 1);
}
function closePop() { if (pop) { pop.remove(); pop = null; } }
async function load() {
closePop();
// quiet = 이미 그려진 달력을 확인만(화면 이동 직후) — 흐리게 하지 않고, 받은 값이 같으면 그대로 둔다
async function load(quiet) {
if (!quiet) closePop();
const p = month.split("-").map(Number);
titleEl.textContent = p[0] + "년 " + p[1] + "월";
const mine = ++seq; // 빠르게 넘기면 늦게 온 앞 달 응답이 덮지 않게
cal.classList.add("is-loading");
if (!quiet) cal.classList.add("is-loading");
try {
const res = await fetch("/inout/api/calendar?month=" + encodeURIComponent(month));
if (!res.ok) throw new Error("HTTP " + res.status);
const got = await res.json();
const text = await res.text();
if (mine !== seq) return;
data = got;
if (text === shown && data) return; // 바뀐 것 없음 — 다시 그리지 않는다
data = JSON.parse(text);
shown = text;
closePop();
render();
remember();
} catch (_) {
if (mine !== seq) return;
if (quiet && data) return; // 확인만 실패 — 붙여 둔 달력 그대로
data = null;
shown = "";
daysEl.innerHTML = '<p class="io-cal-err">달력을 불러오지 못했습니다.</p>';
} finally {
if (mine === seq) cal.classList.remove("is-loading");
@@ -851,6 +924,6 @@
});
document.addEventListener("keydown", function (e) { if (e.key === "Escape") closePop(); });
window.addEventListener("resize", closePop);
load();
load(!!data);
}
})();
+11
View File
@@ -333,6 +333,17 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_031_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_031_owner_as_member.sql && docker compose build web && docker compose up -d web
```
## 입출고 관리 박스 입수 마이그레이션 (inout_db 007)
007은 `inout_products.body_per_box`·`lid_per_box` 열 두 개만 추가한다(통·뚜껑이 한 박스에 몇 개, 뚜껑 없으면 빈칸). 다시 실행 가능, 기존 데이터 변경 없음,
새 환경변수 없음. 004 다음에 적용한다. 미적용이어도 앱은 그대로 — 옵션 → 상품 정보에 두 열이 안 보이고 새 발주서에 박스·파렛트 계산이 없을 뿐.
```bash
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_007_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_007_box_qty.sql && docker compose up --build -d --no-deps web
```
되돌리기(박스 입수만 사라짐): `docker exec postgres-db psql -U postgres -d inout_db -c "ALTER TABLE inout_products DROP COLUMN body_per_box, DROP COLUMN lid_per_box;"`
## 입출고 관리 상품 그룹·색상 마이그레이션 (inout_db 006)
006은 표 1개·열 3개만 추가한다 — `inout_product_groups`(그룹 이름·은 함유량·색상·순서)·`inout_products.group_id`·`inout_products.color`·
+11
View File
@@ -190,6 +190,17 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
- 옵션 화면: 그룹 표(이름·은 함유량·색상[사각형 + 고르기]·순서·상품 수·저장/지우기·추가), 상품 표에 그룹·색상 열. 그룹 상품은 은 함유량·색상 칸 대신 그룹 값(회색 칸),
그룹을 바꾸면 그 자리에서 그룹 값·은 g 다시 계산. 저장 안 한 상품 변경이 있으면 그룹 저장 전에 묻는다.
## 6-3-2. 박스 입수·파렛트(2026-10-21, 마이그레이션 007)
- 사용자 요청: 상품 정보에 **통 수량(박스)**·**뚜껑 수량(박스)** — 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑 없는 상품은 빈칸).
새 발주서에서 상품·수량을 고르면 통·뚜껑 박스 수와 전체 파렛트 수(**1파렛트 = 30박스**)를 계산해 보여 주고, 통·뚜껑 입수가 달라 **공배수**를 힌트로.
**발주 메일은 예전 서식 그대로**(박스·파렛트 안 넣음).
- 계산(화면, `inout.js`): 통 박스 = ⌈수량 ÷ 통 입수⌉, 뚜껑 박스 = ⌈수량 ÷ 뚜껑 입수⌉, 전체 박스 = Σ(통 + 뚜껑), 파렛트 = ⌈전체 ÷ 30⌉, 마지막 파렛트 = 전체 mod 30.
힌트 단위 = lcm(통 입수, 뚜껑 입수)(뚜껑 없으면 통 입수) — 수량이 그 배수면 "✓ 통·뚜껑 박스가 모두 꽉 찹니다", 아니면 아래·위 가까운 배수 버튼(누르면 수량 칸에).
입수가 없는 상품은 "박스 입수 미설정"으로 합계에서 빼고 몇 종 빠졌는지 표시. 예: 통 120·뚜껑 300 → 공배수 600, 1,000개 = 통 9·뚜껑 4박스(600·1,200 힌트).
- 옵션 상품 정보 표 제목 행 = 가운데·굵게·12px × 110%. 그룹 표는 같은 날 **상품 그룹** 탭으로 분리, 옵션 창 폭 1440px 까지.
- **달력 다시 그리기 줄이기**(같은 날): 화면을 옮겨도 마지막 달력을 sessionStorage 에서 바로 붙이고, 서버 값이 바뀐 때만 다시 그린다(보던 달 유지, [오늘]로 돌아옴).
## 6-4. 입고 요청 메일 — 물류센터 전산 등록 부탁(2026-10-19, 마이그레이션 005)
- **왜**(사용자 요청): 물류에 들어온 입고를 물류센터 입고 담당자가 전산에 등록하도록, 입고 담당이 입고를 저장하면 메일로 알린다.
+21
View File
@@ -0,0 +1,21 @@
-- =====================================================================
-- inout_db 마이그레이션 007 — 상품 박스 입수(통·뚜껑 한 박스에 몇 개)(2026-10-21)
-- =====================================================================
-- 멱등(idempotent). 열 두 개만 추가(기존 값 그대로). 004 다음에 적용. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_007_box_qty.sql
--
-- 왜(사용자 요청): 옵션 → 상품 정보에 "통 수량(박스)"·"뚜껑 수량(박스)" = 통·뚜껑이 한 박스에 몇 개씩 들어가는지.
-- 뚜껑이 없는 상품도 있다(NULL). 새 발주서에서 수량을 넣으면 통·뚜껑 박스 수와 전체 파렛트 수(1파렛트 = 30박스)를
-- 화면에서 계산해 보여 준다(통·뚜껑 입수의 공배수 = 박스가 다 차는 수량 힌트). 발주 메일·발주 품목에는 넣지 않는다.
-- 되돌리기: ALTER TABLE inout_products DROP COLUMN body_per_box, DROP COLUMN lid_per_box; (박스 입수만 사라짐 — 실행 전 백업)
-- =====================================================================
\set ON_ERROR_STOP on
BEGIN;
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS body_per_box INT NULL CHECK (body_per_box IS NULL OR body_per_box > 0);
ALTER TABLE inout_products ADD COLUMN IF NOT EXISTS lid_per_box INT NULL CHECK (lid_per_box IS NULL OR lid_per_box > 0);
COMMENT ON COLUMN inout_products.body_per_box IS '통 수량(박스) — 통이 한 박스에 몇 개. NULL = 미입력';
COMMENT ON COLUMN inout_products.lid_per_box IS '뚜껑 수량(박스) — 뚜껑이 한 박스에 몇 개. NULL = 뚜껑 없음·미입력';
COMMIT;
SELECT 'inout_db 007 box qty ready' AS status;
+34
View File
@@ -335,6 +335,40 @@ class InoutDbTests(unittest.TestCase):
pass
self.assertEqual(self.st.catalog_count(), before)
def test_box_quantities(self):
"""007 — 통·뚜껑 박스 입수(뚜껑 없음 = 빈칸), 검사, 목록·검색·조회에 나오고, 넣은 상품은 다시 불러와도 그대로."""
from app.modules.inout import store
if not self.st.boxes_ready():
self.skipTest("inout_db 007 미적용")
T = self.tag.upper()
A, B = f"ZB-{T}-A", f"ZB-{T}-B"
before = self.st.catalog_count()
try:
self.st.import_products([{"code": A, "name": "통"}, {"code": B, "name": "뚜껑없음"}], by="b@x")
self.assertEqual(store.validate_box_values({"body_per_box": "1,200", "lid_per_box": ""}), {"body_per_box": 1200, "lid_per_box": None})
for bad in ("0", "-3", "1.5", "abc"):
with self.assertRaises(ValueError):
store.validate_box_values({"body_per_box": bad})
empty = {"unit_price": None, "weight_g": None, "silver_pct": None}
self.st.save_products([{"code": A, **empty, **store.validate_box_values({"body_per_box": "120", "lid_per_box": "500"})},
{"code": B, **empty, **store.validate_box_values({"body_per_box": "48", "lid_per_box": ""})}], by="b@x")
got = self.st.catalog_lookup([A, B])
self.assertEqual((got[A]["body_per_box"], got[A]["lid_per_box"], got[B]["body_per_box"], got[B]["lid_per_box"]), (120, 500, 48, None))
self.assertEqual({x["item_code"]: x["body_per_box"] for x in self.st.catalog_search(f"ZB-{T}")}, {A: 120, B: 48})
self.assertEqual({x["item_code"]: x["lid_per_box"] for x in self.st.list_products() if x["item_code"] in (A, B)}, {A: 500, B: None})
self.assertEqual(self.st.import_products([{"code": B, "name": "새 이름"}], by="b@x")["kept"], 1) # 박스 입수만 넣어도 값 있는 상품
# 박스 칸을 안 보낸 저장(예전 화면)은 박스 입수를 건드리지 않는다
self.st.save_products([{"code": A, **empty}], by="b@x")
self.assertEqual(self.st.catalog_lookup([A])[A]["body_per_box"], 120)
finally:
for code in (A, B):
try:
self.st.exclude_product(code, by="cleanup@x")
except ValueError:
pass
self.assertEqual(self.st.catalog_count(), before)
def test_product_groups_colors_and_calendar(self):
"""006 — 그룹의 은 함유량·색상이 그룹 상품에 적용(그룹 없는 상품은 자기 값), 같은 이름 거절, 발주 품목 색상 사본,
메일 품목 줄 배경, 그룹 지우면 자기 값으로, 다시 불러와도 그룹·색상만 넣은 상품은 그대로. 달력 = 발주일·입고일(취소 제외)."""