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
+1 -1
View File
@@ -42,7 +42,7 @@ Claude Code는 이 저장소에서 작업을 시작하기 전에 **반드시 아
- 긴급 공지 (`app/modules/notice/`, `project_db` 마이그레이션 024 `urgent_notice*`) — 수퍼관리자만 작성(`/notice/`, ERP 왼쪽 아래·Project ⚙ 옵션). 제목·내용(이미지 bytea)·띄울 시각·전체/고른 사람 → ERP 모든 화면(`erp_base.html`·`main.html`·`admin.html` 의 `static/erp-notice.js`) 가로·세로 정가운데에 [확인] 누를 때까지(Esc·바깥 클릭 무시), 확인 기록. 연결 풀은 `ProjectStore.pool` 공유, 새 환경변수 없음. PC 알림 프로그램은 아직 미지원. 상세는 `docs/NOTICE_MODULE.md`
- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md`
- 입출고 관리 (`app/modules/inout/`, `inout_db`, 2026-10-16) — 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`, 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인), 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고, 미입고 현황(제품별 합계·발주별·지연), 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`), 잔량 종결·취소(입고 없을 때만). 상태는 저장하지 않고 누적 입고로 계산(`store.order_status`). 권한키 `inout`(조회), **발주 담당·입고 담당·공장(담당자·연락처 따로, 002)은 모듈 옵션 — 상단 톱니 → 팝업**(`/inout/settings?panel=1`, ERP 관리자, `inout_roles`·`inout_factories`, 공용 `.erp-input`·`.erp-table-wrap` 겹침은 `.io` 안에서만 바로잡음), 관리자는 둘 다. **발주 메일**(003): 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 본문) → 사람이 [메일 발송]을 눌러야 **발주 담당 본인 Gmail**(Gmail API `gmail.send`, 사람마다 [Gmail 연결] 1회 — 고른 구글 계정 = ERP 계정 확인, 갱신 토큰은 `APP_ENCRYPTION_KEY` AES-GCM 암호문, `app/modules/inout/gmail.py`)로 보냄, 보낸 기록·재발송 확인. **입고증 사진**(003): 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea), 썸네일·크게 보기·나중에 더하기, 초과 확인은 브라우저가 먼저(사진 유지). 이카운트 "발주 대비 미입고"·Odoo 분할 입고/종결 참고. 상세 `docs/INOUT_MODULE.md`
상세는 `docs/PROJECT_OVERVIEW.md`.
+124 -15
View File
@@ -11,7 +11,7 @@ from __future__ import annotations
from datetime import date
from typing import Any
from psycopg.errors import UndefinedColumn
from psycopg.errors import UndefinedColumn, UndefinedTable
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
@@ -53,13 +53,14 @@ class InoutDBStore:
f"FROM inout_factories f {where} ORDER BY f.is_active DESC, f.sort_order, f.name"
).fetchall()
def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", memo: str = "",
is_active: bool = True, sort_order: int = 0) -> int:
"""공장 추가·수정. 담당자(manager, 002)·연락처(contact)는 따로."""
def save_factory(self, *, factory_id: int | None, name: str, manager: str = "", contact: str = "", email: str = "",
memo: str = "", is_active: bool = True, sort_order: int = 0) -> int:
"""공장 추가·수정. 담당자(manager, 002)·연락처(contact)·이메일(email, 003 — 여러 개는 쉼표)."""
name = (name or "").strip()
if not name or len(name) > 100:
raise ValueError("공장 이름을 1~100자로 입력하세요.")
vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], (memo or "").strip()[:store.MEMO_MAX],
emails = ", ".join(store.parse_emails(email, label="공장 이메일"))
vals = (name, (manager or "").strip()[:100], (contact or "").strip()[:200], emails, (memo or "").strip()[:store.MEMO_MAX],
bool(is_active), int(sort_order))
try:
with self._pool.connection() as conn:
@@ -69,16 +70,16 @@ class InoutDBStore:
raise ValueError(f"같은 이름의 공장이 이미 있습니다: {name}")
if factory_id:
row = conn.execute(
"UPDATE inout_factories SET name=%s, manager=%s, contact=%s, memo=%s, is_active=%s, sort_order=%s "
"UPDATE inout_factories SET name=%s, manager=%s, contact=%s, email=%s, memo=%s, is_active=%s, sort_order=%s "
"WHERE id=%s RETURNING id", (*vals, factory_id)).fetchone()
if not row:
raise ValueError("공장을 찾을 수 없습니다.")
return int(row["id"])
return int(conn.execute(
"INSERT INTO inout_factories (name, manager, contact, memo, is_active, sort_order) "
"VALUES (%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"])
"INSERT INTO inout_factories (name, manager, contact, email, memo, is_active, sort_order) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id", vals).fetchone()["id"])
except UndefinedColumn:
raise ValueError("DB 마이그레이션 inout_db 002(공장 담당자 칸)가 아직 적용되지 않았습니다.") from None
raise ValueError("DB 마이그레이션 inout_db 002·003(공장 담당자·이메일 칸)이 아직 적용되지 않았습니다.") from None
def delete_factory(self, factory_id: int) -> None:
"""발주 기록이 없는 공장만 지운다(있으면 '사용 안 함'으로 숨김)."""
@@ -194,7 +195,8 @@ class InoutDBStore:
with self._pool.connection() as conn:
head = conn.execute(
# 담당자(manager)는 002 열 — 미적용 DB 에서도 깨지지 않게 to_jsonb 로 읽는다
"SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact "
"SELECT o.*, f.name AS factory_name, to_jsonb(f) ->> 'manager' AS factory_manager, f.contact AS factory_contact, "
"COALESCE(to_jsonb(f) ->> 'email', '') AS factory_email "
"FROM inout_orders o JOIN inout_factories f ON f.id = o.factory_id WHERE o.id=%s",
(order_id,)).fetchone()
if not head:
@@ -209,6 +211,17 @@ class InoutDBStore:
"SELECT rl.receipt_id, rl.order_line_id, rl.qty, l.item_code, l.item_name FROM inout_receipt_lines rl "
"JOIN inout_order_lines l ON l.id = rl.order_line_id JOIN inout_receipts r ON r.id = rl.receipt_id "
"WHERE r.order_id=%s ORDER BY l.line_no", (order_id,)).fetchall()
# 입고증 사진(목록만 — 내용은 /inout/photos/{id})·발주 메일 기록 — 003 미적용이면 빈 목록
try:
photos = conn.execute(
"SELECT p.id, p.receipt_id, p.filename, p.content_type, p.size_bytes FROM inout_receipt_photos p "
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE r.order_id=%s ORDER BY p.id", (order_id,)).fetchall()
mails = conn.execute("SELECT * FROM inout_order_mails WHERE order_id=%s ORDER BY sent_at, id", (order_id,)).fetchall()
except UndefinedTable:
photos, mails = [], []
by_photo: dict[int, list[dict[str, Any]]] = {}
for ph in photos:
by_photo.setdefault(int(ph["receipt_id"]), []).append(ph)
by_receipt: dict[int, list[dict[str, Any]]] = {}
for r in rlines:
by_receipt.setdefault(int(r["receipt_id"]), []).append(r)
@@ -216,8 +229,9 @@ class InoutDBStore:
status = store.order_status(lines, closed=bool(head["closed_at"]), cancelled=bool(head["cancelled_at"]))
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"]), []),
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts]}
"receipts": [{**r, "lines": by_receipt.get(int(r["id"]), []), "photos": by_photo.get(int(r["id"]), []),
"total": sum(int(x["qty"]) for x in by_receipt.get(int(r["id"]), []))} for r in receipts],
"mails": mails}
def list_orders(self, *, status: str = "active", factory_id: int | None = None, q: str = "",
date_from: date | None = None, date_to: date | None = None, limit: int = 500) -> list[dict[str, Any]]:
@@ -269,8 +283,18 @@ class InoutDBStore:
# 입고
# ════════════════════════════════════════════════════════════
def add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
confirm_over: bool, by: str) -> dict[str, Any]:
"""입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함)."""
confirm_over: bool, by: str, photos: list[dict[str, Any]] | None = None) -> dict[str, Any]:
"""입고 1건 저장. 발주를 넘는 품목이 있는데 confirm_over 가 아니면 OverReceipt(아무것도 저장 안 함).
photos = store.validate_photos 결과(입고증) — 입고와 한 트랜잭션(사진 저장이 실패하면 입고도 저장 안 함)."""
try:
return self._add_receipt(order_id, quantities, receipt_date=receipt_date, memo=memo,
confirm_over=confirm_over, by=by, photos=photos or [])
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않아 사진을 저장할 수 없습니다 — "
"사진 없이 저장하거나 관리자에게 알려 주세요.") from None
def _add_receipt(self, order_id: int, quantities: dict[int, Any], *, receipt_date: Any, memo: Any,
confirm_over: bool, by: str, photos: list[dict[str, Any]]) -> dict[str, Any]:
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
@@ -289,7 +313,92 @@ class InoutDBStore:
for it in data["items"]:
conn.execute("INSERT INTO inout_receipt_lines (receipt_id, order_line_id, qty) VALUES (%s,%s,%s)",
(rid, it["order_line_id"], it["qty"]))
return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"])}
self._insert_photos(conn, int(rid), photos, by)
return {"id": int(rid), "over": data["over"], "total": sum(it["qty"] for it in data["items"]), "photos": len(photos)}
# ── 입고증 사진(003) ──
@staticmethod
def _insert_photos(conn: Any, receipt_id: int, photos: list[dict[str, Any]], by: str) -> None:
for ph in photos:
conn.execute("INSERT INTO inout_receipt_photos (receipt_id, filename, content_type, size_bytes, data, created_by) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(receipt_id, ph["filename"], ph["content_type"], len(ph["data"]), ph["data"], _norm_email(by)))
def add_receipt_photos(self, order_id: int, receipt_id: int, files: list[tuple[str, bytes]], *, by: str) -> int:
"""이미 있는 입고에 사진 더하기(빠뜨렸을 때). 장수 한도는 잠근 뒤 다시 센다. 반환 = 더한 장수."""
try:
with self._pool.connection() as conn, conn.transaction():
head = self._lock_order(conn, order_id)
if head["cancelled_at"]:
raise ValueError("취소된 발주서입니다.")
if not conn.execute("SELECT 1 FROM inout_receipts WHERE id=%s AND order_id=%s", (receipt_id, order_id)).fetchone():
raise ValueError("입고 기록을 찾을 수 없습니다.")
have = int(conn.execute("SELECT count(*) AS n FROM inout_receipt_photos WHERE receipt_id=%s",
(receipt_id,)).fetchone()["n"])
photos = store.validate_photos(files, existing=have)
if not photos:
raise ValueError("올릴 사진을 고르세요.")
self._insert_photos(conn, receipt_id, photos, by)
return len(photos)
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(입고증 사진)이 아직 적용되지 않았습니다.") from None
def delete_receipt_photo(self, order_id: int, photo_id: int) -> None:
with self._pool.connection() as conn, conn.transaction():
self._lock_order(conn, order_id)
row = conn.execute("DELETE FROM inout_receipt_photos p USING inout_receipts r "
"WHERE p.id=%s AND p.receipt_id = r.id AND r.order_id=%s RETURNING p.id",
(photo_id, order_id)).fetchone()
if not row:
raise ValueError("사진을 찾을 수 없습니다.")
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
"""사진 내용(+ 발주서 id) — 보여 주기용."""
try:
with self._pool.connection() as conn:
return conn.execute("SELECT p.id, p.filename, p.content_type, p.data, r.order_id FROM inout_receipt_photos p "
"JOIN inout_receipts r ON r.id = p.receipt_id WHERE p.id=%s", (photo_id,)).fetchone()
except UndefinedTable:
return None
# ════════════════════════════════════════════════════════════
# Gmail 연결(사람별, 갱신 토큰 암호문만) · 발주 메일 기록 — 003
# ════════════════════════════════════════════════════════════
def gmail_token(self, email: str) -> dict[str, Any] | None:
try:
with self._pool.connection() as conn:
return conn.execute("SELECT * FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),)).fetchone()
except UndefinedTable:
return None
def save_gmail_token(self, email: str, *, refresh_token_enc: str, scopes: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_gmail_tokens (email, refresh_token_enc, scopes, connected_at, last_error) "
"VALUES (%s,%s,%s,now(),'') ON CONFLICT (email) DO UPDATE SET refresh_token_enc=EXCLUDED.refresh_token_enc, "
"scopes=EXCLUDED.scopes, connected_at=now(), last_error=''",
(_norm_email(email), refresh_token_enc, scopes[:500]))
except UndefinedTable:
raise ValueError("DB 마이그레이션 inout_db 003(발주 메일)이 아직 적용되지 않았습니다.") from None
def delete_gmail_token(self, email: str) -> None:
try:
with self._pool.connection() as conn:
conn.execute("DELETE FROM inout_gmail_tokens WHERE email=%s", (_norm_email(email),))
except UndefinedTable:
pass
def mark_gmail(self, email: str, *, error: str = "") -> None:
"""보낸 뒤 — 성공이면 마지막 사용 시각, 실패면 오류 문구(비밀값 없음)."""
with self._pool.connection() as conn:
conn.execute("UPDATE inout_gmail_tokens SET last_used_at = CASE WHEN %s = '' THEN now() ELSE last_used_at END, "
"last_error=%s WHERE email=%s", (error[:300], error[:300], _norm_email(email)))
def add_order_mail(self, order_id: int, *, sent_by: str, to: list[str], cc: list[str], subject: str, gmail_id: str) -> None:
with self._pool.connection() as conn:
conn.execute("INSERT INTO inout_order_mails (order_id, sent_by, to_addrs, cc_addrs, subject, gmail_id) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(order_id, _norm_email(sent_by), ", ".join(to), ", ".join(cc), subject[:300], gmail_id[:100]))
def delete_receipt(self, order_id: int, receipt_id: int, *, by: str) -> None:
"""잘못 넣은 입고 1건을 지운다(그 수량만큼 다시 미입고)."""
+186
View File
@@ -0,0 +1,186 @@
"""발주 메일 — 발주 담당자 본인 Gmail 로 보내기(2026-10-16 사용자 요청, Gmail API).
연결(사람마다 한 번): [Gmail 연결] → 구글 동의 화면(로그인과 같은 OAuth 클라이언트 GOOGLE_CLIENT_ID, 범위 = gmail.send 만)
→ /inout/gmail/callback 에서 ① 고른 구글 계정이 ERP 로그인 계정과 같은지(다르면 거절 — 남의 메일함으로 보내지 않게)
② gmail.send 를 허락했는지 ③ 갱신 토큰이 왔는지 확인 → 갱신 토큰을 APP_ENCRYPTION_KEY(실적 모듈과 같은 마스터 키,
AES-256-GCM, AAD = inout:gmail:{email})로 암호화해 inout_gmail_tokens 에. 원문·접근 토큰은 저장·출력하지 않는다.
보내기: 갱신 토큰 → 접근 토큰(oauth2.googleapis.com/token) → gmail.users.messages.send(raw = RFC 822, 글 + HTML).
사람이 [메일 발송]을 눌렀을 때만 보낸다(자동 발송 없음). 연결이 끊겼으면(invalid_grant·권한 없음) 다시 연결 안내.
구글 클라우드 준비(관리자 1회): Gmail API 사용 설정 · OAuth 동의 화면에 …/auth/gmail.send 범위 추가 ·
OAuth 클라이언트의 승인된 리디렉션 URI 에 {PUBLIC_BASE_URL}/inout/gmail/callback 추가. 상세 docs/INOUT_MODULE.md.
"""
from __future__ import annotations
import base64
import os
from email.message import EmailMessage
from email.utils import formataddr
from typing import Any
import httpx
GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
TOKEN_URI = "https://oauth2.googleapis.com/token"
SEND_URI = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
CLIENT_NAME = "inout_gmail"
class GmailNotConnected(Exception):
"""Gmail 연결이 없거나 끊김 — 다시 [Gmail 연결]."""
class GmailError(Exception):
"""보내기 실패(구글 오류 등) — 문구는 화면에 그대로(비밀값 없음)."""
def _http() -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=20.0)
# ── 토큰 암호화(실적 모듈과 같은 마스터 키) ─────────────────
def _ring() -> Any:
from app.modules.performance.security.crypto import CryptoConfigError, KeyRing # noqa: WPS433
try:
return KeyRing.from_env()
except CryptoConfigError as exc:
raise GmailError(f"암호화 키가 없어 Gmail 연결을 저장할 수 없습니다 — {exc}") from None
def _aad(email: str) -> str:
return f"inout:gmail:{(email or '').strip().lower()}"
def encrypt_token(email: str, refresh_token: str) -> str:
from app.modules.performance.security.crypto import encrypt # noqa: WPS433
return encrypt(refresh_token, aad=_aad(email), ring=_ring())
def decrypt_token(email: str, enc: str) -> str:
from app.modules.performance.security.crypto import DecryptError, decrypt # noqa: WPS433
try:
return decrypt(enc, aad=_aad(email), ring=_ring())
except DecryptError:
raise GmailNotConnected("저장된 Gmail 연결을 읽을 수 없습니다(암호화 키가 바뀌었을 수 있음) — 다시 연결하세요.") from None
# ── OAuth 클라이언트(로그인과 같은 GOOGLE_CLIENT_ID, 범위만 다름) ──
def oauth_client() -> Any:
from app.main import env, oauth # noqa: WPS433
if not env("GOOGLE_CLIENT_ID") or not env("GOOGLE_CLIENT_SECRET"):
raise GmailError("GOOGLE_CLIENT_ID/SECRET 이 없어 Gmail 을 연결할 수 없습니다.")
client = oauth.create_client(CLIENT_NAME)
if client is None:
oauth.register(
name=CLIENT_NAME,
client_id=env("GOOGLE_CLIENT_ID"),
client_secret=env("GOOGLE_CLIENT_SECRET"),
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": f"openid email {GMAIL_SCOPE}"},
)
client = oauth.create_client(CLIENT_NAME)
return client
def check_grant(token: dict[str, Any], *, expected_email: str) -> tuple[str, str]:
"""콜백 토큰 확인 → (갱신 토큰, 허락된 범위). 계정이 다르거나 발송 권한·갱신 토큰이 없으면 GmailError."""
info = token.get("userinfo") or {}
got = str(info.get("email") or "").strip().lower()
want = (expected_email or "").strip().lower()
if not got or got != want:
raise GmailError(f"ERP 로그인 계정({want})과 다른 구글 계정({got or '알 수 없음'})을 골랐습니다 — 같은 계정으로 다시 연결하세요.")
scopes = str(token.get("scope") or "")
if GMAIL_SCOPE not in scopes.split():
raise GmailError("메일 보내기 권한(gmail.send)을 허락하지 않았습니다 — 동의 화면에서 체크한 뒤 다시 연결하세요.")
refresh = str(token.get("refresh_token") or "")
if not refresh:
raise GmailError("구글이 갱신 토큰을 주지 않았습니다 — 구글 계정 → 보안 → 타사 앱 접근에서 이 앱을 지우고 다시 연결하세요.")
return refresh, scopes
# ── 보내기 ──────────────────────────────────────────────
def _google_message(resp: httpx.Response) -> str:
try:
body = resp.json()
except ValueError:
return f"HTTP {resp.status_code}"
err = body.get("error")
if isinstance(err, dict):
return str(err.get("message") or err.get("status") or resp.status_code)[:200]
return str(body.get("error_description") or err or resp.status_code)[:200]
def access_token(refresh_token: str) -> str:
from app.main import env # noqa: WPS433
try:
with _http() as client:
resp = client.post(TOKEN_URI, data={"client_id": env("GOOGLE_CLIENT_ID"), "client_secret": env("GOOGLE_CLIENT_SECRET"),
"refresh_token": refresh_token, "grant_type": "refresh_token"})
except httpx.HTTPError as exc:
raise GmailError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
try:
code = str(resp.json().get("error") or "")
except ValueError:
code = ""
if code in ("invalid_grant", "unauthorized_client", "invalid_client"):
raise GmailNotConnected("Gmail 연결이 끊겼습니다(권한 취소·비밀번호 변경 등) — 다시 연결하세요.")
raise GmailError(f"구글 인증 실패: {_google_message(resp)}")
token = str(resp.json().get("access_token") or "")
if not token:
raise GmailError("구글 인증 서버가 접근 토큰을 주지 않았습니다.")
return token
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
text: str, html: str) -> bytes:
msg = EmailMessage()
msg["From"] = formataddr((sender_name or sender_email, sender_email))
msg["To"] = ", ".join(to)
if cc:
msg["Cc"] = ", ".join(cc)
msg["Subject"] = subject
msg.set_content(text)
msg.add_alternative(html, subtype="html")
return msg.as_bytes()
def send(refresh_token: str, raw: bytes) -> str:
"""보내고 Gmail 메시지 id 를 돌려준다."""
token = access_token(refresh_token)
body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
try:
with _http() as client:
resp = client.post(SEND_URI, json=body, headers={"Authorization": f"Bearer {token}"})
except httpx.HTTPError as exc:
raise GmailError(f"Gmail 에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code in (401, 403):
msg = _google_message(resp)
if "has not been used" in msg or "disabled" in msg.lower():
raise GmailError(f"Gmail API 가 꺼져 있습니다 — 관리자가 구글 클라우드에서 Gmail API 를 사용 설정해야 합니다. ({msg})")
raise GmailNotConnected(f"Gmail 보내기 권한이 없습니다 — 다시 연결하세요. ({msg})")
if resp.status_code != 200:
raise GmailError(f"메일을 보내지 못했습니다: {_google_message(resp)}")
return str(resp.json().get("id") or "")
def revoke(refresh_token: str) -> None:
"""연결 끊기 — 구글 쪽 권한도 취소(실패해도 무시, 우리 쪽 토큰은 지운다)."""
try:
with _http() as client:
client.post(REVOKE_URI, data={"token": refresh_token})
except httpx.HTTPError:
pass
def configured() -> bool:
"""APP_ENCRYPTION_KEY·GOOGLE_CLIENT_ID/SECRET 이 있는지(화면 안내용)."""
return bool(os.getenv("APP_ENCRYPTION_KEY", "").strip() and os.getenv("GOOGLE_CLIENT_ID", "").strip()
and os.getenv("GOOGLE_CLIENT_SECRET", "").strip())
+228 -9
View File
@@ -10,6 +10,9 @@
POST /inout/orders/{id}/receipts/{rid}/delete 잘못 넣은 입고 지우기(입고 담당)
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
GET /inout/gmail/connect · /gmail/callback · POST /gmail/disconnect Gmail 연결(사람별, gmail.send 만)
GET /inout/api/items?q= 코드표 단품 검색(JSON)
권한: 모듈 권한키 `inout`(조회). 발주 담당·입고 담당은 옵션(inout_roles)에서 지정, ERP 관리자는 둘 다 + 옵션.
@@ -21,8 +24,8 @@ from datetime import date
from typing import Any
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from fastapi import APIRouter, Body, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from app.timezone import today_kst
@@ -266,7 +269,7 @@ async def order_create(request: Request) -> Any:
res = st.create_order(data, names, by=user.get("email", ""))
except ValueError as exc:
return _form_page(request, user, st, order=None, vals=vals, error=str(exc), status_code=400)
return _redirect(f"/inout/orders/{res['id']}", f"발주서 {res['order_no']} 을(를) 만들었습니다.")
return _redirect(f"/inout/orders/{res['id']}?mail=1", f"발주서 {res['order_no']} 을(를) 만들었습니다.") # 메일 미리보기 바로
@router.get("/orders/{order_id}/edit", response_class=HTMLResponse)
@@ -305,9 +308,13 @@ async def order_update(request: Request, order_id: int) -> Any:
# 발주서 화면 · 종결 · 취소
# ────────────────────────────────────────────────────────────
def _detail(request: Request, user: dict[str, Any], st: Any, order: dict[str, Any], *, receipt_form: dict[str, Any] | None = None,
error: str = "", over: list[dict[str, Any]] | None = None, status_code: int = 200) -> HTMLResponse:
error: str = "", over: list[dict[str, Any]] | None = None, photos_lost: bool = False,
status_code: int = 200) -> HTMLResponse:
perms = _perms(st, user)
return _render(request, "inout/order_detail.html", user, {
"tab": "orders", "order": order, "error": error, "over": over or [],
"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"],
"max_photos": store.MAX_PHOTOS,
"receipt_form": receipt_form or {"receipt_date": today_kst().isoformat(), "memo": "", "qty": {}},
"can_receive_now": order["status"] in (store.ST_OPEN, store.ST_PARTIAL, store.ST_DONE, store.ST_OVER),
}, status_code=status_code)
@@ -381,16 +388,24 @@ async def receipt_add(request: Request, order_id: int) -> Any:
if k.startswith("qty_") and k[4:].isdigit():
qty[int(k[4:])] = str(v)
rf = {"receipt_date": str(form.get("receipt_date") or ""), "memo": str(form.get("memo") or ""), "qty": qty}
had_photos = False
try:
raw_photos = await _read_photos(form)
had_photos = any(data for _n, data in raw_photos)
photos = store.validate_photos(raw_photos)
res = st.add_receipt(order_id, qty, receipt_date=rf["receipt_date"], memo=rf["memo"],
confirm_over=form.get("confirm_over") == "1", by=user.get("email", ""))
confirm_over="1" in form.getlist("confirm_over"), by=user.get("email", ""), photos=photos)
except OverReceipt as exc:
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, over=exc.over, status_code=409)
# 화면이 다시 그려지면 고른 파일은 사라진다 — 사진을 골랐었다면 다시 첨부하라고 알린다
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, over=exc.over,
photos_lost=had_photos, status_code=409)
except LookupError:
raise HTTPException(status_code=404, detail="발주서를 찾을 수 없습니다.") from None
except ValueError as exc:
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, error=str(exc), status_code=400)
note = f"입고 {res['total']:,}개를 저장했습니다." + (" (초과 입고 포함)" if res["over"] else "")
return _detail(request, user, st, _order_or_404(st, order_id), receipt_form=rf, error=str(exc),
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)
@@ -408,6 +423,209 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
return _redirect(f"/inout/orders/{order_id}", "입고 기록을 지웠습니다 — 그만큼 다시 미입고로 잡힙니다.")
# ────────────────────────────────────────────────────────────
# 입고증 사진(003) — 입고와 함께 / 나중에 더하기 / 지우기 / 보기
# ────────────────────────────────────────────────────────────
_PHOTO_HEADERS = {
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
"Cache-Control": "private, max-age=86400",
}
async def _read_photos(form: Any) -> list[tuple[str, bytes]]:
"""폼의 photos 파일들 → [(이름, 내용)]. 한 장은 한도 + 1바이트까지만 읽는다(너무 크면 검사에서 거절)."""
out: list[tuple[str, bytes]] = []
for f in form.getlist("photos"):
if not hasattr(f, "read"):
continue
if len(out) > store.MAX_PHOTOS:
raise ValueError(f"입고 한 건에 사진은 {store.MAX_PHOTOS}장까지입니다.")
out.append((str(getattr(f, "filename", "") or ""), await f.read(store.MAX_PHOTO_BYTES + 1)))
return out
@router.post("/orders/{order_id}/receipts/{receipt_id}/photos")
async def receipt_photos_add(request: Request, order_id: int, receipt_id: int) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "receive")
try:
n = st.add_receipt_photos(order_id, receipt_id, await _read_photos(await request.form()), by=user.get("email", ""))
except (ValueError, LookupError) as exc:
return _redirect(f"/inout/orders/{order_id}", str(exc))
return _redirect(f"/inout/orders/{order_id}", f"입고증 사진 {n}장을 더했습니다.")
@router.post("/orders/{order_id}/photos/{photo_id}/delete")
def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "receive")
try:
st.delete_receipt_photo(order_id, photo_id)
except (ValueError, LookupError) as exc:
return _redirect(f"/inout/orders/{order_id}", str(exc))
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
@router.get("/photos/{photo_id}")
def photo_view(request: Request, photo_id: int) -> Response:
_user(request)
st = _store(request)
row = st.get_photo(photo_id) if st is not None else None
if row is None:
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
from urllib.parse import quote # noqa: WPS433
name = quote(str(row["filename"] or f"photo-{photo_id}"))
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
return Response(content=bytes(row["data"]), media_type=row["content_type"],
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
# ────────────────────────────────────────────────────────────
# 발주 메일 — 발주 담당 본인 Gmail(003). 연결은 사람마다 한 번, 보내기는 [메일 발송]을 눌렀을 때만.
# ────────────────────────────────────────────────────────────
def _safe_next(nxt: Any) -> str:
s = str(nxt or "")
return s if s.startswith("/inout/") and "//" not in s and "\\" not in s else "/inout/"
@router.get("/gmail/connect")
async def gmail_connect(request: Request, next: str = "/inout/") -> Any: # noqa: A002 — 쿼리 이름
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "order")
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
from . import gmail # noqa: WPS433
try:
client = gmail.oauth_client()
except gmail.GmailError as exc:
return _redirect(_safe_next(next), str(exc))
request.session["_inout_gmail_next"] = _safe_next(next)
return await client.authorize_redirect(
request, public_url_for(request, "inout_gmail_callback"),
access_type="offline", prompt="consent", include_granted_scopes="true",
login_hint=user.get("email", ""), hd=ALLOWED_DOMAIN)
@router.get("/gmail/callback", name="inout_gmail_callback")
async def gmail_callback(request: Request) -> Any:
got = _ctx(request)
if not isinstance(got, tuple):
return got
st, user = got
_require(st, user, "order")
from authlib.integrations.starlette_client import OAuthError # noqa: WPS433
from . import gmail # noqa: WPS433
nxt = _safe_next(request.session.pop("_inout_gmail_next", "/inout/"))
email = user.get("email", "")
try:
token = await gmail.oauth_client().authorize_access_token(request)
refresh, scopes = gmail.check_grant(token, expected_email=email)
st.save_gmail_token(email, refresh_token_enc=gmail.encrypt_token(email, refresh), scopes=scopes)
except OAuthError as exc:
msg = "Gmail 연결을 취소했습니다." if exc.error == "access_denied" else f"Gmail 연결 실패({exc.error})"
return _redirect(nxt, msg)
except (gmail.GmailError, ValueError) as exc:
return _redirect(nxt, str(exc))
return _redirect(nxt, "Gmail 을 연결했습니다 — 이제 [메일 발송]으로 보낼 수 있습니다.")
@router.post("/gmail/disconnect")
def gmail_disconnect(request: Request) -> JSONResponse:
user = _user(request)
st = _store(request)
if st is None:
raise HTTPException(status_code=503, detail="입출고 관리 모듈이 설정되지 않았습니다.")
from . import gmail # noqa: WPS433
row = st.gmail_token(user.get("email", ""))
if row:
try:
gmail.revoke(gmail.decrypt_token(user.get("email", ""), row["refresh_token_enc"]))
except (gmail.GmailError, gmail.GmailNotConnected):
pass
st.delete_gmail_token(user.get("email", ""))
return JSONResponse({"ok": True, "message": "Gmail 연결을 끊었습니다."})
def _mail_order(request: Request, order_id: int) -> tuple[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, "order")
order = _order_or_404(st, order_id)
if order["cancelled_at"]:
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
return st, user, order
@router.get("/orders/{order_id}/mail")
def mail_preview(request: Request, order_id: int) -> JSONResponse:
"""메일 미리보기 — 받는 사람(공장 이메일)·제목·본문, Gmail 연결 여부, 보낸 기록."""
st, user, order = _mail_order(request, order_id)
from . import gmail # noqa: WPS433
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=user.get("email", ""))
tok = st.gmail_token(user.get("email", ""))
return JSONResponse({
"connected": tok is not None, "configured": gmail.configured(),
"connect_url": f"/inout/gmail/connect?{urlencode({'next': f'/inout/orders/{order_id}?mail=1'})}",
"from": user.get("email", ""), "to": order.get("factory_email") or "", "factory": order["factory_name"],
"subject": mail["subject"], "html": mail["html"],
"sent": [{"at": m["sent_at"].strftime("%Y-%m-%d %H:%M"), "by": m["sent_by"], "to": m["to_addrs"]} for m in order["mails"]],
})
@router.post("/orders/{order_id}/mail")
def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""[메일 발송] — 사람이 누를 때만. 이미 보낸 발주서는 resend=true 를 함께 보내야(실수로 두 번 보내지 않게)."""
st, user, order = _mail_order(request, order_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 order["mails"] and not payload.get("resend"):
return JSONResponse({"ok": False, "resend_needed": True,
"message": f"이미 {len(order['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 = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
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"])
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_order_mail(order_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 관리자)
# ────────────────────────────────────────────────────────────
@@ -475,6 +693,7 @@ async def settings_factory_save(request: Request) -> Any:
try:
st.save_factory(factory_id=_opt_int(form.get("id")), name=str(form.get("name") or ""),
manager=str(form.get("manager") or ""), contact=str(form.get("contact") or ""),
email=str(form.get("email") or ""),
memo=str(form.get("memo") or ""), is_active=form.get("is_active") == "1",
sort_order=_opt_int(form.get("sort_order")) or 0)
except ValueError as exc:
+111
View File
@@ -8,6 +8,8 @@
from __future__ import annotations
import html as _html
import re
from datetime import date
from typing import Any, Iterable
@@ -202,3 +204,112 @@ def validate_receipt(order_lines: list[dict[str, Any]], quantities: dict[int, An
def order_no(order_date: date, seq: int) -> str:
"""PO-YYMMDD-NN — 발주일 기준 그날 순번(01부터)."""
return f"PO-{order_date:%y%m%d}-{seq:02d}"
# ════════════════════════════════════════════════════════════
# 발주 메일(2026-10-16, 마이그레이션 003) — 받는 주소 검사, 본문(요약) 만들기. 보내기는 gmail.py
# ════════════════════════════════════════════════════════════
MAX_RECIPIENTS = 10
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False) -> list[str]:
"""'a@x.com, b@y.co.kr; c@z.com' → 주소 목록(순서 유지·중복 제거). 형식이 틀리면 ValueError."""
out: list[str] = []
for part in re.split(r"[\s,;]+", str(raw or "")):
if not part:
continue
if not _EMAIL_RE.match(part) or len(part) > 254:
raise ValueError(f"{label} 형식이 올바르지 않습니다: {part[:60]}")
if part.lower() not in [x.lower() for x in out]:
out.append(part)
if required and not out:
raise ValueError(f"{label}을(를) 입력하세요.")
if len(out) > MAX_RECIPIENTS:
raise ValueError(f"{label}은(는) {MAX_RECIPIENTS}개까지 넣을 수 있습니다.")
return out
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과."""
lines = order["lines"]
first = (lines[0]["item_name"] or lines[0]["item_code"]) if lines else ""
more = f" 외 {len(lines) - 1}종" if len(lines) > 1 else ""
subject = f"[발주] {order['order_no']} · {order['factory_name']} · {first}{more}"
total = sum(int(x["qty"]) for x in lines)
due = order["due_date"].strftime("%Y-%m-%d") if order.get("due_date") else "협의"
greet = f"{order['factory_manager']}님, 안녕하세요." if order.get("factory_manager") else "안녕하세요."
who = sender_name or sender_email
facts = [("발주번호", order["order_no"]), ("발주일", order["order_date"].strftime("%Y-%m-%d")),
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
if order.get("memo"):
facts.append(("요청 사항", order["memo"]))
# 글 본문(HTML 을 못 보는 메일 프로그램용)
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
text += [f"- {k}: {v}" for k, v in facts]
text += ["", "[발주 품목]"]
for i, x in enumerate(lines, start=1):
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개" + (f" ({x['memo']})" if x.get("memo") else ""))
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
# HTML 본문 — 값은 모두 escape
e = _html.escape
td = "padding:6px 10px;border:1px solid #d9dce1;"
fact_rows = "".join(f'<tr><th style="{td}background:#f6f7f9;text-align:left;white-space:nowrap">{e(k)}</th>'
f'<td style="{td}">{e(str(v))}</td></tr>' for k, v in facts)
item_rows = "".join(
f'<tr><td style="{td}text-align:center">{i}</td><td style="{td}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
f'<td style="{td}">{e(x["item_name"])}</td><td style="{td}text-align:right">{int(x["qty"]):,}</td>'
f'<td style="{td}">{e(x.get("memo") or "")}</td></tr>' for i, x in enumerate(lines, start=1))
html = (
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
f'<table style="border-collapse:collapse;margin:8px 0 16px">{fact_rows}</table>'
'<table style="border-collapse:collapse;min-width:520px">'
f'<thead><tr style="background:#f6f7f9"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
f'<th style="{td}">수량</th><th style="{td}">비고</th></tr></thead><tbody>{item_rows}</tbody>'
f'<tfoot><tr><th colspan="3" style="{td}text-align:right;background:#f6f7f9">합계</th>'
f'<th style="{td}text-align:right;background:#f6f7f9">{total:,}</th><th style="{td}background:#f6f7f9"></th></tr></tfoot></table>'
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
)
return {"subject": subject, "text": "\n".join(text), "html": html}
# ════════════════════════════════════════════════════════════
# 입고증 사진(2026-10-16, 마이그레이션 003)
# ════════════════════════════════════════════════════════════
MAX_PHOTOS = 10 # 입고 한 건에
MAX_PHOTO_BYTES = 10 * 1024 * 1024 # 한 장(브라우저가 줄여서 보내므로 보통 0.3~1MB)
def sniff_image(data: bytes) -> str | None:
"""파일 머리로 이미지 종류 판단(브라우저가 보낸 종류는 믿지 않는다). 모르면 None."""
if data[:3] == b"\xff\xd8\xff":
return "image/jpeg"
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
return "image/webp"
if data[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
if data[4:12] in (b"ftypheic", b"ftypheix", b"ftypmif1", b"ftyphevc", b"ftypheif"):
return "image/heic" # 아이폰 원본 — 사파리 외 브라우저는 미리보기 못 함(내려받기)
return None
def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> list[dict[str, Any]]:
"""[(파일 이름, 내용)] → [{filename, content_type, data}]. 빈 파일은 건너뛴다. 하나라도 틀리면 ValueError."""
out: list[dict[str, Any]] = []
for name, data in files:
if not data:
continue
name = (name or "photo").replace("\\", "/").rsplit("/", 1)[-1][:120]
if len(data) > MAX_PHOTO_BYTES:
raise ValueError(f"사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지): {name}")
ctype = sniff_image(data)
if ctype is None:
raise ValueError(f"사진 파일(JPG·PNG·WEBP·GIF·HEIC)만 올릴 수 있습니다: {name}")
out.append({"filename": name, "content_type": ctype, "data": data})
if existing + len(out) > MAX_PHOTOS:
raise ValueError(f"입고 한 건에 사진은 {MAX_PHOTOS}장까지입니다.")
return out
@@ -33,12 +33,12 @@
</section>
<section class="io-dlg-pane" data-pane="factories" role="tabpanel" hidden>
<p class="io-help">발주서에서 고르는 공장(발주처)입니다. 발주 기록이 있는 공장은 지우지 말고 <b>사용</b>을 끄면 목록에서 숨겨집니다.</p>
<p class="io-help">발주서에서 고르는 공장(발주처)입니다. <b>이메일</b>은 발주 메일을 받을 주소(여러 개는 쉼표). 발주 기록이 있는 공장은 지우지 말고 <b>사용</b>을 끄면 목록에서 숨겨집니다.</p>
{% for f in factories %}<form method="post" action="/inout/settings/factories" id="io-f{{ f.id }}" class="io-dlg-form"><input type="hidden" name="id" value="{{ f.id }}" /></form>{% endfor %}
<form method="post" action="/inout/settings/factories" id="io-fnew" class="io-dlg-form"><input type="hidden" name="is_active" value="1" /></form>
<table class="io-dlg-table io-factory-table">
<colgroup><col class="w-name" /><col class="w-man" /><col class="w-tel" /><col class="w-memo" /><col class="w-sort" /><col class="w-use" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>공장 이름</th><th>담당자</th><th>연락처</th><th>메모</th><th class="io-c">순서</th><th class="io-c">사용</th><th class="io-c">발주</th><th></th></tr></thead>
<colgroup><col class="w-name" /><col class="w-man" /><col class="w-tel" /><col class="w-mail" /><col class="w-memo" /><col class="w-sort" /><col class="w-use" /><col class="w-cnt" /><col class="w-btn" /></colgroup>
<thead><tr><th>공장 이름</th><th>담당자</th><th>연락처</th><th title="발주 메일을 받을 주소 — 여러 개는 쉼표로">이메일</th><th>메모</th><th class="io-c">순서</th><th class="io-c">사용</th><th class="io-c">발주</th><th></th></tr></thead>
<tbody>
{% for f in factories %}
{% set fid = 'io-f' ~ f.id %}
@@ -46,6 +46,7 @@
<td><input class="io-in" form="{{ fid }}" type="text" name="name" value="{{ f.name }}" maxlength="100" required aria-label="공장 이름" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" name="manager" value="{{ f.manager }}" maxlength="100" aria-label="담당자" /></td>
<td><input class="io-in" form="{{ fid }}" type="tel" name="contact" value="{{ f.contact }}" maxlength="200" aria-label="연락처" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" inputmode="email" name="email" value="{{ f.email }}" maxlength="600" aria-label="이메일" placeholder="발주 메일 받는 주소" /></td>
<td><input class="io-in" form="{{ fid }}" type="text" name="memo" value="{{ f.memo }}" maxlength="500" aria-label="메모" /></td>
<td class="io-c"><input class="io-in io-in-num" form="{{ fid }}" type="number" name="sort_order" value="{{ f.sort_order }}" aria-label="순서" /></td>
<td class="io-c"><input form="{{ fid }}" type="checkbox" name="is_active" value="1" {% if f.is_active %}checked{% endif %} aria-label="사용" /></td>
@@ -61,6 +62,7 @@
<td><input class="io-in" form="io-fnew" type="text" name="name" maxlength="100" required placeholder="새 공장 이름" aria-label="새 공장 이름" /></td>
<td><input class="io-in" form="io-fnew" type="text" name="manager" maxlength="100" placeholder="담당자" aria-label="담당자" /></td>
<td><input class="io-in" form="io-fnew" type="tel" name="contact" maxlength="200" placeholder="010-0000-0000" aria-label="연락처" /></td>
<td><input class="io-in" form="io-fnew" type="text" inputmode="email" name="email" maxlength="600" placeholder="factory@example.com" aria-label="이메일" /></td>
<td><input class="io-in" form="io-fnew" type="text" name="memo" maxlength="500" placeholder="메모" aria-label="메모" /></td>
<td class="io-c"><input class="io-in io-in-num" form="io-fnew" type="number" name="sort_order" value="0" aria-label="순서" /></td>
<td></td><td></td>
+2 -2
View File
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import status_badge, progress, due, n %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016d" />{% endblock %}
{% block content %}
<section class="io">
@@ -58,4 +58,4 @@
</div>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016c" defer></script>{% endblock %}
@@ -1,10 +1,11 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import status_badge, progress, due, n %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016d" />{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
{% set receiving = perms.can_receive and can_receive_now %}
{% set photo_admin = perms.can_receive and not order.cancelled_at %}
<section class="io">
{% include "inout/_nav.html" %}
@@ -18,6 +19,7 @@
<div><dt>발주일</dt><dd>{{ order.order_date.strftime('%Y-%m-%d') }}</dd></div>
<div><dt>입고 예정일</dt><dd>{{ due(order.due_date, today, active) }}</dd></div>
<div><dt>진행</dt><dd>{{ progress(order.summary) }}</dd></div>
<div><dt>발주 메일</dt><dd>{% if order.mails %}{% set last = order.mails[-1] %}<span class="io-mail-sent">보냄 {{ last.sent_at.strftime('%m-%d %H:%M') }}</span><span class="io-factory-who">{{ last.sent_by }} → {{ last.to_addrs }}{% if order.mails|length > 1 %} · 모두 {{ order.mails|length }}번{% endif %}</span>{% else %}<span class="erp-muted">아직 안 보냄</span>{% endif %}</dd></div>
{% if order.memo %}<div class="io-wide"><dt>메모</dt><dd>{{ order.memo }}</dd></div>{% endif %}
{% if order.closed_at %}<div class="io-wide"><dt>종결</dt><dd>{{ order.closed_at.strftime('%Y-%m-%d') }} · {{ order.closed_by }}{% if order.close_reason %} — {{ order.close_reason }}{% endif %}</dd></div>{% endif %}
{% if order.cancelled_at %}<div class="io-wide"><dt>취소</dt><dd>{{ order.cancelled_at.strftime('%Y-%m-%d') }} · {{ order.cancelled_by }}</dd></div>{% endif %}
@@ -31,6 +33,10 @@
</div>
{% if perms.can_order and not order.cancelled_at %}
<div class="io-head-actions">
<button type="button" class="erp-btn erp-btn-primary erp-btn-sm io-mail-btn" id="io-mail-btn" data-order="{{ order.id }}"
{% if open_mail %}data-open="1"{% endif %} aria-haspopup="dialog">
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>
{% if order.mails %}발주 메일 다시 보내기{% else %}발주 메일 보내기{% endif %}</button>
<a class="erp-btn erp-btn-outline erp-btn-sm" href="/inout/orders/{{ order.id }}/edit">발주서 고치기</a>
{% if order.closed_at %}
<form method="post" action="/inout/orders/{{ order.id }}/reopen"><button class="erp-btn erp-btn-outline erp-btn-sm" type="submit">종결 풀기</button></form>
@@ -51,9 +57,10 @@
{% if error %}<div class="io-error" role="alert">{% for line in error.split('\n') %}<div>{{ line }}</div>{% endfor %}</div>{% endif %}
<form method="post" action="/inout/orders/{{ order.id }}/receipts" class="erp-card-block io-block" id="io-receipt-form">
<form method="post" action="/inout/orders/{{ order.id }}/receipts" class="erp-card-block io-block" id="io-receipt-form" enctype="multipart/form-data">
{# Enter 키 = 이 버튼(일반 저장). 없으면 폼의 첫 제출 버튼인 [초과 입고로 저장]이 눌려 확인 없이 초과가 저장된다 #}
{% if receiving %}<button type="submit" class="io-default-submit" tabindex="-1" aria-hidden="true">입고 저장</button>{% endif %}
<input type="hidden" name="confirm_over" value="" id="io-confirm-over" />
<div class="erp-card-block-head">
<h2>품목</h2>
{% if receiving %}<span class="erp-muted">물류에 들어온 수량을 [이번 입고]에 넣고 저장 — 여러 번 나눠 넣어도 됩니다</span>
@@ -64,9 +71,12 @@
<div class="io-over-box" role="alert">
<b>발주보다 많이 입고하려고 합니다.</b> 맞으면 [초과 입고로 저장]을 누르세요.
<ul>{% for o in over %}<li><span class="io-code">{{ o.item_code }}</span> {{ o.item_name }} — 발주 {{ n(o.ordered) }}개, 입고 후 {{ n(o.after) }}개 (<b>+{{ n(o.over) }}</b>)</li>{% endfor %}</ul>
{% if photos_lost %}<p class="io-photo-lost">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>{% endif %}
<button type="submit" class="io-btn-over" name="confirm_over" value="1">초과 입고로 저장</button>
<span class="erp-muted">숫자를 고치려면 아래 칸을 고친 뒤 [입고 저장]</span>
</div>
{% elif photos_lost %}
<p class="io-error">고른 입고증 사진은 다시 첨부해야 합니다(화면이 다시 열리면서 빠졌습니다).</p>
{% endif %}
<div class="erp-table-wrap">
@@ -84,7 +94,8 @@
<td class="io-num{% if ln.remaining and active %} io-remaining{% endif %}">{{ n(ln.remaining) }}{% if ln.over %}<div class="io-over-sub">초과 +{{ n(ln.over) }}</div>{% endif %}</td>
<td>{{ status_badge(ln.status, ln.status_label) }}</td>
{% if receiving %}<td class="io-col-recv"><input class="erp-input io-qty io-recv" type="text" inputmode="numeric" name="qty_{{ ln.id }}"
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" placeholder="{{ ln.remaining if ln.remaining else '' }}"
value="{{ receipt_form.qty.get(ln.id, '') }}" data-remaining="{{ ln.remaining }}" data-ordered="{{ ln.qty }}" data-received="{{ ln.received }}"
data-code="{{ ln.item_code }}" data-name="{{ ln.item_name }}" placeholder="{{ ln.remaining if ln.remaining else '' }}"
aria-label="{{ ln.item_code }} 이번 입고 수량" /></td>{% endif %}
</tr>
{% endfor %}
@@ -95,8 +106,17 @@
<div class="io-receipt-bar">
<label class="erp-field"><span>입고일 *</span><input type="date" name="receipt_date" value="{{ receipt_form.receipt_date }}" required /></label>
<label class="erp-field io-grow"><span>메모</span><input type="text" name="memo" value="{{ receipt_form.memo }}" maxlength="500" placeholder="차량·박스 수·검수 메모 등" /></label>
<div class="erp-field io-photo-field">
<span>입고증 사진 <small>(최대 {{ max_photos }}장)</small></span>
<label class="io-photo-pick">
<input type="file" name="photos" accept="image/*" multiple id="io-photo-input" class="io-photo-input" data-max="{{ max_photos }}" />
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></svg>
사진 고르기·찍기
</label>
</div>
<button type="button" class="erp-btn erp-btn-outline" id="io-fill-remaining">남은 수량 모두 채우기</button>
<button type="submit" class="erp-btn erp-btn-primary">입고 저장 <span id="io-recv-total"></span></button>
<div class="io-photo-previews" id="io-photo-previews" aria-live="polite"></div>
</div>
{% endif %}
</form>
@@ -106,17 +126,33 @@
{% 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>{% if perms.can_receive and not order.cancelled_at %}<th></th>{% endif %}</tr></thead>
<thead><tr><th>입고일</th><th>품목별 수량</th><th class="io-num">합계</th><th>입고증</th><th>입력</th>{% if photo_admin %}<th></th>{% endif %}</tr></thead>
<tbody>
{% for r in order.receipts %}
<tr>
<td>{{ r.receipt_date.strftime('%Y-%m-%d') }}{% if r.memo %}<div class="erp-row-sub">{{ r.memo }}</div>{% endif %}</td>
<td>{% for x in r.lines %}<span class="io-chip"><span class="io-code">{{ x.item_code }}</span> {{ n(x.qty) }}</span>{% endfor %}</td>
<td class="io-num">{{ n(r.total) }}</td>
<td class="io-photos-cell">
{% for ph in r.photos %}
<button type="button" class="io-thumb" data-photo="{{ ph.id }}" data-receipt="{{ r.id }}" data-type="{{ ph.content_type }}"
data-name="{{ ph.filename }}" title="{{ ph.filename }} — 크게 보기" aria-label="입고증 사진 크게 보기 {{ loop.index }}">
{% if ph.content_type == 'image/heic' %}<span class="io-thumb-heic">HEIC</span>{% else %}<img src="/inout/photos/{{ ph.id }}" alt="" loading="lazy" />{% endif %}
</button>
{% endfor %}
{% if photo_admin and r.photos|length < max_photos %}
<form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/photos" enctype="multipart/form-data" class="io-add-photo-form">
<label class="io-thumb io-thumb-add" title="입고증 사진 더하기">
<input type="file" name="photos" accept="image/*" multiple class="io-photo-input io-photo-auto" data-max="{{ max_photos - r.photos|length }}" aria-label="입고증 사진 더하기" />
<span aria-hidden="true">+</span>
</label>
</form>
{% elif not r.photos %}<span class="erp-muted">-</span>{% endif %}
</td>
<td class="erp-muted">{{ r.created_by }}<div class="erp-row-sub">{{ r.created_at.strftime('%Y-%m-%d %H:%M') }}</div></td>
{% if perms.can_receive and not order.cancelled_at %}
{% if photo_admin %}
<td><form method="post" action="/inout/orders/{{ order.id }}/receipts/{{ r.id }}/delete"
data-erp-confirm="{{ r.receipt_date.strftime('%Y-%m-%d') }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 됩니다.">
data-erp-confirm="{{ r.receipt_date.strftime('%Y-%m-%d') }} 입고 {{ n(r.total) }}개 기록을 지울까요? 그만큼 다시 미입고가 되고 입고증 사진도 지워집니다.">
<button type="submit" class="erp-btn erp-btn-outline erp-btn-sm">지우기</button></form></td>
{% endif %}
</tr>
@@ -128,6 +164,40 @@
<p class="erp-empty">아직 입고된 것이 없습니다.</p>
{% endif %}
</div>
{# 입고증 사진 크게 보기 — 앞뒤 넘기기(←/→), 원본 열기, 지우기(입고 담당) #}
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
<div class="io-viewer-bar">
<span class="io-viewer-title" id="io-viewer-title"></span>
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
</div>
<button type="button" class="io-viewer-nav is-prev" data-step="-1" aria-label="이전 사진">‹</button>
<img class="io-viewer-img" id="io-viewer-img" alt="입고증 사진" />
<p class="io-viewer-heic" id="io-viewer-heic" hidden>HEIC 사진은 이 브라우저에서 미리 볼 수 없습니다 — [원본]으로 내려받으세요.</p>
<button type="button" class="io-viewer-nav is-next" data-step="1" aria-label="다음 사진">›</button>
</dialog>
{% 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>
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016c" defer></script>{% endblock %}
@@ -1,5 +1,5 @@
{% extends "erp_base.html" %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016d" />{% endblock %}
{% block content %}
<section class="io">
@@ -76,4 +76,4 @@
</form>
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016c" defer></script>{% endblock %}
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import due, n %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016c" />{% endblock %}
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261016d" />{% endblock %}
{% block content %}
<section class="io">
@@ -88,4 +88,4 @@
{% endif %}
</section>
{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016b" defer></script>{% endblock %}
{% block scripts %}<script src="/static/inout.js?v=20261016c" defer></script>{% endblock %}
+70 -4
View File
@@ -124,7 +124,7 @@
.io-factory-who { display: block; font-size: 12px; color: var(--color-midtone-gray); margin-top: 2px; }
/* 옵션 팝업 */
.io-dlg { width: min(1040px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
.io-dlg { width: min(1180px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
border-radius: 12px; box-shadow: 0 12px 40px rgba(0, 0, 0, .2); color: var(--color-rich-black); overflow: hidden; }
.io-dlg[open] { display: flex; flex-direction: column; }
.io-dlg:focus { outline: none; }
@@ -158,9 +158,9 @@
color: var(--color-rich-black); background: #fff; }
.io-in:focus { outline: none; border-color: var(--color-rich-black); box-shadow: 0 0 0 3px rgba(0, 0, 0, .06); }
.io-in-num { text-align: right; }
.io-factory-table col.w-name { width: 18%; }
.io-factory-table col.w-man { width: 12%; }
.io-factory-table col.w-tel { width: 18%; }
.io-factory-table col.w-name { width: 15%; }
.io-factory-table col.w-man { width: 10%; }
.io-factory-table col.w-tel { width: 14%; }
.io-factory-table col.w-memo { width: auto; }
.io-factory-table col.w-sort { width: 64px; }
.io-factory-table col.w-use { width: 48px; }
@@ -180,3 +180,69 @@
.io-dlg-body { overflow-x: auto; }
.io-factory-table { min-width: 860px; }
}
/* ── 발주 메일(003) ── */
.io-mail-btn { display: inline-flex; align-items: center; gap: 6px; }
.io-mail-sent { color: #1e7a34; font-weight: 600; }
.io-mail-dlg { width: min(860px, calc(100vw - 40px)); }
.io-mail-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 14px; margin-bottom: 12px; }
.io-mail-fields label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--color-midtone-gray); }
.io-mail-fields input[readonly] { background: var(--color-ghost-gray); color: #3d3f42; }
.io-mail-sentlist { margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: #f3fbf5; border: 1px solid #cdeed6; font-size: 12.5px; }
.io-mail-sentlist ul { margin: 4px 0 0; padding-left: 18px; }
.io-mail-preview { width: 100%; height: 380px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; }
.io-mail-connect { padding: 8px 2px 4px; font-size: 13.5px; line-height: 1.7; }
.io-mail-connect .erp-btn { margin-top: 6px; }
.io-hint { margin: -4px 0 12px; font-size: 12.5px; color: #9a5b00; }
.io-dlg-footbar { display: flex; align-items: center; gap: 8px; padding: 12px 22px; border-top: 1px solid var(--color-subtle-ash); background: #fafbfc; }
.io-link-btn { border: 0; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--color-midtone-gray); text-decoration: underline; cursor: pointer; }
.io-link-btn:hover { color: var(--color-rich-black); }
/* ── 입고증 사진(003) ── */
.io-photo-field { min-width: 180px; }
.io-photo-pick { position: relative; display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border: 1px dashed #b7bcc4;
border-radius: 8px; background: #fff; color: var(--color-rich-black); font-size: 13px; cursor: pointer; white-space: nowrap; }
.io-photo-pick:hover { border-color: var(--color-rich-black); background: var(--color-ghost-gray); }
.io-photo-pick:focus-within { outline: 2px solid var(--color-rich-black); outline-offset: 2px; }
.io-photo-input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
.io-photo-previews { flex-basis: 100%; display: flex; flex-wrap: wrap; gap: 8px; }
.io-photo-previews:empty { display: none; }
.io-photo-chip { display: inline-flex; align-items: center; gap: 8px; padding: 4px 6px 4px 4px; border: 1px solid var(--color-subtle-ash);
border-radius: 8px; background: #fff; font-size: 12px; color: #3d3f42; max-width: 280px; }
.io-photo-chip img { width: 40px; height: 40px; object-fit: cover; border-radius: 6px; background: var(--color-ghost-gray); }
.io-photo-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.io-photo-chip button { border: 0; background: none; color: #6d6e6f; cursor: pointer; font-size: 13px; padding: 2px 4px; border-radius: 4px; }
.io-photo-chip button:hover { background: var(--color-ghost-gray); color: #c5221f; }
.io-photo-lost { margin: 0 0 8px; font-size: 12.5px; color: #7a1d14; font-weight: 600; }
.io-photos-cell { white-space: normal !important; min-width: 120px; }
.io-photos-cell .io-add-photo-form { display: inline-block; margin: 0; vertical-align: middle; }
.io-thumb { position: relative; display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; margin: 2px 4px 2px 0;
padding: 0; overflow: hidden; border: 1px solid var(--color-subtle-ash); border-radius: 6px; background: var(--color-ghost-gray); cursor: zoom-in; vertical-align: middle; }
.io-thumb img { width: 100%; height: 100%; object-fit: cover; }
.io-thumb:hover { border-color: var(--color-rich-black); }
.io-thumb-heic { font-size: 10px; font-weight: 700; color: #6d6e6f; }
.io-thumb-add { cursor: pointer; border-style: dashed; background: #fff; color: #6d6e6f; font-size: 20px; }
.io-thumb-add:hover { color: var(--color-rich-black); }
.io-viewer { width: min(1100px, calc(100vw - 40px)); height: min(860px, calc(100vh - 40px)); padding: 0; border: 0; border-radius: 12px;
background: #111; color: #fff; overflow: hidden; }
.io-viewer[open] { display: flex; align-items: center; justify-content: center; }
.io-viewer:focus { outline: none; }
.io-viewer::backdrop { background: rgba(0, 0, 0, .7); }
.io-viewer-bar { position: absolute; top: 0; left: 0; right: 0; display: flex; align-items: center; gap: 8px; padding: 10px 14px;
background: linear-gradient(rgba(0, 0, 0, .6), rgba(0, 0, 0, 0)); z-index: 1; }
.io-viewer-bar form { margin: 0; }
.io-viewer-title { flex: 1 1 auto; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.io-viewer-btn { padding: 5px 12px; border: 1px solid rgba(255, 255, 255, .35); border-radius: 6px; background: rgba(0, 0, 0, .35); color: #fff;
font: inherit; font-size: 12.5px; text-decoration: none; cursor: pointer; }
.io-viewer-btn:hover { background: rgba(255, 255, 255, .15); }
.io-viewer-img { max-width: 100%; max-height: 100%; object-fit: contain; }
.io-viewer-heic { padding: 24px; text-align: center; }
.io-viewer-nav { position: absolute; top: 50%; transform: translateY(-50%); width: 44px; height: 64px; border: 0; border-radius: 8px;
background: rgba(0, 0, 0, .45); color: #fff; font-size: 30px; cursor: pointer; z-index: 1; }
.io-viewer-nav:hover { background: rgba(255, 255, 255, .2); }
.io-viewer-nav.is-prev { left: 10px; }
.io-viewer-nav.is-next { right: 10px; }
.io-factory-table col.w-mail { width: 17%; }
@media (max-width: 900px) {
.io-mail-fields { grid-template-columns: 1fr; }
}
+230
View File
@@ -3,6 +3,8 @@
· 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운
· 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계
· 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리
· 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게)
· 발주 메일: 미리보기 팝업 → [메일 발송](발주 담당 본인 Gmail), 처음엔 [Gmail 연결]
· data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */
(function () {
"use strict";
@@ -307,4 +309,232 @@
});
if (btn.dataset.open === "1") open();
}
// ── 입고증 사진(003) — 브라우저에서 줄여(긴 변 2000px JPEG) 올린다. 못 줄이는 형식(HEIC 등)은 원본 그대로 ──
const PHOTO_MAX_SIDE = 2000;
async function shrinkPhoto(file) {
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) return file; // GIF(움직임)·HEIC 등은 그대로
try {
const bmp = await createImageBitmap(file);
const scale = Math.min(1, PHOTO_MAX_SIDE / Math.max(bmp.width, bmp.height));
if (scale === 1 && file.size < 1.5 * 1024 * 1024) { bmp.close && bmp.close(); return file; }
const cv = document.createElement("canvas");
cv.width = Math.round(bmp.width * scale);
cv.height = Math.round(bmp.height * scale);
cv.getContext("2d").drawImage(bmp, 0, 0, cv.width, cv.height);
bmp.close && bmp.close();
const blob = await new Promise(function (r) { cv.toBlob(r, "image/jpeg", 0.85); });
if (!blob || blob.size >= file.size) return file;
return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".jpg", { type: "image/jpeg", lastModified: file.lastModified });
} catch (_) { return file; }
}
async function prepare(input) {
const max = parseInt(input.dataset.max || "10", 10);
let files = Array.from(input._ioFiles || []).concat(Array.from(input.files || []));
if (files.length > max) {
alertMsg("입고증 사진은 " + max + "장까지 올릴 수 있습니다 — 앞의 " + max + "장만 넣습니다.");
files = files.slice(0, max);
}
input.disabled = true;
const done = [];
for (const f of files) done.push(f._ioShrunk ? f : Object.assign(await shrinkPhoto(f), { _ioShrunk: true }));
input.disabled = false;
setFiles(input, done);
return done;
}
function setFiles(input, files) {
input._ioFiles = files;
try {
const dt = new DataTransfer();
files.forEach(function (f) { dt.items.add(f); });
input.files = dt.files;
} catch (_) { /* 아주 옛 브라우저 — 고른 원본 그대로 올라간다 */ }
}
function paintPreviews(input, box) {
box.innerHTML = "";
(input._ioFiles || []).forEach(function (f, i) {
const chip = document.createElement("span");
chip.className = "io-photo-chip";
const img = document.createElement("img");
img.alt = "";
if (/^image\/(jpeg|png|webp|gif)$/i.test(f.type)) img.src = URL.createObjectURL(f);
chip.appendChild(img);
const meta = document.createElement("span");
meta.textContent = f.name + " · " + Math.max(1, Math.round(f.size / 1024)) + "KB";
chip.appendChild(meta);
const x = document.createElement("button");
x.type = "button";
x.textContent = "✕";
x.setAttribute("aria-label", f.name + " 빼기");
x.addEventListener("click", function () {
const left = input._ioFiles.filter(function (_f, k) { return k !== i; });
input.value = "";
setFiles(input, left);
paintPreviews(input, box);
});
chip.appendChild(x);
box.appendChild(chip);
});
}
document.addEventListener("change", async function (e) {
const input = e.target;
if (!input.classList || !input.classList.contains("io-photo-input")) return;
if (input.classList.contains("io-photo-auto")) { // 입고 기록 [+] — 고르면 바로 올림
input._ioFiles = [];
const files = await prepare(input);
if (files.length) input.form.submit();
return;
}
const fresh = Array.from(input.files || []);
input._ioFiles = (input._ioFiles || []).filter(function () { return true; });
input.value = "";
try { const dt = new DataTransfer(); fresh.forEach(function (f) { dt.items.add(f); }); input.files = dt.files; } catch (_) {}
await prepare(input);
const box = document.getElementById("io-photo-previews");
if (box) paintPreviews(input, box);
});
// ── 입고 저장 전 초과 확인(브라우저) — 서버까지 갔다 오면 고른 사진이 사라지므로 여기서 먼저 묻는다 ──
const recvForm2 = document.getElementById("io-receipt-form");
if (recvForm2) recvForm2.addEventListener("submit", function (e) {
const flag = document.getElementById("io-confirm-over");
if (!flag || flag.value === "1" || (e.submitter && e.submitter.name === "confirm_over")) return;
const overs = Array.from(recvForm2.querySelectorAll(".io-recv")).map(function (i) {
const after = num(i.dataset.received) + num(i.value);
return { code: i.dataset.code, name: i.dataset.name, ordered: num(i.dataset.ordered), after: after, add: num(i.value) };
}).filter(function (x) { return x.add && x.after > x.ordered; });
if (!overs.length) return;
e.preventDefault();
const lines = overs.map(function (x) { return x.code + " " + x.name + " — 발주 " + fmt(x.ordered) + "개, 입고 후 " + fmt(x.after) + "개(+" + fmt(x.after - x.ordered) + ")"; });
confirmMsg("발주보다 많이 입고하려고 합니다.\n\n" + lines.join("\n") + "\n\n초과 입고로 저장할까요?").then(function (ok) {
if (!ok) return;
flag.value = "1";
if (recvForm2.requestSubmit) recvForm2.requestSubmit(); else recvForm2.submit();
});
});
// ── 입고증 사진 크게 보기 ──
const viewer = document.getElementById("io-viewer");
if (viewer) {
const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic");
const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open");
const del = document.getElementById("io-viewer-del");
let list = [], at = 0;
function show(i) {
at = (i + list.length) % list.length;
const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic";
img.hidden = isHeic;
heic.hidden = !isHeic;
if (!isHeic) img.src = "/inout/photos/" + id;
openA.href = "/inout/photos/" + id;
title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")";
if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete";
viewer.querySelectorAll(".io-viewer-nav").forEach(function (n) { n.hidden = list.length < 2; });
}
document.addEventListener("click", function (e) {
const b = e.target.closest(".io-thumb[data-photo]");
if (!b) return;
list = Array.from(document.querySelectorAll('.io-thumb[data-receipt="' + b.dataset.receipt + '"][data-photo]'));
show(list.indexOf(b));
viewer.showModal();
viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음)
});
viewer.addEventListener("click", function (e) {
if (e.target === viewer || e.target.closest("[data-close]")) viewer.close();
const step = e.target.closest("[data-step]");
if (step) show(at + parseInt(step.dataset.step, 10));
});
viewer.addEventListener("keydown", function (e) {
if (e.key === "ArrowLeft") show(at - 1);
if (e.key === "ArrowRight") show(at + 1);
});
}
// ── 발주 메일(003) — 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ──
const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail");
if (mailBtn && mailDlg) initMail(mailBtn, mailDlg);
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 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; }
async function load() {
const res = await fetch(base, { headers: { Accept: "application/json" } });
data = await res.json();
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
if (!data.connected) {
foot.hidden = true;
body.innerHTML = '<div class="io-mail-connect">' +
"<p><b>발주 메일은 내 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></div>';
return;
}
foot.hidden = false;
const sentList = (data.sent || []).map(function (m) { return "<li>" + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "</li>"; }).join("");
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\" value=\"" + esc(data.subject) + "\" readonly /></label></div>" +
(data.to ? "" : '<p class="io-hint">' + esc(data.factory) + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.</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() {
say("");
sent = false;
if (!dlg.open) dlg.showModal();
dlg.focus({ preventScroll: true });
body.innerHTML = '<p class="erp-muted">불러오는 중…</p>';
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;
sendBtn.disabled = true;
say("보내는 중…");
try {
const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) });
const out = await res.json();
if (out.resend_needed) {
say("");
if (await confirmMsg(out.message)) return send(true);
return;
}
if (out.reconnect) { say(out.message, true); await load(); return; }
if (!res.ok || !out.ok) { say(out.message || out.detail || "보내지 못했습니다.", true); return; }
sent = true;
say(out.message);
await load();
} catch (_) {
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 () {
if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return;
await fetch("/inout/gmail/disconnect", { method: "POST" });
await load();
say("Gmail 연결을 끊었습니다.");
});
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");
url.searchParams.delete("msg");
if (sent) location.href = url.toString(); // 머리의 '발주 메일' 기록이 바뀌었다
else if (had) history.replaceState(null, "", url.toString());
});
if (btn.dataset.open === "1") open();
}
})();
+14
View File
@@ -287,6 +287,20 @@ curl -s http://127.0.0.1:8080/inout/health # {"status":"ok"} — DSN
그다음 ERP 관리자 화면에서 쓸 사람에게 **입출고 관리** 권한 → 입출고 관리 → 옵션에서 공장·발주 담당·입고 담당 지정.
백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`.
## 입출고 관리 발주 메일·입고증 사진 마이그레이션 (inout_db 003)
003은 공장 이메일 열, Gmail 연결(토큰 암호문)·발주 메일 기록·입고증 사진 표만 추가한다(다시 실행 가능, 기존 값 변경 없음).
미적용이어도 발주·입고는 그대로(사진·메일만 안내). 발주 메일은 **구글 클라우드 준비(관리자 1회)**가 필요하다 — `docs/INOUT_MODULE.md` 6-1:
Gmail API 사용 · OAuth 동의 화면에 `…/auth/gmail.send` 범위 · 로그인용 OAuth 클라이언트에 리디렉션 URI `{PUBLIC_BASE_URL}/inout/gmail/callback`.
새 환경변수 없음(`APP_ENCRYPTION_KEY`·`GOOGLE_CLIENT_ID/SECRET`·`PUBLIC_BASE_URL` 재사용).
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres inout_db > ~/inout_db_before_003_$(date +%Y%m%d%H%M).sql
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d inout_db < scripts/sql/inout_db_003_mail_photos.sql
grep -c "^APP_ENCRYPTION_KEY=" .env # 1 이어야 Gmail 연결 저장 가능
```
## 입출고 관리 공장 담당자 마이그레이션 (inout_db 002)
002는 `inout_factories.manager`(담당자) 열만 추가한다(다시 실행 가능). 예전 "담당자·연락처" 한 칸에 숫자 없이 이름만 있던 값은 담당자로 옮긴다.
+43 -2
View File
@@ -71,7 +71,10 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
| 표 | 내용 |
|---|---|
| `inout_factories` | 공장 — 이름(대소문자 무시 유일)·담당자(`manager`, 002)·연락처(`contact`)·메모·사용·순서 |
| `inout_factories` | 공장 — 이름(대소문자 무시 유일)·담당자(`manager`, 002)·연락처(`contact`)·이메일(`email`, 003)·메모·사용·순서 |
| `inout_gmail_tokens` | 사람별 Gmail 연결 — 갱신 토큰 **암호문**만(003) |
| `inout_order_mails` | 발주 메일 보낸 기록(003) |
| `inout_receipt_photos` | 입고증 사진(bytea, 003) |
| `inout_roles` | 담당자 — (email, role: order/receive) |
| `inout_orders` | 발주서 — 번호·공장·발주일·입고 예정일·메모·종결(시각·사람·사유)·취소 |
| `inout_order_lines` | 발주 품목 — 단품 코드·이름 사본·수량·줄 메모, 발주서 안에서 코드 유일 |
@@ -82,10 +85,48 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
002 미적용이어도 발주서 화면은 열리고(담당자 = `to_jsonb(f)->>'manager'`), 공장 저장만 "002 필요" 안내.
앱 계정 `inout_app` 은 SELECT/INSERT/UPDATE/DELETE + 시퀀스만. 초기화는 멱등(DROP·TRUNCATE 없음). 백업 권장: 매일 `pg_dump inout_db`.
## 6-1. 발주 메일 — 발주 담당자 본인 Gmail(2026-10-16, 마이그레이션 003)
- **받는 사람** = 옵션 → 공장 **이메일**(`inout_factories.email`, 여러 개는 쉼표). 발주서 화면에서 바꾸거나 참조를 더할 수 있다.
- **흐름**: 새 발주서를 저장하면 발주서 화면이 `?mail=1` 로 열려 **메일 미리보기 팝업**이 바로 뜬다(받는 사람·제목·본문).
사람이 **[메일 발송]**을 눌러야만 보낸다(자동 발송 없음). 머리 **[발주 메일 보내기 / 다시 보내기]**로 언제든 다시 연다.
- **본문**(`store.order_mail`) = 인사(공장 담당자 이름) · 발주번호·발주일·입고 예정일·품목 수·총수량·요청 사항(메모) 표 ·
품목 표(No·제품 코드·제품명·수량·비고, 합계) · 보낸 사람. HTML + 글 본문(둘 다), 값은 모두 escape. 제목 `[발주] {번호} · {공장} · {첫 품목} 외 n종`.
- **보내는 계정** = 누른 사람(발주 담당)의 Gmail — Gmail API `users.messages.send`(`gmail.py`).
사람마다 처음 한 번 **[Gmail 연결]**: 구글 동의 화면(로그인과 같은 OAuth 클라이언트, 범위 `openid email gmail.send` 만, `hd=` 회사 도메인,
`login_hint` = ERP 계정) → `/inout/gmail/callback` 에서 **고른 구글 계정 = ERP 로그인 계정**인지(다르면 거절), gmail.send 허락·갱신 토큰 확인 →
갱신 토큰을 `APP_ENCRYPTION_KEY`(실적 모듈과 같은 마스터 키, AES-256-GCM, AAD `inout:gmail:{email}`)로 암호화해 `inout_gmail_tokens`.
원문·접근 토큰은 저장·출력하지 않는다. 연결 끊기 = 구글 권한 취소(revoke) + 토큰 삭제.
- **기록**: `inout_order_mails`(보낸 사람·받는 사람·참조·제목·Gmail id·시각) — 머리 "발주 메일: 보냄 MM-DD HH:MM … · 모두 n번".
이미 보낸 발주서는 `resend: true` 를 같이 보내야 한다(409 → 화면이 "다시 보낼까요?" 확인) — 실수로 두 번 안 가게.
- **오류**: 구글이 연결을 끊었으면(invalid_grant·권한 없음) 토큰을 지우고 "다시 연결" 안내, Gmail API 꺼짐은 관리자 안내, 그 밖은 구글 문구.
- **권한**: 미리보기·발송·연결 = 발주 담당(관리자 포함). 취소된 발주서는 보낼 수 없다.
### 구글 클라우드 준비(관리자 1회 — 로그인에 쓰는 OAuth 클라이언트가 있는 프로젝트)
1. **API 및 서비스 → 라이브러리 → Gmail API → 사용**.
2. **OAuth 동의 화면 → 범위(데이터 액세스) → 범위 추가**: `https://www.googleapis.com/auth/gmail.send`
(사용자 유형이 **내부**(Workspace)면 구글 심사 없이 바로 쓸 수 있다).
3. **사용자 인증 정보 → 로그인용 OAuth 2.0 클라이언트 → 승인된 리디렉션 URI 추가**: `{PUBLIC_BASE_URL}/inout/gmail/callback`
(예: `https://dbx.no1king.freeddns.org/inout/gmail/callback`).
4. 서버 `.env` 에 `APP_ENCRYPTION_KEY`(실적 모듈과 같은 키)·`GOOGLE_CLIENT_ID/SECRET`·`PUBLIC_BASE_URL` 이 있어야 한다(새 변수 없음).
## 6-2. 입고증 사진(2026-10-16, 마이그레이션 003)
- 입고 담당이 **입고 저장 때** [사진 고르기·찍기](여러 장, 휴대폰은 카메라) — 브라우저가 긴 변 2000px JPEG 로 줄여 올린다
(4032×3024 7.9MB → 2000×1500 약 0.8MB, 줄인 게 더 크면 원본, HEIC·GIF 는 그대로). 입고 한 건에 **10장**, 한 장 **10MB**까지.
- 서버는 파일 머리로 종류를 판단(`store.sniff_image` — JPG·PNG·WEBP·GIF·HEIC, SVG·PDF 등 거절)하고 **입고와 한 트랜잭션**으로
`inout_receipt_photos`(bytea — 백업에 함께)에 넣는다 — 사진이 틀리면 입고도 저장 안 함, 초과 확인에 막혀도 사진 저장 안 함.
- 초과 입고는 **브라우저가 먼저 확인**한다(저장 전 확인 창 → `confirm_over=1`) — 서버 확인 화면으로 돌아가면 고른 파일이 사라지기 때문.
그래도 서버까지 가서 막히면(동시 입고 등) "사진은 다시 첨부" 안내.
- 입고 기록 **입고증** 칸 = 썸네일(누르면 크게 보기 — ←/→ 넘기기, [원본], [지우기](입고 담당)) + **[+]** 로 나중에 더하기.
입고 기록을 지우면 사진도 함께 지워진다(CASCADE).
- 보기 `GET /inout/photos/{id}` — 모듈 권한자, `X-Content-Type-Options: nosniff`·CSP sandbox, HEIC 는 내려받기(브라우저가 못 보여 줌).
## 7. 테스트
```bash
python -m pytest tests/test_inout_store.py tests/test_inout_web.py # DB 없이(등록·미설정 화면·상태·검사)
python -m pytest tests/test_inout_store.py tests/test_inout_mail_photo.py tests/test_inout_web.py # DB 없이(상태·검사·메일 본문·Gmail·사진)
INOUT_TEST_DB_URL=postgresql://inout_app:<pw>@127.0.0.1:5432/inout_db \
python -m pytest tests/test_inout_db.py tests/test_inout_web.py # 로컬 테스트 DB(초기화 SQL 적용, 앱 계정 — 권한도 확인)
```
+63
View File
@@ -0,0 +1,63 @@
-- =====================================================================
-- inout_db 마이그레이션 003 — 공장 이메일 · 발주 메일(Gmail) · 입고증 사진(2026-10-16)
-- =====================================================================
-- 멱등(idempotent). 열·표 추가만, 기존 값 변경·삭제 없음. 운영: /opt/www/main 에서 기존 inout_db 에 적용(백업 먼저).
--
-- 왜(사용자 요청):
-- ① 옵션에서 공장 담당자 이메일 입력 → 발주서를 저장한 뒤 발주 내용 요약을 발주 담당자 본인 Gmail 로 공장에 보낸다
-- (보내기는 사람이 [메일 발송]을 눌러야 함). Gmail 은 사람마다 한 번 [Gmail 연결](OAuth, gmail.send 범위만)
-- → 갱신 토큰을 APP_ENCRYPTION_KEY 로 암호화해 저장(원문은 DB 에 없음). 보낸 기록을 남긴다.
-- ② 입고 등록 때 공장이 보낸 입고증 사진 첨부 — 사진은 DB(bytea)에(백업에 함께 들어가고 디스크 정리가 없음).
-- 되돌리기: 백업에서 복원(새 표·열만 생기므로 남아 있어도 이전 앱은 동작).
-- =====================================================================
\set ON_ERROR_STOP on
BEGIN;
-- ① 공장 이메일(여러 개면 쉼표로)
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN inout_factories.email IS '발주 메일 받는 주소(여러 개는 쉼표)';
-- ② 사람별 Gmail 연결 — 갱신 토큰 암호문만(v{키버전}:… AES-256-GCM, AAD = inout:gmail:{email})
CREATE TABLE IF NOT EXISTS inout_gmail_tokens (
email TEXT PRIMARY KEY,
refresh_token_enc TEXT NOT NULL,
scopes TEXT NOT NULL DEFAULT '',
connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_used_at TIMESTAMPTZ NULL,
last_error TEXT NOT NULL DEFAULT ''
);
COMMENT ON TABLE inout_gmail_tokens IS '입출고 — 발주 메일 보낼 Gmail 연결(사람별, 토큰은 암호문)';
-- ③ 발주 메일 보낸 기록
CREATE TABLE IF NOT EXISTS inout_order_mails (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
sent_by TEXT NOT NULL,
to_addrs TEXT NOT NULL,
cc_addrs TEXT NOT NULL DEFAULT '',
subject TEXT NOT NULL,
gmail_id TEXT NOT NULL DEFAULT '',
sent_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_inout_order_mails_order ON inout_order_mails (order_id, sent_at);
COMMENT ON TABLE inout_order_mails IS '입출고 — 발주 메일 보낸 기록';
-- ④ 입고증 사진
CREATE TABLE IF NOT EXISTS inout_receipt_photos (
id BIGSERIAL PRIMARY KEY,
receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE,
filename TEXT NOT NULL DEFAULT '',
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
data BYTEA NOT NULL,
created_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_inout_receipt_photos_receipt ON inout_receipt_photos (receipt_id, id);
COMMENT ON TABLE inout_receipt_photos IS '입출고 — 입고증 사진(공장 → 물류)';
GRANT SELECT, INSERT, UPDATE, DELETE ON inout_gmail_tokens, inout_order_mails, inout_receipt_photos TO inout_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
COMMIT;
SELECT 'inout_db 003 mail photos ready' AS status;
+48 -1
View File
@@ -142,12 +142,59 @@ CREATE INDEX IF NOT EXISTS idx_inout_receipt_lines_line ON inout_receipt_lines (
COMMENT ON TABLE inout_receipts IS '입출고 — 물류 입고(한 번 들어온 것)';
COMMENT ON TABLE inout_receipt_lines IS '입출고 — 입고 품목별 수량';
-- ════════════════════════════════════════════════════════════
-- 5) 공장 이메일 · Gmail 연결 · 발주 메일 기록 · 입고증 사진 (= 마이그레이션 003, 새로 만들 때도 같게)
-- ════════════════════════════════════════════════════════════
-- ① 공장 이메일(여러 개면 쉼표로)
ALTER TABLE inout_factories ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN inout_factories.email IS '발주 메일 받는 주소(여러 개는 쉼표)';
-- ② 사람별 Gmail 연결 — 갱신 토큰 암호문만(v{키버전}:… AES-256-GCM, AAD = inout:gmail:{email})
CREATE TABLE IF NOT EXISTS inout_gmail_tokens (
email TEXT PRIMARY KEY,
refresh_token_enc TEXT NOT NULL,
scopes TEXT NOT NULL DEFAULT '',
connected_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_used_at TIMESTAMPTZ NULL,
last_error TEXT NOT NULL DEFAULT ''
);
COMMENT ON TABLE inout_gmail_tokens IS '입출고 — 발주 메일 보낼 Gmail 연결(사람별, 토큰은 암호문)';
-- ③ 발주 메일 보낸 기록
CREATE TABLE IF NOT EXISTS inout_order_mails (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES inout_orders(id) ON DELETE CASCADE,
sent_by TEXT NOT NULL,
to_addrs TEXT NOT NULL,
cc_addrs TEXT NOT NULL DEFAULT '',
subject TEXT NOT NULL,
gmail_id TEXT NOT NULL DEFAULT '',
sent_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_inout_order_mails_order ON inout_order_mails (order_id, sent_at);
COMMENT ON TABLE inout_order_mails IS '입출고 — 발주 메일 보낸 기록';
-- ④ 입고증 사진
CREATE TABLE IF NOT EXISTS inout_receipt_photos (
id BIGSERIAL PRIMARY KEY,
receipt_id BIGINT NOT NULL REFERENCES inout_receipts(id) ON DELETE CASCADE,
filename TEXT NOT NULL DEFAULT '',
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),
data BYTEA NOT NULL,
created_by TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_inout_receipt_photos_receipt ON inout_receipt_photos (receipt_id, id);
COMMENT ON TABLE inout_receipt_photos IS '입출고 — 입고증 사진(공장 → 물류)';
-- ════════════════════════════════════════════════════════════
-- 권한 — 앱 계정은 읽기·쓰기만(스키마 변경 없음)
-- ════════════════════════════════════════════════════════════
GRANT USAGE ON SCHEMA public TO inout_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON
inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines
inout_factories, inout_roles, inout_orders, inout_order_lines, inout_receipts, inout_receipt_lines,
inout_gmail_tokens, inout_order_mails, inout_receipt_photos
TO inout_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO inout_app;
+63
View File
@@ -163,6 +163,69 @@ class InoutDbTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "사용하지 않는 공장"):
self.order([("MT-M", 1)], factory_id=off)
# ── 003: 입고증 사진 · 공장 이메일 · Gmail 연결 · 메일 기록 ──
def test_receipt_photos_atomic_limit_delete(self):
from app.modules.inout import store
jpeg = b"\xff\xd8\xff\xe0" + b"1" * 100
o = self.order([("MT-P", 10)])
ids = self.line_ids(o["id"])
photos = store.validate_photos([("a.jpg", jpeg), ("b.jpg", jpeg)])
r = self.st.add_receipt(o["id"], {ids["MT-P"]: "4"}, receipt_date="2026-10-20", memo="", confirm_over=False,
by="w@x", photos=photos)
self.assertEqual(r["photos"], 2)
got = self.st.get_order(o["id"])
ph = got["receipts"][0]["photos"]
self.assertEqual([(p["filename"], p["content_type"], p["size_bytes"]) for p in ph], [("a.jpg", "image/jpeg", 104), ("b.jpg", "image/jpeg", 104)])
self.assertNotIn("data", ph[0]) # 목록엔 내용 없음
one = self.st.get_photo(ph[0]["id"])
self.assertEqual((bytes(one["data"]), one["order_id"]), (jpeg, o["id"]))
# 초과 확인 전에 막히면 사진도 저장 안 됨(한 트랜잭션)
from app.modules.inout.db import OverReceipt
with self.assertRaises(OverReceipt):
self.st.add_receipt(o["id"], {ids["MT-P"]: "99"}, receipt_date="2026-10-21", memo="", confirm_over=False, by="w@x",
photos=store.validate_photos([("c.jpg", jpeg)]))
self.assertEqual(sum(len(x["photos"]) for x in self.st.get_order(o["id"])["receipts"]), 2)
# 나중에 더하기 — 10장 한도는 이미 있는 장수와 합쳐서
rid = got["receipts"][0]["id"]
self.assertEqual(self.st.add_receipt_photos(o["id"], rid, [("d.jpg", jpeg)] * 8, by="w@x"), 8)
with self.assertRaisesRegex(ValueError, "10장"):
self.st.add_receipt_photos(o["id"], rid, [("e.jpg", jpeg)], by="w@x")
with self.assertRaisesRegex(ValueError, "찾을 수 없"):
self.st.add_receipt_photos(o["id"], 999999, [("e.jpg", jpeg)], by="w@x")
self.st.delete_receipt_photo(o["id"], ph[0]["id"])
self.assertIsNone(self.st.get_photo(ph[0]["id"]))
o2 = self.order([("MT-Q", 1)])
with self.assertRaisesRegex(ValueError, "찾을 수 없"): # 다른 발주서의 사진 id 로는 못 지운다
self.st.delete_receipt_photo(o2["id"], ph[1]["id"])
self.st.delete_receipt(o["id"], rid, by="w@x") # 입고를 지우면 사진도 함께
self.assertIsNone(self.st.get_photo(ph[1]["id"]))
def test_factory_email_gmail_tokens_and_mail_log(self):
fid = self.st.save_factory(factory_id=None, name=f"메일공장-{self.tag}", manager="박과장", email="a@x.com; b@y.co.kr")
f = next(x for x in self.st.list_factories() if x["id"] == fid)
self.assertEqual(f["email"], "a@x.com, b@y.co.kr")
with self.assertRaisesRegex(ValueError, "공장 이메일 형식"):
self.st.save_factory(factory_id=fid, name=f"메일공장-{self.tag}", email="not-an-email")
o = self.order([("MT-M", 3)], factory_id=fid)
self.assertEqual(self.st.get_order(o["id"])["factory_email"], "a@x.com, b@y.co.kr")
me = f"Buyer-{self.tag}@X.com"
self.assertIsNone(self.st.gmail_token(me))
self.st.save_gmail_token(me, refresh_token_enc="v1:enc1", scopes="openid email gmail.send")
self.st.save_gmail_token(me, refresh_token_enc="v1:enc2", scopes="openid email gmail.send") # 다시 연결 = 덮어씀
tok = self.st.gmail_token(me.upper())
self.assertEqual((tok["email"], tok["refresh_token_enc"]), (me.lower(), "v1:enc2"))
self.st.mark_gmail(me, error="Gmail 오류")
self.assertEqual(self.st.gmail_token(me)["last_error"], "Gmail 오류")
self.st.mark_gmail(me)
tok = self.st.gmail_token(me)
self.assertEqual(tok["last_error"], "")
self.assertIsNotNone(tok["last_used_at"])
self.st.add_order_mail(o["id"], sent_by=me, to=["a@x.com"], cc=["c@z.com"], subject="[발주] x", gmail_id="18f")
mails = self.st.get_order(o["id"])["mails"]
self.assertEqual([(m["to_addrs"], m["cc_addrs"], m["gmail_id"]) for m in mails], [("a@x.com", "c@z.com", "18f")])
self.st.delete_gmail_token(me)
self.assertIsNone(self.st.gmail_token(me))
if __name__ == "__main__":
unittest.main()
+158
View File
@@ -0,0 +1,158 @@
"""입출고 003 — 발주 메일(본문·받는 주소·Gmail 연결 검사·토큰·보내기)과 입고증 사진 검사. DB·구글 없이(가짜 구글 서버)."""
import base64
import email
import json
import unittest
from datetime import date
from email import policy
from unittest.mock import patch
import httpx
from app.modules.inout import gmail
from app.modules.inout import store as s
JPEG = b"\xff\xd8\xff\xe0" + b"0" * 64
PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 64
def _order(**over):
o = {"order_no": "PO-261016-01", "factory_name": "엘리화학", "factory_manager": "이석준", "order_date": date(2026, 10, 16),
"due_date": date(2026, 10, 30), "memo": "박스당 24개<포장>",
"lines": [{"item_code": "MT-0320", "item_name": "미라클 통 320ml", "qty": 5000, "memo": ""},
{"item_code": "MT-0500", "item_name": "<b>뚜껑</b>", "qty": 1200, "memo": "흰색"}]}
o.update(over)
return o
class MailContentTests(unittest.TestCase):
def test_parse_emails(self):
self.assertEqual(s.parse_emails("a@x.com, B@y.co.kr; a@X.com\nc@z.kr"), ["a@x.com", "B@y.co.kr", "c@z.kr"])
self.assertEqual(s.parse_emails(""), [])
for bad in ("abc", "a@b", "a@@b.com", "a b@c.com"):
with self.subTest(bad=bad), self.assertRaises(ValueError):
s.parse_emails(bad)
with self.assertRaisesRegex(ValueError, "입력하세요"):
s.parse_emails(" ", label="받는 사람", required=True)
with self.assertRaisesRegex(ValueError, "10개"):
s.parse_emails(",".join(f"u{i}@x.com" for i in range(11)))
def test_order_mail_summary_and_escaping(self):
m = s.order_mail(_order(), sender_name="King", sender_email="king@dbxcorp.co.kr")
self.assertEqual(m["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml 외 1종")
for part in ("이석준님, 안녕하세요.", "발주번호: PO-261016-01", "입고 예정일: 2026-10-30", "2종 · 총 6,200개",
"1. MT-0320 미라클 통 320ml — 5,000개", "(흰색)", "발주 담당: King (king@dbxcorp.co.kr)"):
self.assertIn(part, m["text"])
h = m["html"]
self.assertIn("&lt;b&gt;뚜껑&lt;/b&gt;", h) # 제품 이름·메모의 HTML 은 글자로
self.assertIn("박스당 24개&lt;포장&gt;", h)
self.assertNotIn("<b>뚜껑</b>", h)
self.assertIn("6,200", h) and self.assertIn("5,000", h)
m2 = s.order_mail(_order(due_date=None, factory_manager="", memo="", lines=_order()["lines"][:1]),
sender_name="", sender_email="k@x.com")
self.assertEqual(m2["subject"], "[발주] PO-261016-01 · 엘리화학 · 미라클 통 320ml")
self.assertIn("입고 예정일: 협의", m2["text"])
self.assertTrue(m2["text"].startswith("안녕하세요."))
self.assertNotIn("요청 사항", m2["text"])
def test_build_message_utf8_and_alternative(self):
raw = gmail.build_message(sender_name="킹", sender_email="king@dbxcorp.co.kr", to=["a@x.com", "b@y.com"], cc=["c@z.com"],
subject="[발주] 테스트 · 한글", text="본문", html="<p>본문</p>")
msg = email.message_from_bytes(raw, policy=policy.default)
self.assertEqual(msg["Subject"], "[발주] 테스트 · 한글")
self.assertEqual((msg["To"], msg["Cc"]), ("a@x.com, b@y.com", "c@z.com"))
self.assertIn("king@dbxcorp.co.kr", msg["From"])
self.assertEqual([p.get_content_type() for p in msg.iter_parts()], ["text/plain", "text/html"])
class PhotoTests(unittest.TestCase):
def test_sniff(self):
self.assertEqual(s.sniff_image(JPEG), "image/jpeg")
self.assertEqual(s.sniff_image(PNG), "image/png")
self.assertEqual(s.sniff_image(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp")
self.assertEqual(s.sniff_image(b"GIF89a..."), "image/gif")
self.assertEqual(s.sniff_image(b"\x00\x00\x00\x18ftypheic...."), "image/heic")
self.assertIsNone(s.sniff_image(b"%PDF-1.4"))
self.assertIsNone(s.sniff_image(b"<svg xmlns=...")) # SVG(스크립트 가능)는 받지 않는다
def test_validate(self):
out = s.validate_photos([("C:\\폰\\IMG_1.jpg", JPEG), ("empty.jpg", b""), ("b.png", PNG)])
self.assertEqual([(x["filename"], x["content_type"]) for x in out], [("IMG_1.jpg", "image/jpeg"), ("b.png", "image/png")])
with self.assertRaisesRegex(ValueError, "사진 파일"):
s.validate_photos([("x.pdf", b"%PDF-1.4")])
with self.assertRaisesRegex(ValueError, "너무 큽니다"):
s.validate_photos([("big.jpg", JPEG + b"0" * s.MAX_PHOTO_BYTES)])
with self.assertRaisesRegex(ValueError, "10장"):
s.validate_photos([("a.jpg", JPEG)] * 3, existing=8)
class GmailTests(unittest.TestCase):
def test_check_grant(self):
ok = {"userinfo": {"email": "King@dbxcorp.co.kr"}, "scope": f"openid email {gmail.GMAIL_SCOPE}", "refresh_token": "1//r"}
self.assertEqual(gmail.check_grant(ok, expected_email="king@dbxcorp.co.kr"), ("1//r", ok["scope"]))
with self.assertRaisesRegex(gmail.GmailError, "다른 구글 계정"):
gmail.check_grant({**ok, "userinfo": {"email": "me@gmail.com"}}, expected_email="king@dbxcorp.co.kr")
with self.assertRaisesRegex(gmail.GmailError, "gmail.send"):
gmail.check_grant({**ok, "scope": "openid email"}, expected_email="king@dbxcorp.co.kr")
with self.assertRaisesRegex(gmail.GmailError, "갱신 토큰"):
gmail.check_grant({**ok, "refresh_token": ""}, expected_email="king@dbxcorp.co.kr")
def test_token_encryption_roundtrip_and_aad(self):
env = {"APP_ENCRYPTION_KEY": "11" * 32, "APP_ENCRYPTION_KEY_VERSION": "1"}
with patch.dict("os.environ", env):
enc = gmail.encrypt_token("King@x.com", "1//refresh-secret")
self.assertNotIn("refresh-secret", enc)
self.assertEqual(gmail.decrypt_token("king@x.com", enc), "1//refresh-secret")
with self.assertRaises(gmail.GmailNotConnected): # 남의 이메일 이름으로는 못 푼다(AAD)
gmail.decrypt_token("other@x.com", enc)
with patch.dict("os.environ", {"APP_ENCRYPTION_KEY": ""}), self.assertRaisesRegex(gmail.GmailError, "암호화 키"):
gmail.encrypt_token("k@x.com", "r")
def _fake(self, handler):
return patch.object(gmail, "_http", lambda: httpx.Client(transport=httpx.MockTransport(handler)))
def test_send_refreshes_and_posts_raw(self):
seen = []
def handler(req):
seen.append(req)
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "ya29.A", "expires_in": 3600})
return httpx.Response(200, json={"id": "18f-msg", "threadId": "t"})
with self._fake(handler), patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "cid", "GOOGLE_CLIENT_SECRET": "sec"}.get(k, d)):
gid = gmail.send("1//r", b"Subject: x\r\n\r\nbody")
self.assertEqual(gid, "18f-msg")
form = dict(x.split("=", 1) for x in seen[0].content.decode().split("&"))
self.assertEqual((form["grant_type"], form["refresh_token"], form["client_id"]), ("refresh_token", "1%2F%2Fr", "cid"))
self.assertEqual(seen[1].headers["Authorization"], "Bearer ya29.A")
self.assertEqual(base64.urlsafe_b64decode(json.loads(seen[1].content)["raw"]), b"Subject: x\r\n\r\nbody")
def test_errors(self):
env = patch("app.main.env", side_effect=lambda k, d="": {"GOOGLE_CLIENT_ID": "c", "GOOGLE_CLIENT_SECRET": "s"}.get(k, d))
revoked = lambda req: httpx.Response(400, json={"error": "invalid_grant", "error_description": "Token has been expired or revoked."}) # noqa: E731
with self._fake(revoked), env, self.assertRaisesRegex(gmail.GmailNotConnected, "끊겼습니다"):
gmail.send("1//r", b"x")
def no_api(req):
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "a"})
return httpx.Response(403, json={"error": {"message": "Gmail API has not been used in project 1 before or it is disabled."}})
with self._fake(no_api), env, self.assertRaisesRegex(gmail.GmailError, "Gmail API 가 꺼져"):
gmail.send("1//r", b"x")
def scope(req):
if req.url.host == "oauth2.googleapis.com":
return httpx.Response(200, json={"access_token": "a"})
return httpx.Response(403, json={"error": {"message": "Request had insufficient authentication scopes."}})
with self._fake(scope), env, self.assertRaises(gmail.GmailNotConnected):
gmail.send("1//r", b"x")
def down(req):
raise httpx.ConnectError("x")
with self._fake(down), env, self.assertRaisesRegex(gmail.GmailError, "ConnectError"):
gmail.send("1//r", b"x")
if __name__ == "__main__":
unittest.main()
+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)