feat(inout): 발주 메일(발주 담당 본인 Gmail) · 공장 이메일 · 입고증 사진

- inout_db 003: 공장 이메일, 사람별 Gmail 연결(갱신 토큰 암호문만), 발주 메일 기록, 입고증 사진(bytea). init 에도 같게.
- 발주 메일: 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 HTML + 글 본문) → 사람이 [메일 발송]을
  눌러야 Gmail API(gmail.send)로 본인 Gmail 에서 발송. [Gmail 연결]은 사람마다 1회 — 고른 구글 계정 = ERP 계정 확인,
  APP_ENCRYPTION_KEY(AES-GCM, AAD inout:gmail:{email})로 암호화 저장. 보낸 기록, 재발송은 확인 후(resend),
  연결 끊김(invalid_grant)은 토큰 삭제 후 재연결 안내.
- 입고증 사진: 입고 저장 때 첨부(브라우저가 긴 변 2000px JPEG 로 줄임 — 7.9MB → 0.8MB), 10장·10MB, 파일 머리로 형식 검사,
  입고와 한 트랜잭션. 썸네일·크게 보기(←/→)·나중에 더하기·지우기, 보기는 nosniff·CSP sandbox. 초과 확인은 브라우저가 먼저(사진 유지).
- 테스트: 메일 본문·escape·받는 주소·Gmail 연결 검사·토큰 갱신/발송(가짜 구글)·암호화, 사진 검사, 실제 PostgreSQL 저장,
  실제 앱 흐름(사진 업로드·보기 헤더·권한, 메일 미리보기·연결·발송·재발송·끊김). 실제 브라우저로 팝업·사진·축소 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 16:41:28 +09:00
parent 2ed275cd80
commit 451b37955e
19 changed files with 1520 additions and 50 deletions
+93 -2
View File
@@ -111,7 +111,7 @@ def body(c):
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",
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)
@@ -187,11 +187,102 @@ def body(c):
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["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})
''', {"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)