"""입출고 관리 — 실제 앱(메뉴·권한·화면·폼)을 격리된 하위 프로세스에서 확인. 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 ">옵션" 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 "]*?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"] # 돌린 사진이 캐시에 남지 않게 — 매번 확인(no-cache + ETag), 같으면 304 assert "no-cache" in img.headers["cache-control"] and img.headers["etag"] assert c.get("/inout/photos/%d" % pids[0], headers={"If-None-Match": img.headers["etag"]}).status_code == 304 # 내용이 가짜 JPEG 이면 원본 그대로, 안내만(400) r = c.post("/inout/orders/%d/photos/%d/rotate?degrees=90" % (oid3, pids[0])) assert r.status_code == 400 and r.json()["error"] and c.get("/inout/photos/%d" % pids[0]).content == JPEG, r.text 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 assert c.post("/inout/orders/%d/photos/%d/rotate?degrees=90" % (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 # 품목 표(2026-10-21) — PP 사용량·은(Ag) 함유량 = 발주 수량 전체(kg), 아래 작은 글씨 = 개당 값. 합계 = " 원"·정수 " kg" # MT-A 100개 × 24.5g = 2.45kg, 은 0.5% = 0.01225kg, PP 사용량 2.43775kg → 줄 2.438kg, 합계 2 kg(X2 는 은 함유량 없어 PP 사용량 없음) for part in ("단가(원)", "금액(원)", "150,000 원", "단가 미입력 1종 제외", ">PP 사용량<", ">은(Ag) 함유량<", "2.438kg", "24.5g/개", "0.012kg", "0.5% · 0.1225g/개", "2 kg<", "0 kg<", "제품 코드"): assert part in detail, part assert "PP(g/개)" not in detail 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() # 메일 표(2026-10-19) — 전체 무게 = 개당 g × 수량(kg), PP 사용량 = 전체 − 은, 은 괄호 = 전체 무게 × %(kg) for part in ("150,000 원", "전체 무게(kg)", "PP 사용량(kg)", "은(Ag) 함유량", "0.5% (0.0123kg)", ">2 kg<", ">2.438<", "0.0123 kg"): # 합계 2.48 → 2 kg 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 ("제품 코드", "단가(원)", "금액(원)", "150,000", "PP(g/개)", ">미입고", ">상태"): 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 '가 단품 40' 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) @unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set") def test_bag_products_separated(self): """008 — 옵션: 봉투·백 표가 따로(칸 다름), 저장·발주서 제품 검색·발주서 화면에 값이 나온다.""" res = _run(''' import uuid from app.modules.inout.db import InoutDBStore st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) main.app.state.inout_store = st main.app.state.inout_items = Items() tag = uuid.uuid4().hex[:6].upper() admin = U("admin-%s@t.local" % tag.lower(), role="admin") users.append(admin) BAG, BOX = "ZG-%s-A" % tag, "ZG-%s-B" % tag def body(c): who["u"] = admin st.import_products([{"code": BAG, "name": "미라클백 " + tag}, {"code": BOX, "name": "통 " + tag}], by=admin["email"]) try: panel = c.get("/inout/settings?panel=1").text assert panel.count('class="io-prod-part"') == 2 and "1파렛트당 박스 수량" in panel bag_row = panel[panel.index('data-code="%s"' % BAG):] bag_row = bag_row[:bag_row.index("")] box_row = panel[panel.index('data-code="%s"' % BOX):] box_row = box_row[:box_row.index("")] assert 'data-key="boxes_per_pallet"' in bag_row and 'data-key="lid_per_box"' not in bag_row assert 'data-key="boxes_per_pallet"' not in box_row and 'data-key="lid_per_box"' in box_row assert panel.index('data-code="%s"' % BAG) < panel.index("일반 상품") < panel.index('data-code="%s"' % BOX) # 봉투·백 표엔 단가·무게·은 칸이 없다(일반 상품 표에만) — 전에 넣은 값은 숨은 칸으로 남아 저장해도 안 지워짐 assert panel.count("단가(원)") == 1 and panel.count("은(g/개)") == 1 assert 'class="io-ag"' not in bag_row and 'io-ag' not in bag_row and 'io-in-num" data-key="unit_price"' not in bag_row assert 'io-in-num" data-key="unit_price"' in box_row r = c.post("/inout/settings/products/save", headers={"X-Inout-Options": "1"}, json={"rows": [ {"code": BAG, "unit_price": "1500", "weight_g": "", "silver_pct": "", "body_per_box": "1,000", "boxes_per_pallet": "40"}]}) assert r.status_code == 200 and r.json()["ok"], r.text assert 'type="hidden" data-key="unit_price" value="1,500"' in c.get("/inout/settings?panel=1").text item = c.get("/inout/api/items?q=" + BAG).json()["items"][0] assert (item["is_bag"], item["body_per_box"], item["lid_per_box"], item["boxes_per_pallet"]) == (True, 1000, None, 40) r = c.post("/inout/settings/products/save", headers={"X-Inout-Options": "1"}, json={"rows": [ {"code": BAG, "unit_price": "", "weight_g": "", "silver_pct": "", "body_per_box": "1", "boxes_per_pallet": "0"}]}) assert r.json()["ok"] is False and "1파렛트당 박스 수량" in r.json()["message"], r.text form = c.post("/inout/orders/new", data={"factory_id": "", "order_date": "2026-11-04", "item_code": [BAG], "item_name": [""], "qty": ["500"], "line_memo": [""]}).text assert 'data-body-box="1000" data-lid-box="" data-bag="1" data-pallet-box="40"' in form, form[:300] assert 'id="io-pallet-bag"' in form finally: for code in (BAG, BOX): st.exclude_product(code, by=admin["email"]) print("OK") run(body) ''', {"INOUT_TEST_DB_URL": DSN}) 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_simple_factory_mail_shows_boxes(self): """대성화학 메일 미리보기 — 상품 정보의 박스 입수로 박스 칸이 차고 단가는 없음. 다른 공장은 예전 표.""" res = _run(''' import re, uuid from app.modules.inout.db import InoutDBStore st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) main.app.state.inout_store = st main.app.state.inout_items = Items() tag = uuid.uuid4().hex[:6].upper() admin = U("admin-%s@t.local" % tag.lower(), role="admin") users.append(admin) CODE = "ZS-%s-A" % tag def order_for(c, factory): c.post("/inout/settings/factories", data={"name": factory, "is_active": "1"}, headers={"X-Inout-Options": "1"}) fid = next(f["id"] for f in st.list_factories() if f["name"] == factory) r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-11-04", "item_code": [CODE], "item_name": [""], "qty": ["100"], "line_memo": [""]}, follow_redirects=False) return int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1)) def body(c): who["u"] = admin st.import_products([{"code": CODE, "name": "통 " + tag}], by=admin["email"]) try: r = c.post("/inout/settings/products/save", headers={"X-Inout-Options": "1"}, json={"rows": [ {"code": CODE, "unit_price": "7777", "weight_g": "", "silver_pct": "", "body_per_box": "30", "lid_per_box": ""}]}) assert r.json()["ok"], r.text html = c.get("/inout/orders/%d/mail" % order_for(c, "대성화학-" + tag)).json()["html"] assert "박스당 수량" in html and ">30개" in html and ">4박스" in html, html assert "단가" not in html and "7,777" not in html html = c.get("/inout/orders/%d/mail" % order_for(c, "보통공장-" + tag)).json()["html"] assert "박스당 수량" not in html and "7,777" in html finally: st.exclude_product(CODE, by=admin["email"]) print("OK") run(body) ''', {"INOUT_TEST_DB_URL": DSN}) 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_list_status_remembered_per_user(self): """발주 목록 상태 보기 — 사람마다 따로 기억, 처음은 진행 중, 틀린 값은 저장 안 함.""" res = _run(''' import uuid from app.modules.inout.db import InoutDBStore st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) main.app.state.inout_store = st main.app.state.inout_items = Items() tag = uuid.uuid4().hex[:6] a, b = U("a-%s@t.local" % tag), U("b-%s@t.local" % tag) users.extend([a, b]) def shown(c, url="/inout/"): page = c.get(url).text return next(k for k in ("active", "done", "closed", "all") if 'name="status" value="%s"' % k in page) def body(c): who["u"] = a assert shown(c) == "active" # 처음은 진행 중 assert shown(c, "/inout/?status=closed") == "closed" assert shown(c) == "closed" # 다음 접속에도 그대로 who["u"] = b assert shown(c) == "active" # 다른 사람 선택은 영향 없음 assert shown(c, "/inout/?status=all") == "all" who["u"] = a assert shown(c) == "closed" # b 가 바꿔도 a 는 그대로 assert shown(c, "/inout/?status=nope") == "closed" and shown(c) == "closed" assert st.get_settings().keys().isdisjoint({"list_status:" + a["email"]}) # 모듈 설정에 섞이지 않음 print("OK") run(body) ''', {"INOUT_TEST_DB_URL": DSN}) 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_super_admin_deletes_order(self): """발주 목록 🗑 — 수퍼관리자만(ERP 관리자·발주 담당은 403·버튼 없음), 지운 뒤 보던 목록으로.""" res = _run(''' import re, uuid from app.modules.inout.db import InoutDBStore st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"]) main.app.state.inout_store = st main.app.state.inout_items = Items() tag = uuid.uuid4().hex[:6] admin = U("admin-%s@t.local" % tag, role="admin") boss = dict(U("boss-%s@t.local" % tag, role="admin"), is_super_admin=True) users.extend([admin, boss]) def body(c): who["u"] = admin H = {"X-Inout-Options": "1"} c.post("/inout/settings/factories", data={"name": "공장D-" + tag, "is_active": "1"}, headers=H) fid = next(f["id"] for f in st.list_factories() if f["name"] == "공장D-" + tag) r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-10-16", "item_code": ["MT-A"], "item_name": [""], "qty": ["7"], "line_memo": [""]}, follow_redirects=False) oid = int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1)) no = st.get_order(oid)["order_no"] # ERP 관리자(수퍼 아님) — 버튼 없음, 직접 보내도 403 assert 'action="/inout/orders/%d/delete"' % oid not in c.get("/inout/?status=all").text assert c.post("/inout/orders/%d/delete" % oid).status_code == 403 assert st.get_order(oid) is not None # 수퍼관리자 — 목록에 🗑, 지우면 보던 목록(거르기 그대로)으로 who["u"] = boss lst = c.get("/inout/?status=all&q=" + no).text assert 'action="/inout/orders/%d/delete"' % oid in lst and "완전히 삭제할까요?" in lst r = c.post("/inout/orders/%d/delete" % oid, data={"back": "/inout/?status=all&q=" + no}, follow_redirects=False) assert r.status_code == 303 and r.headers["location"].startswith("/inout/?status=all&q=" + no + "&msg="), r.headers["location"] assert st.get_order(oid) is None assert c.post("/inout/orders/%d/delete" % oid, data={"back": "https://evil.example/"}, follow_redirects=False).headers["location"].startswith("/inout/?msg=") 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()