08fe894d1b
- 옵션 → 물류센터 탭: 물류센터 담당자 이메일·입고 요청 메일 참조(기본 king@·bj@dbxcorp.co.kr) - 입고 저장 → 미리보기 팝업 바로 → [메일 발송](입고 담당 본인 Gmail), 입고 기록 줄 보내기/다시 보내기 - 제목 "[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.", 본문 = 전산 등록 부탁 + 상품 이름·코드·입고 수량·비고 표 - 입고증 사진은 첨부가 아니라 본문 안 이미지(CID multipart/related), 가로 최대 600px·비율 유지로 줄임 - Gmail 연결 권한을 발주 담당 → 발주·입고 담당으로 - 마이그레이션 inout_db 005(inout_settings·inout_receipt_mails), 초기화 SQL 에도 반영 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
231 lines
12 KiB
Python
231 lines
12 KiB
Python
"""입출고 005 — 입고 요청 메일(물류센터): 제목·본문 표·본문 안 사진(가로 600px, CID)·옵션 저장·미리보기/발송 API. DB·구글 없이."""
|
|
import email
|
|
import io
|
|
import unittest
|
|
from datetime import date, datetime
|
|
from email import policy
|
|
from unittest.mock import patch
|
|
|
|
from PIL import Image
|
|
|
|
from app.modules.inout import gmail
|
|
from app.modules.inout import store as s
|
|
|
|
|
|
def _jpeg(w, h, color=(200, 30, 30)):
|
|
buf = io.BytesIO()
|
|
Image.new("RGB", (w, h), color).save(buf, "JPEG")
|
|
return buf.getvalue()
|
|
|
|
|
|
def _png_alpha(w, h):
|
|
buf = io.BytesIO()
|
|
Image.new("RGBA", (w, h), (0, 0, 255, 128)).save(buf, "PNG")
|
|
return buf.getvalue()
|
|
|
|
|
|
HEIC = b"\x00\x00\x00\x18ftypheic" + b"0" * 64
|
|
|
|
|
|
def _order():
|
|
return {"id": 7, "order_no": "PO-261019-01", "factory_name": "엘리화학", "cancelled_at": None,
|
|
"lines": [{"id": 11, "item_code": "MW-0320", "item_name": "미라클 통 황토 320ml", "qty": 5000, "memo": "흰 뚜껑"},
|
|
{"id": 12, "item_code": "MW-0950", "item_name": "<b>950ml</b>", "qty": 10000, "memo": ""}]}
|
|
|
|
|
|
def _receipt(**over):
|
|
r = {"id": 3, "receipt_date": date(2026, 10, 19), "memo": "박스 12개<파손 없음>", "mails": [],
|
|
"lines": [{"order_line_id": 11, "item_code": "MW-0320", "item_name": "미라클 통 황토 320ml", "qty": 2000},
|
|
{"order_line_id": 12, "item_code": "MW-0950", "item_name": "<b>950ml</b>", "qty": 500}]}
|
|
r.update(over)
|
|
return r
|
|
|
|
|
|
class ReceiptMailTests(unittest.TestCase):
|
|
def test_subject_format(self):
|
|
self.assertEqual(s.receipt_mail_subject(date(2026, 10, 19)), "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.")
|
|
self.assertEqual(s.receipt_mail_subject(date(2026, 3, 1)), "[입고 요청] 2026년 03월 01일(일) 입고 요청 합니다.")
|
|
|
|
def test_mail_images_resize_to_600_keep_ratio(self):
|
|
photos = [{"id": 1, "data": _jpeg(2000, 1500)}, {"id": 2, "data": _jpeg(400, 900)},
|
|
{"id": 3, "data": _png_alpha(1200, 300)}, {"id": 4, "data": HEIC}]
|
|
imgs, skipped = s.mail_images(photos)
|
|
self.assertEqual(skipped, 1) # HEIC 은 서버가 못 연다 → 뺌
|
|
self.assertEqual([(i["width"], i["height"]) for i in imgs], [(600, 450), (400, 900), (600, 150)])
|
|
self.assertEqual([i["cid"] for i in imgs], ["inout-photo-1@dbx", "inout-photo-2@dbx", "inout-photo-3@dbx"])
|
|
for i in imgs:
|
|
im = Image.open(io.BytesIO(i["data"]))
|
|
self.assertEqual((im.format, im.size), ("JPEG", (i["width"], i["height"])))
|
|
|
|
def test_mail_images_respects_exif_rotation(self):
|
|
im = Image.new("RGB", (1600, 1200), (10, 200, 10))
|
|
exif = im.getexif()
|
|
exif[0x0112] = 6 # 시계 방향 90° — 휴대폰 세로 사진
|
|
buf = io.BytesIO()
|
|
im.save(buf, "JPEG", exif=exif.tobytes())
|
|
imgs, _ = s.mail_images([{"id": 9, "data": buf.getvalue()}])
|
|
self.assertEqual((imgs[0]["width"], imgs[0]["height"]), (600, 800))
|
|
|
|
def test_body_table_photos_and_escaping(self):
|
|
imgs, _ = s.mail_images([{"id": 1, "data": _jpeg(2000, 1500)}])
|
|
m = s.receipt_mail(_order(), _receipt(), images=imgs, skipped=1, sender_name="김물류", sender_email="wh@dbxcorp.co.kr")
|
|
self.assertEqual(m["subject"], "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.")
|
|
h = m["html"]
|
|
self.assertIn("입고된 아래 리스트 상품을 전산 등록 부탁드립니다.", h)
|
|
heads = [x.split("</th>")[0].split(">")[-1] for x in h.split("<thead>")[1].split("</thead>")[0].split("<th")[1:]]
|
|
self.assertEqual(heads, ["상품 이름", "상품 코드", "입고 수량", "비고"])
|
|
self.assertIn(">2,000<", h) and self.assertIn(">500<", h) and self.assertIn(">2,500<", h) # 합계
|
|
self.assertIn("흰 뚜껑", h) # 비고 = 발주 품목 줄 메모
|
|
self.assertIn("<b>950ml</b>", h) and self.assertNotIn("<b>950ml</b>", h)
|
|
self.assertIn("박스 12개<파손 없음>", h)
|
|
self.assertIn('src="cid:inout-photo-1@dbx" width="600" height="450"', h) # 본문 안 이미지(첨부 아님)
|
|
self.assertLess(h.index("<table"), h.index("cid:inout-photo-1")) # 사진은 맨 아래
|
|
self.assertIn("본문에 넣지 못한 사진 1장", h)
|
|
for part in ("입고된 아래 리스트 상품을 전산 등록 부탁드립니다.", "- 미라클 통 황토 320ml · MW-0320 · 2,000개 · 흰 뚜껑",
|
|
"합계 2,500개", "입고 담당: 김물류 (wh@dbxcorp.co.kr)"):
|
|
self.assertIn(part, m["text"])
|
|
prev = s.inline_preview_html(h, imgs)
|
|
self.assertNotIn("cid:", prev) and self.assertIn('src="data:image/jpeg;base64,', prev)
|
|
none = s.receipt_mail(_order(), _receipt(memo=""), images=[], sender_name="", sender_email="wh@x.com")
|
|
self.assertNotIn("입고 인증 사진", none["html"]) and self.assertNotIn("메모:", none["html"])
|
|
|
|
def test_build_message_inline_images_are_related_not_attachments(self):
|
|
imgs, _ = s.mail_images([{"id": 1, "data": _jpeg(800, 600)}, {"id": 2, "data": _jpeg(300, 300)}])
|
|
m = s.receipt_mail(_order(), _receipt(), images=imgs, sender_name="K", sender_email="k@dbxcorp.co.kr")
|
|
raw = gmail.build_message(sender_name="K", sender_email="k@dbxcorp.co.kr", to=["lg@x.com"],
|
|
cc=["king@dbxcorp.co.kr", "bj@dbxcorp.co.kr"], subject=m["subject"], text=m["text"],
|
|
html=m["html"], inline_images=imgs)
|
|
msg = email.message_from_bytes(raw, policy=policy.default)
|
|
self.assertEqual(msg["Cc"], "king@dbxcorp.co.kr, bj@dbxcorp.co.kr")
|
|
self.assertEqual(str(msg["Subject"]), "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.")
|
|
self.assertEqual(msg.get_content_type(), "multipart/alternative")
|
|
related = msg.get_payload()[1]
|
|
self.assertEqual(related.get_content_type(), "multipart/related")
|
|
parts = related.get_payload()
|
|
self.assertEqual(parts[0].get_content_type(), "text/html")
|
|
self.assertEqual([p["Content-ID"] for p in parts[1:]], ["<inout-photo-1@dbx>", "<inout-photo-2@dbx>"])
|
|
self.assertTrue(all(p.get_content_disposition() == "inline" and p.get_filename() is None for p in parts[1:]))
|
|
self.assertEqual(Image.open(io.BytesIO(parts[1].get_content())).size, (600, 450))
|
|
self.assertEqual(list(msg.iter_attachments()), []) # 첨부 파일 없음
|
|
plain = gmail.build_message(sender_name="K", sender_email="k@x.com", to=["a@x.com"], cc=[], subject="x", text="t", html="<p>h</p>")
|
|
self.assertEqual(email.message_from_bytes(plain, policy=policy.default).get_payload()[1].get_content_type(), "text/html")
|
|
|
|
def test_clean_emails(self):
|
|
self.assertEqual(s.clean_emails("a@x.com;b@y.com a@x.com", label="x"), "a@x.com, b@y.com")
|
|
self.assertEqual(s.clean_emails("", label="x"), "")
|
|
with self.assertRaises(ValueError):
|
|
s.clean_emails("nope", label="물류센터")
|
|
|
|
|
|
class _Store:
|
|
"""라우터가 부르는 것만 — 입고 1건(사진 1장)·설정·Gmail 연결."""
|
|
|
|
def __init__(self):
|
|
self.mails, self.saved, self.token = [], None, {"refresh_token_enc": "enc"}
|
|
self.settings = {"logistics_emails": "lg@x.com", "receipt_mail_cc": "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"}
|
|
|
|
def roles_of(self, email):
|
|
return {"receive"}
|
|
|
|
def get_order(self, oid):
|
|
if oid != 7:
|
|
return None
|
|
return {**_order(), "receipts": [_receipt(mails=list(self.mails))]}
|
|
|
|
def get_settings(self):
|
|
return dict(self.settings)
|
|
|
|
def settings_ready(self):
|
|
return True
|
|
|
|
def save_settings(self, values, *, by):
|
|
self.saved = (values, by)
|
|
|
|
def receipt_photo_data(self, rid):
|
|
return [{"id": 5, "filename": "a.jpg", "content_type": "image/jpeg", "data": _jpeg(1000, 500)}]
|
|
|
|
def gmail_token(self, email):
|
|
return self.token
|
|
|
|
def mark_gmail(self, email, error=""):
|
|
pass
|
|
|
|
def delete_gmail_token(self, email):
|
|
self.token = None
|
|
|
|
def add_receipt_mail(self, rid, **kw):
|
|
self.mails.append({"sent_at": datetime(2026, 10, 19, 15, 0), "sent_by": kw["sent_by"], "to_addrs": ", ".join(kw["to"])})
|
|
self.last = (rid, kw)
|
|
|
|
|
|
class ReceiptMailApiTests(unittest.TestCase):
|
|
def setUp(self):
|
|
import importlib
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
self.api = importlib.import_module("app.modules.inout.router")
|
|
self.st = _Store()
|
|
app = FastAPI()
|
|
app.include_router(self.api.router)
|
|
app.state.inout_store = self.st
|
|
self.user = {"email": "wh@dbxcorp.co.kr", "name": "김물류", "role": "user"}
|
|
p1 = patch.object(self.api, "_user", lambda request: self.user)
|
|
p2 = patch.object(self.api, "_is_admin", lambda user: False)
|
|
p3 = patch.object(self.api, "_callback_url", lambda request: "https://erp/inout/gmail/callback")
|
|
for p in (p1, p2, p3):
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
self.c = TestClient(app)
|
|
|
|
def test_preview_defaults_and_photos_inline(self):
|
|
r = self.c.get("/inout/orders/7/receipts/3/mail")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
d = r.json()
|
|
self.assertEqual((d["to"], d["cc"]), ("lg@x.com", "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"))
|
|
self.assertEqual(d["subject"], "[입고 요청] 2026년 10월 19일(월) 입고 요청 합니다.")
|
|
self.assertTrue(d["connected"]) and self.assertEqual(d["photos"], 1)
|
|
self.assertIn('src="data:image/jpeg;base64,', d["html"]) and self.assertNotIn("cid:", d["html"])
|
|
self.assertIn("rmail%3D3", d["connect_url"]) # 연결 뒤 이 입고 메일 창으로 돌아옴
|
|
self.assertEqual(self.c.get("/inout/orders/7/receipts/99/mail").status_code, 404)
|
|
|
|
def test_send_records_and_resend_guard(self):
|
|
sent = []
|
|
|
|
def fake_send(refresh, raw):
|
|
sent.append(email.message_from_bytes(raw, policy=policy.default))
|
|
return "gm-1"
|
|
|
|
with patch.object(gmail, "decrypt_token", lambda e, enc: "refresh"), patch.object(gmail, "send", fake_send):
|
|
r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com", "cc": "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.st.last[0], 3)
|
|
self.assertEqual(self.st.last[1]["cc"], ["king@dbxcorp.co.kr", "bj@dbxcorp.co.kr"])
|
|
msg = sent[0]
|
|
self.assertEqual(msg["To"], "lg@x.com")
|
|
related = msg.get_payload()[1]
|
|
self.assertEqual(related.get_content_type(), "multipart/related")
|
|
self.assertEqual(Image.open(io.BytesIO(related.get_payload()[1].get_content())).size, (600, 300))
|
|
# 이미 보냄 → resend 없이는 409, resend=true 면 보냄
|
|
r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com"})
|
|
self.assertEqual((r.status_code, r.json()["resend_needed"]), (409, True))
|
|
r = self.c.post("/inout/orders/7/receipts/3/mail", json={"to": "lg@x.com", "resend": True})
|
|
self.assertEqual(r.status_code, 200) and self.assertEqual(len(sent), 2)
|
|
self.assertEqual(self.c.post("/inout/orders/7/receipts/3/mail", json={"to": ""}).status_code, 400)
|
|
|
|
def test_order_role_cannot_send_receipt_mail(self):
|
|
self.st.roles_of = lambda email: {"order"}
|
|
self.assertEqual(self.c.get("/inout/orders/7/receipts/3/mail").status_code, 403)
|
|
|
|
def test_receive_role_may_connect_gmail(self):
|
|
p = self.api._perms(self.st, self.user)
|
|
self.assertEqual(self.api._require(self.st, self.user, "mail"), p) # 입고 담당도 Gmail 연결
|
|
self.st.roles_of = lambda email: set()
|
|
with self.assertRaises(Exception):
|
|
self.api._require(self.st, self.user, "mail")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|