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:
+124
-15
@@ -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건을 지운다(그 수량만큼 다시 미입고)."""
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 %}
|
||||
|
||||
Reference in New Issue
Block a user