Files
dbx-main/tests/test_inout_web.py
T
king fde37515c8 feat(inout): 전체 입고 완료 표기 · 날짜 서식 yyyy.mm.dd(요일)
- 모든 품목이 입고완료·초과입고면 목록·발주서 머리에 초록 "✓ 전체 입고 완료"(초과가 있으면 "초과 포함")
- 화면·메일·메일 기록 날짜를 모두 2026.10.17(토) / 2026.10.17(토) 15:14 로(ymd·ymdhm 매크로, store.fmt_date·fmt_datetime)
- 발주서 품목 합계 줄 왼쪽 여백

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 01:37:15 +09:00

405 lines
24 KiB
Python

"""입출고 관리 — 실제 앱(메뉴·권한·화면·폼)을 격리된 하위 프로세스에서 확인.
1) 등록·미설정: 메뉴·관리자 권한 칩·"설정 필요" 화면(DB 없이 늘 실행)
2) 전체 흐름(INOUT_TEST_DB_URL 이 localhost 일 때만): 옵션(공장·담당자) → 발주 담당 발주서 작성(코드표 단품만)
→ 입고 담당 분할 입고 → 초과 입고 확인 → 미입고 현황 → 잔량 종결, 그리고 권한(조회만·담당 아님 403).
코드표(itemcode_db)는 가짜 리더로 바꾼다. 운영 DSN·데이터는 쓰지 않는다.
"""
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
DSN = os.getenv("INOUT_TEST_DB_URL", "")
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
PRELUDE = '''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as main
def U(email, role="user", inout=True):
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False,
"modules": {"inout": inout}}
who = {"u": None}
users = []
class Items:
enabled = True
reason = ""
NAMES = {"MT-A": "가 단품", "MT-B": "나 단품", "MT-C": "다 단품"}
def search(self, q, limit=30):
return [{"code": c, "name": n} for c, n in self.NAMES.items() if q.upper() in c or q in n]
def lookup(self, codes):
return {c: self.NAMES[c] for c in codes if c in self.NAMES}
def list_all(self, limit=20000):
return [{"code": c, "name": n} for c, n in self.NAMES.items()]
def run(body):
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
patch.object(main.user_store, "list_all", side_effect=lambda: users):
client = TestClient(main.app)
body(client)
'''
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
env = dict(os.environ)
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
"ITEMCODE", "EXPENSE", "INOUT"):
env[key + "_DB_URL"] = ""
env.update(SESSION_SECRET_KEY="local-inout-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
env.update(extra_env or {})
with tempfile.TemporaryDirectory(prefix="inout-web-") as directory:
env["DATA_DIR"] = directory
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=90)
class InoutWebTests(unittest.TestCase):
def test_registered_and_unconfigured(self):
res = _run('''
from app.store import MODULE_KEYS
admin = U("admin@test.local", role="admin")
users.append(admin)
who["u"] = admin
def body(c):
assert "inout" in MODULE_KEYS
assert main.MODULE_LABELS["inout"] == "입출고 관리"
assert any(x["key"] == "inout" and x["active"] for x in main.build_erp_nav(admin, active="inout"))
assert "입출고 관리" in c.get("/admin").text # 관리자 화면 권한 칩
r = c.get("/inout/")
assert r.status_code == 503 and "INOUT_DB_URL" in r.text, r.status_code # DB 미설정 = 설정 필요 안내
assert c.get("/inout/health").json() == {"status": "not_configured"}
who["u"] = U("nobody@test.local", inout=False)
assert c.get("/inout/").status_code == 403 # 모듈 권한 없음
print("OK")
run(body)
''')
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
def test_full_flow(self):
res = _run('''
import re, uuid
from app.modules.inout.db import InoutDBStore
main.app.state.inout_store = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
main.app.state.inout_items = Items()
tag = uuid.uuid4().hex[:6]
admin, buyer, wh, viewer = (U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag),
U("wh-%s@t.local" % tag), U("viewer-%s@t.local" % tag))
users.extend([admin, buyer, wh, viewer])
def body(c):
# ── 옵션(톱니 팝업): 공장·담당자(관리자만) ──
who["u"] = buyer
assert c.get("/inout/settings?panel=1").status_code == 403
assert 'id="io-options-btn"' not in c.get("/inout/").text # 관리자 아니면 톱니 없음
who["u"] = admin
lst = c.get("/inout/").text
assert 'id="io-options-btn"' in lst and 'id="io-options"' in lst and ">옵션</a>" not in lst # 탭 대신 톱니 + 팝업
r = c.get("/inout/settings", follow_redirects=False) # 예전 주소 = 목록으로 가서 팝업 열기
assert r.status_code == 303 and r.headers["location"] == "/inout/?options=1"
assert 'data-open="1"' in c.get("/inout/?options=1").text
panel = c.get("/inout/settings?panel=1").text
assert buyer["email"] in panel and "발주 담당" in panel and "<html" not in panel.lower() # 팝업 안 내용만
assert 'name="manager"' in panel and 'name="contact"' in panel # 담당자·연락처 따로
H = {"X-Inout-Options": "1"}
r = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "manager": "김공장", "contact": "010-1", "email": "factory-%s@x.com" % tag,
"is_active": "1"}, headers=H)
assert r.status_code == 200 and r.json() == {"ok": True, "message": "공장을 저장했습니다."}
dup = c.post("/inout/settings/factories", data={"name": "공장-" + tag, "is_active": "1"}, headers=H)
assert dup.status_code == 400 and dup.json()["ok"] is False and "같은 이름" in dup.json()["message"]
r = c.post("/inout/settings/factories", data={"name": "폼-" + tag, "is_active": "1"}, follow_redirects=False)
assert r.status_code == 303 and r.headers["location"].startswith("/inout/?options=1&msg=") # 팝업이 아닌 제출 = 이동
fid = next(f["id"] for f in main.app.state.inout_store.list_factories() if f["name"] == "공장-" + tag)
f = next(x for x in main.app.state.inout_store.list_factories() if x["id"] == fid)
assert (f["manager"], f["contact"]) == ("김공장", "010-1")
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]},
headers=H).json()["ok"]
st = main.app.state.inout_store
assert st.roles_of(buyer["email"]) == {"order"} and st.roles_of(wh["email"]) == {"receive"}
# ── 조회만 하는 사람 ──
who["u"] = viewer
assert c.get("/inout/").status_code == 200
assert c.get("/inout/orders/new").status_code == 403
assert "조회만 가능" in c.get("/inout/").text
# ── 발주 담당: 발주서(코드표 단품만) ──
who["u"] = buyer
form = c.get("/inout/orders/new").text
assert "공장-" + tag in form and "새 발주서" in form
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
"item_code": ["MT-A", "ZZ-9"], "item_name": ["", ""], "qty": ["100", "5"], "line_memo": ["", ""]})
assert bad.status_code == 400 and 'value="ZZ-9"' in bad.text
assert "코드표 단품에 없는 제품입니다: ZZ-9" in bad.text or "상품 정보에 없는 단품입니다(옵션 → 상품 정보에서 불러오거나 되살리세요): ZZ-9" in bad.text
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "due_date": "2026-10-20",
"memo": "1차", "item_code": ["mt-a", "MT-B", ""], "item_name": ["", "", ""], "qty": ["1,00", "50", ""],
"line_memo": ["", "포장 주의", ""]}, follow_redirects=False)
assert r.status_code == 303, r.text[:300]
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
detail = c.get(r.headers["location"]).text
assert "김공장 · 010-1" in detail # 공장 담당자·연락처
assert "가 단품" in detail and "포장 주의" in detail and "PO-261016-" in detail and "발주서 PO-261016-" in detail
assert "이번 입고" not in detail # 발주 담당은 입고 칸이 없다
assert c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17"}).status_code == 403
# ── 입고 담당: 분할 입고 → 초과 확인 ──
who["u"] = wh
detail = c.get("/inout/orders/%d" % oid).text
ids = {code: lid for lid, code in re.findall(r'name="qty_(\\d+)"[^>]*?data-code="(MT-[AB])"', detail, re.S)}
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-17", "memo": "1차 트럭",
"qty_" + ids["MT-A"]: "60"}, follow_redirects=False)
assert r.status_code == 303
page = c.get("/inout/orders/%d" % oid).text
assert "부분입고" in page and "1차 트럭" in page
over = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
"qty_" + ids["MT-B"]: "50"})
assert over.status_code == 409 and "초과 입고로 저장" in over.text and "+5" in over.text
assert 'value="45"' in over.text # 넣은 숫자는 그대로
assert st.get_order(oid)["summary"]["received"] == 60 # 확인 전엔 저장 안 됨
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-18", "qty_" + ids["MT-A"]: "45",
"qty_" + ids["MT-B"]: "50", "confirm_over": "1"}, follow_redirects=False)
assert r.status_code == 303 and "%EC%B4%88%EA%B3%BC" in r.headers["location"] # "초과 입고 포함" 안내
got = st.get_order(oid)
assert (got["status"], got["summary"]["over"]) == ("over", 5)
page = c.get("/inout/orders/%d" % oid).text
assert "✓ 전체 입고 완료" in page and "초과 포함" in page # 모든 품목 입고완료·초과입고
assert "2026.10.18(일)" in page and "2026.10.16(금)" in page # 날짜 서식(입고일·발주일)
lst = c.get("/inout/?status=done").text
assert got["order_no"] in lst and "✓ 전체 입고 완료" in lst and "2026.10.16(금)" in lst
pend = c.get("/inout/pending").text
assert "초과 입고" in pend and got["order_no"] in pend
# ── 두 번째 발주: 미입고 현황 → 잔량 종결 ──
who["u"] = buyer
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-C"],
"item_name": [""], "qty": ["30"], "line_memo": [""]}, follow_redirects=False)
oid2 = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
pend = c.get("/inout/pending?q=MT-C").text
assert "다 단품" in pend and "30" in pend
assert "제품별 미입고 합계" in pend
lst = c.get("/inout/?status=active&q=MT-C").text
assert st.get_order(oid2)["order_no"] in lst
c.post("/inout/orders/%d/close" % oid2, data={"reason": "단종"})
assert st.get_order(oid2)["status"] == "closed"
assert st.get_order(oid2)["order_no"] not in c.get("/inout/pending?q=MT-C").text
assert st.get_order(oid2)["order_no"] in c.get("/inout/?status=closed&q=MT-C").text
# ── 003: 입고증 사진(입고와 함께 · 나중에 더하기 · 보기) ──
JPEG = b"\\xff\\xd8\\xff\\xe0" + b"7" * 300
who["u"] = wh
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
assert o3.status_code == 403 # 입고 담당은 발주 못 함
who["u"] = buyer
o3 = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"],
"item_name": [""], "qty": ["10"], "line_memo": [""]}, follow_redirects=False)
assert "mail=1" in o3.headers["location"] # 새 발주서 → 메일 미리보기 바로
oid3 = int(re.search(r"/inout/orders/(\\d+)", o3.headers["location"]).group(1))
assert 'data-open="1"' in c.get(o3.headers["location"]).text
who["u"] = wh
page = c.get("/inout/orders/%d" % oid3).text
assert 'enctype="multipart/form-data"' in page and 'name="photos"' in page and 'id="io-mail-btn"' not in page
lid = re.search(r'name="qty_(\\d+)"', page).group(1)
bad = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
files=[("photos", ("doc.pdf", b"%PDF-1.4 x", "application/pdf"))])
assert bad.status_code == 400 and "사진 파일" in bad.text and "다시 첨부" in bad.text
assert st.get_order(oid3)["summary"]["received"] == 0 # 사진이 틀리면 입고도 저장 안 함
r = c.post("/inout/orders/%d/receipts" % oid3, data={"receipt_date": "2026-10-20", "qty_" + lid: "3"},
files=[("photos", ("입고증1.jpg", JPEG, "image/jpeg")), ("photos", ("입고증2.jpg", JPEG, "image/jpeg"))],
follow_redirects=False)
assert r.status_code == 303, r.text[:300]
got = st.get_order(oid3)
pids = [p["id"] for p in got["receipts"][0]["photos"]]
assert len(pids) == 2 and got["summary"]["received"] == 3
img = c.get("/inout/photos/%d" % pids[0])
assert img.status_code == 200 and img.content == JPEG and img.headers["content-type"] == "image/jpeg"
assert img.headers["x-content-type-options"] == "nosniff" and "sandbox" in img.headers["content-security-policy"]
page = c.get("/inout/orders/%d" % oid3).text
assert 'data-photo="%d"' % pids[0] in page and 'src="/inout/photos/%d"' % pids[0] in page
rid3 = got["receipts"][0]["id"]
r = c.post("/inout/orders/%d/receipts/%d/photos" % (oid3, rid3), files=[("photos", ("추가.png", b"\\x89PNG\\r\\n\\x1a\\n" + b"1" * 50, "image/png"))],
follow_redirects=False)
assert r.status_code == 303 and len(st.get_order(oid3)["receipts"][0]["photos"]) == 3
who["u"] = viewer
assert c.get("/inout/photos/%d" % pids[0]).status_code == 200 # 모듈 권한이면 보기는 됨
assert c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0])).status_code == 403
who["u"] = U("nobody-%s@t.local" % tag, inout=False)
assert c.get("/inout/photos/%d" % pids[0]).status_code == 403
who["u"] = wh
c.post("/inout/orders/%d/photos/%d/delete" % (oid3, pids[0]))
assert len(st.get_order(oid3)["receipts"][0]["photos"]) == 2
# ── 003: 발주 메일(발주 담당 본인 Gmail) ──
import app.modules.inout.gmail as g
sent = []
g.send = lambda refresh, raw: (sent.append((refresh, raw)) or "gid-%d" % len(sent))
who["u"] = viewer
assert c.get("/inout/orders/%d/mail" % oid3).status_code == 403 # 발주 담당만
who["u"] = buyer
pv = c.get("/inout/orders/%d/mail" % oid3).json()
assert pv["connected"] is False and pv["connect_url"].startswith("/inout/gmail/connect?next=")
assert pv["callback_url"].endswith("/inout/gmail/callback") # 구글에 등록할 주소 안내
assert pv["to"] == "factory-%s@x.com" % tag and pv["subject"].startswith("[발주] ") and "가 단품" in pv["html"]
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
assert r.status_code == 409 and r.json()["reconnect"] is True # 연결 전엔 못 보냄
# 연결 — 구글 콜백(가짜): 다른 계정이면 거절, 같은 계정이면 저장(암호문)
class FakeClient:
token = None
async def authorize_access_token(self, request):
return self.token
fake = FakeClient()
g.oauth_client = lambda: fake
fake.token = {"userinfo": {"email": "someone@gmail.com"}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//x"}
r = c.get("/inout/gmail/callback", follow_redirects=False)
assert r.status_code == 303 and "%EB%8B%A4%EB%A5%B8" in r.headers["location"] # "다른 구글 계정"
assert st.gmail_token(buyer["email"]) is None
fake.token = {"userinfo": {"email": buyer["email"]}, "scope": "openid email " + g.GMAIL_SCOPE, "refresh_token": "1//buyer-refresh"}
c.get("/inout/gmail/callback", follow_redirects=False)
tok = st.gmail_token(buyer["email"])
assert tok is not None and "1//buyer-refresh" not in tok["refresh_token_enc"] # 원문은 DB 에 없음
assert c.get("/inout/orders/%d/mail" % oid3).json()["connected"] is True
bad_to = c.post("/inout/orders/%d/mail" % oid3, json={"to": "nope"})
assert bad_to.status_code == 400 and "받는 사람 형식" in bad_to.json()["detail"]
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "cc": "boss@x.com"})
assert r.status_code == 200 and r.json()["ok"], r.text
refresh, raw = sent[-1]
assert refresh == "1//buyer-refresh" and b"factory-" in raw and b"boss@x.com" in raw
again = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"]})
assert again.status_code == 409 and again.json()["resend_needed"] is True and len(sent) == 1 # 실수로 두 번 안 감
assert c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True}).json()["ok"] and len(sent) == 2
detail = c.get("/inout/orders/%d" % oid3).text
assert "모두 2번" in detail and "발주 메일 다시 보내기" in detail
# 구글이 연결을 끊었으면(invalid_grant) 토큰을 지우고 다시 연결 안내
def gone(refresh, raw):
raise g.GmailNotConnected("Gmail 연결이 끊겼습니다 — 다시 연결하세요.")
g.send = gone
r = c.post("/inout/orders/%d/mail" % oid3, json={"to": pv["to"], "resend": True})
assert r.status_code == 409 and r.json()["reconnect"] and st.gmail_token(buyer["email"]) is None
# ── 단품 검색 API ──
assert c.get("/inout/api/items?q=MT-").json()["items"][0]["code"] == "MT-A"
print("OK")
run(body)
''', {"INOUT_TEST_DB_URL": DSN, "APP_ENCRYPTION_KEY": "22" * 32, "GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"})
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
def test_products_prices_and_receiver_view(self):
"""004 — 옵션 → 상품 정보(관리자), 발주서 단가·금액, 메일 본문 금액·PP·은, 입고 담당은 이름·발주 수량만."""
res = _run('''
import re, uuid
from app.modules.inout.db import InoutDBStore
st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
assert st.products_ready(), "inout_db 004 미적용"
main.app.state.inout_store = st
items = Items()
main.app.state.inout_items = items
tag = uuid.uuid4().hex[:6]
T = tag.upper()
X1, X2 = "ZT-%s-1" % T, "ZT-%s-2" % T
items.NAMES = dict(Items.NAMES, **{X1: "지울 단품 " + T, X2: "둘째 단품 " + T})
admin, buyer, wh = U("admin-%s@t.local" % tag, role="admin"), U("buyer-%s@t.local" % tag), U("wh-%s@t.local" % tag)
users.extend([admin, buyer, wh])
H = {"X-Inout-Options": "1"}
def body(c):
who["u"] = admin
assert c.post("/inout/settings/factories", data={"name": "공장P-" + tag, "email": "fp-%s@x.com" % tag, "is_active": "1"},
headers=H).json()["ok"]
fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장P-" + tag)
assert c.post("/inout/settings/roles", data={"order_email": [buyer["email"]], "receive_email": [wh["email"]]}, headers=H).json()["ok"]
# ── 옵션 → 상품 정보: 관리자만 ──
for u in (buyer, wh):
who["u"] = u
assert c.post("/inout/settings/products/import", headers=H).status_code == 403
assert c.get("/inout/settings?panel=1").status_code == 403 # 입고 담당은 옵션을 못 봄
who["u"] = admin
r = c.post("/inout/settings/products/import", headers=H).json()
assert r["ok"] and "단품을 불러왔습니다" in r["message"], r
assert {"MT-A", X1, X2} <= {p["item_code"] for p in st.list_products()}
panel = c.get("/inout/settings?panel=1").text
assert 'data-pane="products"' in panel and 'data-code="%s"' % X1 in panel and "단품 불러오기" in panel
bad = c.post("/inout/settings/products/save", json={"rows": [{"code": X2, "unit_price": "abc"}]}, headers=H)
assert bad.status_code == 400 and bad.json()["ok"] is False and X2 in bad.json()["message"]
r = c.post("/inout/settings/products/save", headers=H, json={"rows": [
{"code": "MT-A", "unit_price": "1,500", "weight_g": "24.5", "silver_pct": "0.5"},
{"code": X2, "unit_price": "", "weight_g": "10", "silver_pct": ""}]}).json()
assert r["ok"] and "2개" in r["message"], r
panel = c.get("/inout/settings?panel=1").text
assert 'value="1,500"' in panel and ">0.1225<" in panel # 은 g = 무게 × % (자동)
# 다시 불러와도 값은 그대로
c.post("/inout/settings/products/import", headers=H)
a = st.catalog_lookup(["MT-A"])["MT-A"]
assert (str(a["unit_price"]), str(a["weight_g"]), str(a["silver_pct"])) == ("1500.00", "24.50", "0.5000")
# 지우기 → 다음 불러오기에서도 빠짐 → 제외 목록에 보임
assert c.post("/inout/settings/products/%s/exclude" % X1, headers=H).json()["ok"]
c.post("/inout/settings/products/import", headers=H)
assert X1 not in st.catalog_lookup([X1])
panel = c.get("/inout/settings?panel=1").text
assert 'data-restore="%s"' % X1 in panel and 'data-code="%s"' % X1 not in panel
# ── 발주 담당: 제품 고르기 = 상품 정보(지운 단품 빼고), 단가 함께 ──
who["u"] = buyer
found = c.get("/inout/api/items?q=" + T).json()
assert found["source"] == "products" and [x["code"] for x in found["items"]] == [X2]
mta = c.get("/inout/api/items?q=MT-A").json()["items"][0]
assert (mta["code"], mta["unit_price"], mta["price"]) == ("MT-A", "1,500", 1500.0)
bad = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": [X1],
"item_name": [""], "qty": ["5"], "line_memo": [""]})
assert bad.status_code == 400 and "상품 정보에 없는 단품입니다" in bad.text
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A", X2],
"item_name": ["", ""], "qty": ["100", "3"], "line_memo": ["", ""]}, follow_redirects=False)
assert r.status_code == 303, r.text[:300]
oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
# 그 뒤 단가가 바뀌어도 이 발주서는 발주할 때 값
who["u"] = admin
c.post("/inout/settings/products/save", headers=H, json={"rows": [{"code": "MT-A", "unit_price": "2000", "weight_g": "24.5", "silver_pct": "0.5"}]})
who["u"] = buyer
detail = c.get("/inout/orders/%d" % oid).text
for part in ("단가(원)", "금액(원)", "150,000", "단가 미입력 1종 제외", "2.48kg", "12.25g", "0.5%", "<th>제품 코드</th>"):
assert part in detail, part
assert "200,000" not in detail
assert 'data-price="1500"' in c.get("/inout/orders/%d/edit" % oid).text or "1,500" in c.get("/inout/orders/%d/edit" % oid).text
pv = c.get("/inout/orders/%d/mail" % oid).json()
for part in ("150,000", "PP(g/개)", "은(Ag) 함유량", "0.5% (0.1225g)", "2.48 kg", "12.25 g"):
assert part in pv["html"], part
# ── 입고 담당: 품목은 제품 이름·발주 수량(+ 이번 입고)만 ──
who["u"] = wh
page = c.get("/inout/orders/%d" % oid).text
assert "가 단품" in page and "이번 입고" in page
for hidden in ("<th>제품 코드</th>", "단가(원)", "금액(원)", "150,000", "PP(g/개)", ">미입고</th>", ">상태</th>"):
assert hidden not in page, hidden
lid = re.search(r'name="qty_(\\d+)"[^>]*data-code="MT-A"', page, re.S).group(1)
r = c.post("/inout/orders/%d/receipts" % oid, data={"receipt_date": "2026-10-20", "qty_" + lid: "40"}, follow_redirects=False)
assert r.status_code == 303
page = c.get("/inout/orders/%d" % oid).text
assert '<span class="io-chip">가 단품 40</span>' in page # 입고 기록도 코드 없이 이름
# 정리 — 테스트 단품은 지운다(MT-A~C 는 남아도 다른 테스트에 영향 없음)
who["u"] = admin
c.post("/inout/settings/products/%s/exclude" % X2, headers=H)
print("OK")
run(body)
''', {"INOUT_TEST_DB_URL": DSN})
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
self.assertIn("OK", res.stdout)
if __name__ == "__main__":
unittest.main()