feat(inout): 물류센터 이메일 옵션 · 입고 저장 뒤 입고 요청 메일(Gmail, 본문 안 사진 600px)

- 옵션 → 물류센터 탭: 물류센터 담당자 이메일·입고 요청 메일 참조(기본 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>
This commit is contained in:
2026-10-19 13:33:46 +09:00
parent b95d3909a4
commit 08fe894d1b
19 changed files with 794 additions and 53 deletions
+7
View File
@@ -29,6 +29,13 @@
- **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인). 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문(`gmail.py`).
- 보낸 기록·재발송 확인.
## 입고 요청 메일 (005, 2026-10-19)
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
- 받는 사람 = 옵션 → **물류센터** 탭 담당자 이메일(`inout_settings` `logistics_emails`), 참조 기본 = `receipt_mail_cc`(005 가 `king@dbxcorp.co.kr, bj@dbxcorp.co.kr` 넣음). 창에서 고칠 수 있음.
- 제목 `[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.`(입고일) · 본문 "입고된 아래 리스트 상품을 전산 등록 부탁드립니다." + 표(상품 이름·상품 코드·입고 수량·비고 = 발주 품목 줄 메모, 합계) + 메모 + **맨 아래 입고증 사진 = 본문 안 이미지**(CID `multipart/related`, 첨부 아님 — `gmail.build_message(inline_images=)`), 서버가 가로 600px 이하·비율 유지 JPEG 로 줄임(`store.mail_images`, EXIF 회전 반영, HEIC 는 빼고 안내). 미리보기는 cid → data: 로 바꿔 보여 줌.
- 보낸 기록 `inout_receipt_mails`(입고 지우면 CASCADE), 이미 보낸 입고는 `resend` 확인.
## 입고증 사진 (003)
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
+59
View File
@@ -257,6 +257,16 @@ class InoutDBStore:
mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall()
except UndefinedTable:
photos, mails = [], []
# 입고 요청 메일 기록(005) — 미적용이면 빈 목록
try:
rmails = conn.execute(
"SELECT m.* FROM inout_receipt_mails m JOIN inout_receipts r ON r.id = m.receipt_id "
"WHERE r.order_id=%s ORDER BY m.sent_at, m.id", (order_id,)).fetchall()
except UndefinedTable:
rmails = []
by_rmail: dict[int, list[dict[str, Any]]] = {}
for m in rmails:
by_rmail.setdefault(int(m["receipt_id"]), []).append(m)
by_photo: dict[int, list[dict[str, Any]]] = {}
for ph in photos:
by_photo.setdefault(int(ph["receipt_id"]), []).append(ph)
@@ -268,6 +278,7 @@ class InoutDBStore:
return {**head, "lines": lines, "summary": store.summarize(lines), "status": status,
"status_label": store.ORDER_LABELS[status],
"receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []),
"mails": by_rmail.get(int(r["id"]), []),
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts],
"mails": mails}
@@ -438,6 +449,54 @@ class InoutDBStore:
"VALUES (%s,%s,%s,%s,%s,%s)",
(order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
# ════════════════════════════════════════════════════════════
# 모듈 설정(물류센터 이메일·입고 요청 메일 참조) · 입고 요청 메일 기록 — 005
# ════════════════════════════════════════════════════════════
def settings_ready(self) -> bool:
with self._pool.connection() as conn:
return bool(conn.execute("SELECT to_regclass('public.inout_settings') IS NOT NULL AND "
"to_regclass('public.inout_receipt_mails') IS NOT NULL AS ok").fetchone()["ok"])
def get_settings(self) -> dict[str, str]:
"""설정 값 — 없는 키는 store.SETTING_DEFAULTS. 005 미적용이어도 기본값으로."""
out = dict(store.SETTING_DEFAULTS)
try:
with self._pool.connection() as conn:
for r in conn.execute("SELECT key, value FROM inout_settings").fetchall():
if r["key"] in out:
out[r["key"]] = r["value"]
except UndefinedTable:
pass
return out
def save_settings(self, values: dict[str, str], *, by: str) -> None:
try:
with self._pool.connection() as conn, conn.transaction():
for k, v in values.items():
conn.execute("INSERT INTO inout_settings (key, value, updated_by, updated_at) VALUES (%s,%s,%s,now()) "
"ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_by=EXCLUDED.updated_by, updated_at=now()",
(k, v, _norm_email(by)))
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
try:
with self._pool.connection() as conn:
return conn.execute("SELECT id, filename, content_type, data FROM inout_receipt_photos WHERE receipt_id=%s ORDER BY id",
(receipt_id,)).fetchall()
except UndefinedTable:
return []
def add_receipt_mail(self, receipt_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_receipt_mails (receipt_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(receipt_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
except UndefinedTable:
pass # 메일은 이미 나갔다 — 기록만 못 남김(005 미적용)
def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None:
"""잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고)."""
with self._pool.connection() as conn, conn.transaction():
+7 -1
View File
@@ -140,7 +140,9 @@ def access_token(refresh_token: str) -> str:
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
text: str, html: str) -> bytes:
text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes:
"""글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어
<img src="cid:…"> 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19)."""
msg = EmailMessage()
msg["From"] = formataddr((sender_name or sender_email, sender_email))
msg["To"] = ", ".join(to)
@@ -149,6 +151,10 @@ def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: lis
msg["Subject"] = subject
msg.set_content(text)
msg.add_alternative(html, subtype="html")
if inline_images:
html_part = msg.get_payload()[1]
for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게
html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline")
return msg.as_bytes()
+112 -3
View File
@@ -13,6 +13,8 @@
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만)
GET /inout/api/items?q= 코드표 단품 검색(JSON)
@@ -95,6 +97,8 @@ def _require(st: Any, user: dict[str, Any], what: str) -> dict[str, bool]:
raise HTTPException(status_code=403, detail="발주 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).")
if what == "receive" and not p["can_receive"]:
raise HTTPException(status_code=403, detail="입고 담당만 할 수 있습니다(입출고 관리 → 옵션에서 지정).")
if what == "mail" and not (p["can_order"] or p["can_receive"]): # Gmail 연결 — 발주 메일·입고 요청 메일 보내는 사람
raise HTTPException(status_code=403, detail="발주 담당·입고 담당만 Gmail 을 연결할 수 있습니다.")
if what == "admin" and not p["admin"]:
raise HTTPException(status_code=403, detail="옵션은 ERP 관리자만 바꿀 수 있습니다.")
if what == "super" and not p["super"]:
@@ -337,6 +341,8 @@ def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, An
return _render(request, "inout/order_detail.html", user, {
"tab": "orders", "order": order, "error": error, "over": over or [], "photos_lost": photos_lost,
"open_mail": request.query_params.get("mail") == "1" and perms["can_order"] and not order["cancelled_at"],
# 입고 저장 뒤 ?rmail={입고 id} — 입고 요청 메일 미리보기를 바로 연다(005)
"open_rmail": _opt_int(request.query_params.get("rmail")) if perms["can_receive"] else None,
# 입고 담당(발주 담당 아님)은 품목을 이름·발주 수량(+ 이번 입고 칸)만 — 2026-10-16 사용자 요청
"items_limited": perms["can_receive"] and not perms["can_order"],
"show_prices": perms["can_order"], "totals": store.order_totals(order["lines"]),
@@ -452,7 +458,8 @@ async def receipt_add(request: Request, order_id: int) -> Any:
photos_lost=had_photos, status_code=400)
note = (f"입고 {res['total']:,}개를 저장했습니다." + (" (초과 입고 포함)" if res["over"] else "")
+ (f" 입고증 사진 {res['photos']}장." if res.get("photos") else ""))
return _redirect(f"/inout/orders/{order_id}", note)
# 바로 입고 요청 메일 미리보기(물류센터) — 보내기는 사람이 [메일 발송]을 눌러야
return _redirect(f"/inout/orders/{order_id}?rmail={res['id']}", note)
@router.post("/orders/{order_id}/receipts/{receipt_id}/delete")
@@ -554,7 +561,7 @@ async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "order")
_require(st, user, "mail")
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
from . import gmail # noqa: WPS433
@@ -576,7 +583,7 @@ async def gmail_callback(request: Request) -> Any:
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "order")
_require(st, user, "mail")
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
from . import gmail # noqa: WPS433
@@ -679,6 +686,88 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
return JSONResponse({"ok": True, "message": f"메일을 보냈습니다 → {', '.join(to)}"})
# ────────────────────────────────────────────────────────────
# 입고 요청 메일 — 입고 담당 본인 Gmail(005). 입고 저장 뒤 미리보기 → [메일 발송], 받는 사람 = 옵션 → 물류센터 이메일.
# 본문 = 입고 상품 표 + 입고증 사진(본문 안 이미지, 가로 600px 이하 — store.mail_images).
# ────────────────────────────────────────────────────────────
def _mail_receipt(request: Request, order_id: int, receipt_id: int) -> tuple[Any, dict[str, Any], dict[str, Any], dict[str, Any]]:
user = _user(request)
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="입출고 관리 모듈이 설정되지 않았습니다.")
_require(st, user, "receive")
order = _order_or_404(st, order_id)
receipt = next((r for r in order["receipts"] if int(r["id"]) == receipt_id), None)
if receipt is None:
raise HTTPException(status_code=404, detail="입고 기록을 찾을 수 없습니다.")
return st, user, order, receipt
def _receipt_mail_parts(st: Any, user: dict[str, Any], order: dict[str, Any],
receipt: dict[str, Any]) -> tuple[dict[str, str], list[dict[str, Any]], int]:
images, skipped = store.mail_images(st.receipt_photo_data(int(receipt["id"])))
mail = store.receipt_mail(order, receipt, images=images, skipped=skipped,
sender_name=str(user.get("name") or ""), sender_email=user.get("email", ""))
return mail, images, skipped
@router.get("/orders/{order_id}/receipts/{receipt_id}/mail")
def receipt_mail_preview(request: Request, order_id: int, receipt_id: int) -> JSONResponse:
"""입고 요청 메일 미리보기 — 받는 사람(물류센터)·참조(기본 king@·bj@)·제목·본문(사진은 미리보기용 data: 로), 보낸 기록."""
st, user, order, receipt = _mail_receipt(request, order_id, receipt_id)
from . import gmail # noqa: WPS433
conf = st.get_settings()
mail, images, skipped = _receipt_mail_parts(st, user, order, receipt)
tok = st.gmail_token(user.get("email", ""))
return JSONResponse({
"kind": "receipt", "connected": tok is not None, "configured": gmail.configured(), "ready": st.settings_ready(),
"connect_url": f"/inout/gmail/connect?{urlencode({'next': f'/inout/orders/{order_id}?rmail={receipt_id}'})}",
"callback_url": _callback_url(request),
"from": user.get("email", ""), "to": conf[store.SETTING_LOGISTICS_EMAILS], "cc": conf[store.SETTING_RECEIPT_MAIL_CC],
"subject": mail["subject"], "html": store.inline_preview_html(mail["html"], images),
"photos": len(images), "photos_skipped": skipped,
"sent": [{"at": store.fmt_datetime(m["sent_at"]), "by": m["sent_by"], "to": m["to_addrs"]} for m in receipt["mails"]],
})
@router.post("/orders/{order_id}/receipts/{receipt_id}/mail")
def receipt_mail_send(request: Request, order_id: int, receipt_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""[메일 발송] — 사람이 누를 때만. 이미 보낸 입고는 resend=true 를 함께(실수로 두 번 보내지 않게)."""
st, user, order, receipt = _mail_receipt(request, order_id, receipt_id)
from . import gmail # noqa: WPS433
email = user.get("email", "")
try:
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
cc = store.parse_emails(payload.get("cc"), label="참조")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
if receipt["mails"] and not payload.get("resend"):
return JSONResponse({"ok": False, "resend_needed": True,
"message": f"이 입고는 이미 {len(receipt['mails'])}번 입고 요청 메일을 보냈습니다. 다시 보낼까요?"},
status_code=409)
row = st.gmail_token(email)
if row is None:
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
status_code=409)
mail, images, _skipped = _receipt_mail_parts(st, user, order, receipt)
try:
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
subject=mail["subject"], text=mail["text"], html=mail["html"], inline_images=images)
gid = gmail.send(refresh, raw)
except gmail.GmailNotConnected as exc:
st.delete_gmail_token(email)
return JSONResponse({"ok": False, "reconnect": True, "message": str(exc)}, status_code=409)
except gmail.GmailError as exc:
st.mark_gmail(email, error=str(exc))
return JSONResponse({"ok": False, "message": str(exc)}, status_code=502)
st.add_receipt_mail(receipt_id, sent_by=email, to=to, cc=cc, subject=mail["subject"], gmail_id=gid)
st.mark_gmail(email)
return JSONResponse({"ok": True, "message": f"입고 요청 메일을 보냈습니다 → {', '.join(to)}"})
# ────────────────────────────────────────────────────────────
# 옵션 — 공장·발주 담당·입고 담당(ERP 관리자)
# ────────────────────────────────────────────────────────────
@@ -710,6 +799,7 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_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(),
"candidates": cands,
"items_status": "연결됨" if reader is not None and reader.enabled else (reader.reason if reader else "없음")}
@@ -759,6 +849,25 @@ async def settings_factory_save(request: Request) -> Any:
return _options_done(request, "공장을 저장했습니다.")
@router.post("/settings/logistics")
async def settings_logistics_save(request: Request) -> Any:
"""옵션 → 물류센터 — 입고 요청 메일 받는 주소(물류센터 입고 담당자)·참조 기본값(005)."""
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "admin")
form = await request.form()
try:
st.save_settings({
store.SETTING_LOGISTICS_EMAILS: store.clean_emails(form.get("logistics_emails"), label="물류센터 담당자 이메일"),
store.SETTING_RECEIPT_MAIL_CC: store.clean_emails(form.get("receipt_mail_cc"), label="참조"),
}, by=user.get("email", ""))
except ValueError as exc:
return _options_done(request, str(exc), ok=False)
return _options_done(request, "물류센터 이메일을 저장했습니다.")
@router.post("/settings/factories/{factory_id}/delete")
def settings_factory_delete(request: Request, factory_id: int) -> Any:
got = _ctx(request)
+115
View File
@@ -473,3 +473,118 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
if existing + len(out) > MAX_PHOTOS:
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
return out
# ════════════════════════════════════════════════════════════
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
# 본문 = 입고 상품 표(상품 이름·상품 코드·입고 수량·비고) + 입고증 사진을 본문 안 이미지(CID, 첨부 아님, 가로 600px 이하).
# ════════════════════════════════════════════════════════════
SETTING_LOGISTICS_EMAILS = "logistics_emails"
SETTING_RECEIPT_MAIL_CC = "receipt_mail_cc"
SETTING_DEFAULTS = {SETTING_LOGISTICS_EMAILS: "", SETTING_RECEIPT_MAIL_CC: "king@dbxcorp.co.kr, bj@dbxcorp.co.kr"}
MAIL_IMAGE_MAX_W = 600
def clean_emails(raw: Any, *, label: str) -> str:
"""옵션 저장용 — 주소 검사 후 'a@x.com, b@y.com' 로 다시 씀(비우면 '')."""
return ", ".join(parse_emails(raw, label=label))
def mail_images(photos: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int]:
"""입고증 사진 → 메일 본문용 JPEG(가로 최대 600px, 세로는 비율대로, 회전 정보 반영).
반환 ([{cid, data, width, height}], 못 넣은 장수) — HEIC 등 서버가 못 여는 사진은 빼고 센다."""
from io import BytesIO # noqa: WPS433
from PIL import Image, ImageOps # noqa: WPS433
out: list[dict[str, Any]] = []
skipped = 0
for ph in photos:
try:
im = Image.open(BytesIO(bytes(ph["data"])))
if im.format == "JPEG":
im.draft("RGB", (MAIL_IMAGE_MAX_W * 2, MAIL_IMAGE_MAX_W * 2)) # 큰 JPEG 는 줄여서 읽기(빠름)
im = ImageOps.exif_transpose(im)
if im.mode not in ("RGB", "L"):
rgba = im.convert("RGBA")
bg = Image.new("RGB", rgba.size, (255, 255, 255))
bg.paste(rgba, mask=rgba.split()[-1])
im = bg
if im.width > MAIL_IMAGE_MAX_W:
im = im.resize((MAIL_IMAGE_MAX_W, max(1, round(im.height * MAIL_IMAGE_MAX_W / im.width))), Image.LANCZOS)
buf = BytesIO()
im.convert("RGB").save(buf, "JPEG", quality=85, optimize=True)
except Exception: # noqa: BLE001 — HEIC·깨진 파일은 본문에서 뺀다(입고 기록의 사진은 그대로)
skipped += 1
continue
out.append({"cid": f"inout-photo-{ph['id']}@dbx", "data": buf.getvalue(), "width": im.width, "height": im.height})
return out, skipped
def receipt_mail_subject(receipt_date: date) -> str:
d = receipt_date
return f"[입고 요청] {d.year}년 {d.month:02d}월 {d.day:02d}일({WEEKDAYS_KO[d.weekday()]}) 입고 요청 합니다."
def receipt_mail(order: dict[str, Any], receipt: dict[str, Any], *, images: list[dict[str, Any]], skipped: int = 0,
sender_name: str, sender_email: str) -> dict[str, str]:
"""입고 1건 → 제목·글 본문·HTML 본문. 이미지는 <img src="cid:…"> (보낼 때 gmail.build_message 가 본문에 붙임).
비고 = 그 발주 품목의 줄 메모. 값은 모두 escape."""
memo_of = {int(ln["id"]): (ln.get("memo") or "") for ln in order["lines"]}
rows = [{"name": x["item_name"], "code": x["item_code"], "qty": int(x["qty"]), "note": memo_of.get(int(x["order_line_id"]), "")}
for x in receipt["lines"]]
total = sum(r["qty"] for r in rows)
who = sender_name or sender_email
when = fmt_date(receipt["receipt_date"])
info = f"입고일 {when} · 발주번호 {order['order_no']} · 공장 {order['factory_name']}"
lead = "입고된 아래 리스트 상품을 전산 등록 부탁드립니다."
# 글 본문(HTML 을 못 보는 메일 프로그램용)
text = ["안녕하세요.", "", lead, "", info, "", "[입고 상품] 상품 이름 · 상품 코드 · 입고 수량 · 비고"]
text += [f"- {r['name']} · {r['code']} · {r['qty']:,}개" + (f" · {r['note']}" if r["note"] else "") for r in rows]
text.append(f"합계 {total:,}개")
if receipt.get("memo"):
text += ["", f"메모: {receipt['memo']}"]
if images or skipped:
text += ["", f"입고 인증 사진 {len(images)}장(본문 이미지)" + (f", 본문에 넣지 못한 사진 {skipped}장(HEIC 등)" if skipped else "")]
text += ["", f"입고 담당: {who} ({sender_email})"]
# HTML 본문
e = _html.escape
td = "padding:6px 10px;border:1px solid #d9dce1;"
r_ = "text-align:right;white-space:nowrap;"
bg = "background:#f6f7f9;"
body_rows = "".join(
f'<tr><td style="{td}">{e(r["name"])}</td><td style="{td}font-family:Consolas,monospace">{e(r["code"])}</td>'
f'<td style="{td}{r_}">{r["qty"]:,}</td><td style="{td}">{e(r["note"])}</td></tr>' for r in rows)
imgs = "".join(
f'<p style="margin:8px 0"><img src="cid:{e(im["cid"])}" width="{im["width"]}" height="{im["height"]}" alt="입고 인증 사진 {i}" '
f'style="display:block;width:{im["width"]}px;max-width:100%;height:auto;border:1px solid #d9dce1"></p>'
for i, im in enumerate(images, start=1))
photo_block = ""
if images or skipped:
photo_block = (f'<p style="margin:18px 0 4px"><b>입고 인증 사진</b> <span style="color:#777">{len(images)}장</span></p>{imgs}'
+ (f'<p style="color:#777">본문에 넣지 못한 사진 {skipped}장(HEIC 등) — ERP 입고 기록에서 볼 수 있습니다.</p>' if skipped else ""))
html = (
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
f"<p>안녕하세요.<br>{e(lead)}</p>"
f'<p style="color:#555;margin:0 0 8px">{e(info)}</p>'
'<table style="border-collapse:collapse;min-width:480px">'
f'<thead><tr style="{bg}"><th style="{td}">상품 이름</th><th style="{td}">상품 코드</th><th style="{td}">입고 수량</th>'
f'<th style="{td}">비고</th></tr></thead><tbody>{body_rows}</tbody>'
f'<tfoot><tr><th colspan="2" style="{td}{bg}text-align:right">합계</th><th style="{td}{bg}{r_}">{total:,}</th>'
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
+ (f'<p style="margin:10px 0 0">메모: {e(str(receipt["memo"]))}</p>' if receipt.get("memo") else "")
+ photo_block
+ f'<p style="color:#555;margin-top:18px">입고 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
)
return {"subject": receipt_mail_subject(receipt["receipt_date"]), "text": "\n".join(text), "html": html}
def inline_preview_html(html: str, images: list[dict[str, Any]]) -> str:
"""미리보기 창용 — cid: 를 data: 로 바꿔 브라우저에서 바로 보이게(보내는 메일은 cid 그대로)."""
import base64 # noqa: WPS433
for im in images:
html = html.replace(f'src="cid:{_html.escape(im["cid"])}"',
f'src="data:image/jpeg;base64,{base64.b64encode(im["data"]).decode("ascii")}"')
return html
@@ -5,6 +5,7 @@
<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="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>
<section class="io-dlg-pane" data-pane="roles" role="tabpanel">
@@ -126,4 +127,23 @@
{% endif %}
</section>
<section class="io-dlg-pane" data-pane="logistics" role="tabpanel" hidden>
{% if not settings_ready %}
<p class="io-error">DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다 — 관리자에게 알려 주세요.</p>
{% endif %}
<p class="io-help">
입고 담당이 <b>입고 저장</b>을 누르면 물류센터 입고 담당자에게 보낼 <b>입고 요청 메일</b>(전산 등록 부탁 · 입고 상품 표 · 입고증 사진)을
미리 보여 주고, [메일 발송]을 눌러 입고 담당 본인 Gmail 로 보냅니다. 아래 주소가 받는 사람·참조 칸에 미리 들어갑니다(보낼 때 고칠 수 있음).
</p>
<form method="post" action="/inout/settings/logistics" class="io-dlg-form io-logi-form">
<label class="io-logi-field"><span>물류센터 담당자 이메일 <small>(받는 사람 — 여러 개는 쉼표)</small></span>
<input class="io-in" type="text" inputmode="email" name="logistics_emails" value="{{ settings.logistics_emails }}" maxlength="1000"
placeholder="logistics@example.com" aria-label="물류센터 담당자 이메일" /></label>
<label class="io-logi-field"><span>입고 요청 메일 참조 <small>(여러 개는 쉼표)</small></span>
<input class="io-in" type="text" inputmode="email" name="receipt_mail_cc" value="{{ settings.receipt_mail_cc }}" maxlength="1000"
aria-label="입고 요청 메일 참조" /></label>
<div class="io-dlg-actions"><button type="submit" class="erp-btn erp-btn-primary"{% if not settings_ready %} disabled{% endif %}>물류센터 저장</button></div>
</form>
</section>
<p class="io-dlg-foot">코드표(단품) 연결: {{ items_status }}</p>
+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=20261017c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019a" />{% endblock %}
{% block content %}
<section class="io">
@@ -68,4 +68,4 @@
</div>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
@@ -1,6 +1,26 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import status_badge, order_badge, progress, due, n, ymd, ymdhm %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017c" />{% endblock %}
{#- 메일 창(발주 메일 · 입고 요청 메일 같은 모양) — 열면 미리보기 GET, [메일 발송]을 눌러야 보낸다(inout.js initMail) -#}
{%- macro mail_dialog(id, title, open_url='', open_title='') -%}
<dialog class="io-dlg io-mail-dlg" id="{{ id }}" aria-labelledby="{{ id }}-title" tabindex="-1"
{%- if open_url %} data-open-url="{{ open_url }}" data-open-title="{{ open_title }}"{% endif %}>
<header class="io-dlg-head">
<h2 id="{{ id }}-title" data-mail-title>{{ title }}</h2>
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
</button>
</header>
<p class="io-dlg-msg" role="status" hidden></p>
<div class="io-dlg-body" data-mail-body><p class="erp-muted">불러오는 중…</p></div>
<footer class="io-dlg-footbar" data-mail-foot hidden>
<button type="button" class="io-link-btn" data-gmail-disconnect>Gmail 연결 끊기</button>
<span class="io-nav-gap"></span>
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
<button type="button" class="erp-btn erp-btn-primary" data-mail-send>메일 발송</button>
</footer>
</dialog>
{%- endmacro -%}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019a" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
@@ -150,7 +170,7 @@
{% if order.receipts %}
<div class="erp-table-wrap">
<table class="erp-table io-table">
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th><th>입고 요청 메일</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
<tbody>
{% for r in order.receipts %}
<tr>
@@ -174,6 +194,14 @@
{% elif not r.photos %}<span class="erp-muted">-</span>{% endif %}
</td>
<td class="erp-muted">{{ r.created_by }}<div class="erp-row-sub">{{ ymdhm(r.created_at) }}</div></td>
<td class="io-rmail-cell">
{% if r.mails %}{% set lm = r.mails[-1] %}<span class="io-mail-sent">보냄 {{ ymdhm(lm.sent_at) }}</span>
<div class="erp-row-sub">{{ lm.sent_by }}{% if r.mails|length > 1 %} · 모두 {{ r.mails|length }}번{% endif %}</div>{% endif %}
{% if perms.can_receive %}<button type="button" class="erp-btn erp-btn-outline erp-btn-sm io-rmail-btn" aria-haspopup="dialog"
data-url="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/mail" data-title="입고 요청 메일 · {{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개">
{% if r.mails %}다시 보내기{% else %}보내기{% endif %}</button>
{% elif not r.mails %}<span class="erp-muted">-</span>{% endif %}
</td>
{% if photo_admin %}
<td><form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/delete"
data-erp-confirm="{{ ymd(r.receipt_date) }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 되고 입고증 사진도 지워집니다.">
@@ -205,23 +233,16 @@
{% if perms.can_order and not order.cancelled_at %}
{# 발주 메일 — 열면 GET /inout/orders/{id}/mail 로 미리보기, [메일 발송]을 눌러야 보낸다(발주 담당 본인 Gmail) #}
<dialog class="io-dlg io-mail-dlg" id="io-mail" aria-labelledby="io-mail-title" tabindex="-1">
<header class="io-dlg-head">
<h2 id="io-mail-title">발주 메일 보내기 · {{ order.order_no }}</h2>
<button type="button" class="io-dlg-x" data-close aria-label="닫기" title="닫기">
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>
</button>
</header>
<p class="io-dlg-msg" role="status" hidden></p>
<div class="io-dlg-body" id="io-mail-body"><p class="erp-muted">불러오는 중…</p></div>
<footer class="io-dlg-footbar" id="io-mail-foot" hidden>
<button type="button" class="io-link-btn" id="io-gmail-disconnect">Gmail 연결 끊기</button>
<span class="io-nav-gap"></span>
<button type="button" class="erp-btn erp-btn-outline" data-close>취소</button>
<button type="button" class="erp-btn erp-btn-primary" id="io-mail-send">메일 발송</button>
</footer>
</dialog>
{{ mail_dialog('io-mail', '발주 메일 보내기 · ' ~ order.order_no) }}
{% endif %}
{% if perms.can_receive and order.receipts %}
{# 입고 요청 메일(005) — 물류센터 입고 담당자에게 전산 등록 부탁(입고 담당 본인 Gmail). 입고 저장 뒤 ?rmail={입고 id} 면 바로 연다 #}
{% set open_r = order.receipts | selectattr('id', 'equalto', open_rmail) | list if open_rmail else [] %}
{% if open_r %}
{{ mail_dialog('io-rmail', '입고 요청 메일', '/inout/orders/' ~ order.id ~ '/receipts/' ~ open_r[0].id ~ '/mail',
'입고 요청 메일 · ' ~ ymd(open_r[0].receipt_date) ~ ' 입고 ' ~ n(open_r[0].total) ~ '개') }}
{% else %}{{ mail_dialog('io-rmail', '입고 요청 메일') }}{% endif %}
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
@@ -1,5 +1,5 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261017c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019a" />{% endblock %}
{% block content %}
<section class="io">
@@ -80,4 +80,4 @@
</form>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" 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=20261017c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261019a" />{% endblock %}
{% block content %}
<section class="io">
@@ -88,4 +88,4 @@
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261017a" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261019a" defer></script>{% endblock %}
+8
View File
@@ -286,3 +286,11 @@
.io-table .io-col-trash form { margin: 0; display: inline-flex; }
.io-del-btn { display: inline-flex; align-items: center; justify-content: center; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
/* 입고 요청 메일(005) — 입고 기록 칸 · 옵션 → 물류센터 */
.io-rmail-cell { white-space: nowrap; }
.io-rmail-cell .io-rmail-btn { margin-top: 4px; }
.io-logi-form { display: grid; gap: 12px; max-width: 640px; }
.io-logi-field { display: grid; gap: 4px; }
.io-logi-field > span { font-weight: 600; }
.io-logi-field small { font-weight: 400; color: var(--color-midtone-gray, #777); }
+48 -20
View File
@@ -4,7 +4,7 @@
· 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계
· 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리
· 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게)
· 발주 메일: 미리보기 팝업 → [메일 발송](발주 담당 본인 Gmail), 처음엔 [Gmail 연결]
· 발주 메일·입고 요청 메일: 미리보기 팝업 → [메일 발송](보내는 사람 본인 Gmail), 처음엔 [Gmail 연결]
· data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */
(function () {
"use strict";
@@ -551,17 +551,34 @@
});
}
// ── 발주 메일(003) — 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ──
// ── 메일 창 — 발주 메일(003)·입고 요청 메일(005) 공용. 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ──
// 발주 메일: 머리 [발주 메일 보내기] → GET|POST /inout/orders/{id}/mail (발주 담당 본인 Gmail, 받는 사람 = 공장 이메일)
// 입고 요청 메일: 입고 저장 뒤 바로(?rmail=입고 id) 또는 입고 기록 줄 [보내기] → GET|POST …/receipts/{rid}/mail
// (입고 담당 본인 Gmail, 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = 옵션 값, 본문에 입고증 사진)
const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail");
if (mailBtn && mailDlg) initMail(mailBtn, mailDlg);
if (mailBtn && mailDlg) {
const om = initMail(mailDlg, { param: "mail", what: "발주 메일" });
const url = "/inout/orders/" + mailBtn.dataset.order + "/mail";
mailBtn.addEventListener("click", function () { om.open(url); });
if (mailBtn.dataset.open === "1") om.open(url);
}
const rmailDlg = document.getElementById("io-rmail");
if (rmailDlg) {
const rm = initMail(rmailDlg, { param: "rmail", what: "입고 요청 메일" });
document.querySelectorAll(".io-rmail-btn").forEach(function (b) {
b.addEventListener("click", function () { rm.open(b.dataset.url, b.dataset.title); });
});
if (rmailDlg.dataset.openUrl) rm.open(rmailDlg.dataset.openUrl, rmailDlg.dataset.openTitle);
}
function initMail(btn, dlg) {
const body = document.getElementById("io-mail-body"), foot = document.getElementById("io-mail-foot");
const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = document.getElementById("io-mail-send");
const base = "/inout/orders/" + btn.dataset.order + "/mail";
let data = null, sent = false;
function initMail(dlg, cfg) {
const body = dlg.querySelector("[data-mail-body]"), foot = dlg.querySelector("[data-mail-foot]");
const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = dlg.querySelector("[data-mail-send]");
const titleEl = dlg.querySelector("[data-mail-title]");
let base = "", data = null, sent = false;
function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); }
function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }
function field(name) { return body.querySelector('[data-mail-field="' + name + '"]'); }
async function load() {
const res = await fetch(base, { headers: { Accept: "application/json" } });
data = await res.json();
@@ -569,7 +586,7 @@
if (!data.connected) {
foot.hidden = true;
body.innerHTML = '<div class="io-mail-connect">' +
"<p><b>발주 메일은 내 Gmail(" + esc(data.from) + ")로 보냅니다.</b> 처음 한 번만 Gmail 연결이 필요합니다.</p>" +
"<p><b>" + esc(cfg.what) + "은 내 Gmail(" + esc(data.from) + ")로 보냅니다.</b> 처음 한 번만 Gmail 연결이 필요합니다.</p>" +
"<p class=\"erp-muted\">구글 화면에서 <b>같은 계정</b>을 고르고 '메일 보내기' 권한을 허락하세요. 보내기 권한만 받으며, 메일함은 읽지 않습니다.</p>" +
(data.configured ? "" : '<p class="io-error">서버 설정(APP_ENCRYPTION_KEY·구글 OAuth)이 없어 연결할 수 없습니다 — 관리자에게 알려 주세요.</p>') +
'<a class="erp-btn erp-btn-primary" href="' + esc(data.connect_url) + '">Gmail 연결</a>' +
@@ -580,29 +597,41 @@
return;
}
foot.hidden = false;
const receipt = data.kind === "receipt";
const sentList = (data.sent || []).map(function (m) { return "<li>" + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "</li>"; }).join("");
let hint = "";
if (!data.to) {
hint = receipt ? "물류센터 담당자 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 물류센터에 넣어 두세요."
: (data.factory || "공장") + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.";
}
if (receipt && data.ready === false) hint += (hint ? " " : "") + "(DB 마이그레이션 005 전이라 보낸 기록이 남지 않습니다.)";
body.innerHTML =
'<div class="io-mail-fields">' +
"<label><span>보내는 사람</span><input class=\"io-in\" value=\"" + esc(data.from) + "\" readonly /></label>" +
"<label><span>받는 사람 *</span><input class=\"io-in\" id=\"io-mail-to\" value=\"" + esc(data.to) + "\" placeholder=\"공장 이메일 — 옵션에서 넣어 두면 자동\" /></label>" +
"<label><span>참조</span><input class=\"io-in\" id=\"io-mail-cc\" placeholder=\"여러 개는 쉼표로\" /></label>" +
"<label><span>받는 사람 *</span><input class=\"io-in\" data-mail-field=\"to\" value=\"" + esc(data.to) + "\" placeholder=\"" +
(receipt ? "물류센터 담당자 이메일 — 옵션에서 넣어 두면 자동" : "공장 이메일 — 옵션에서 넣어 두면 자동") + "\" /></label>" +
"<label><span>참조</span><input class=\"io-in\" data-mail-field=\"cc\" value=\"" + esc(data.cc || "") + "\" placeholder=\"여러 개는 쉼표로\" /></label>" +
"<label><span>제목</span><input class=\"io-in\" value=\"" + esc(data.subject) + "\" readonly /></label></div>" +
(data.to ? "" : '<p class="io-hint">' + esc(data.factory) + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.</p>") +
(hint ? '<p class="io-hint">' + esc(hint) + "</p>" : "") +
(receipt && data.photos_skipped ? '<p class="io-hint">HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).</p>" : "") +
(sentList ? '<div class="io-mail-sentlist"><b>보낸 기록</b><ul>' + sentList + "</ul></div>" : "") +
'<iframe class="io-mail-preview" sandbox title="메일 본문 미리보기"></iframe>';
body.querySelector(".io-mail-preview").srcdoc = data.html;
sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송";
}
async function open() {
async function open(url, title) {
base = url;
if (title && titleEl) titleEl.textContent = title;
say("");
sent = false;
if (!dlg.open) dlg.showModal();
dlg.focus({ preventScroll: true });
body.innerHTML = '<p class="erp-muted">불러오는 중…</p>';
foot.hidden = true;
try { await load(); } catch (err) { body.innerHTML = '<p class="io-error">' + esc(err.message) + "</p>"; foot.hidden = true; }
}
async function send(resend) {
const to = document.getElementById("io-mail-to").value, cc = document.getElementById("io-mail-cc").value;
const to = field("to").value, cc = field("cc").value;
sendBtn.disabled = true;
say("보내는 중…");
try {
@@ -623,9 +652,8 @@
say("보내지 못했습니다(연결 오류). 다시 눌러 주세요.", true);
} finally { sendBtn.disabled = false; }
}
btn.addEventListener("click", open);
sendBtn.addEventListener("click", function () { send(false); });
document.getElementById("io-gmail-disconnect").addEventListener("click", async function () {
dlg.querySelector("[data-gmail-disconnect]").addEventListener("click", async function () {
if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return;
await fetch("/inout/gmail/disconnect", { method: "POST" });
await load();
@@ -634,12 +662,12 @@
dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); });
dlg.addEventListener("close", function () {
const url = new URL(location.href);
const had = url.searchParams.has("mail");
url.searchParams.delete("mail");
const had = url.searchParams.has(cfg.param);
url.searchParams.delete(cfg.param);
url.searchParams.delete("msg");
if (sent) location.href = url.toString(); // 머리의 '발주 메일' 기록이 바뀌었다
if (sent) location.href = url.toString(); // 보낸 기록(머리·입고 기록 칸)이 바뀌었다
else if (had) history.replaceState(null, "", url.toString());
});
if (btn.dataset.open === "1") open();
return { open: open };
}
})();