From 451b37955e72fca579d15e3585ac6a5fc25ed946 Mon Sep 17 00:00:00 2001 From: king Date: Fri, 16 Oct 2026 16:41:28 +0900 Subject: [PATCH] =?UTF-8?q?feat(inout):=20=EB=B0=9C=EC=A3=BC=20=EB=A9=94?= =?UTF-8?q?=EC=9D=BC(=EB=B0=9C=EC=A3=BC=20=EB=8B=B4=EB=8B=B9=20=EB=B3=B8?= =?UTF-8?q?=EC=9D=B8=20Gmail)=20=C2=B7=20=EA=B3=B5=EC=9E=A5=20=EC=9D=B4?= =?UTF-8?q?=EB=A9=94=EC=9D=BC=20=C2=B7=20=EC=9E=85=EA=B3=A0=EC=A6=9D=20?= =?UTF-8?q?=EC=82=AC=EC=A7=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- CLAUDE.md | 2 +- app/modules/inout/db.py | 139 ++++++++-- app/modules/inout/gmail.py | 186 ++++++++++++++ app/modules/inout/router.py | 237 +++++++++++++++++- app/modules/inout/store.py | 111 ++++++++ .../inout/templates/inout/_options_panel.html | 8 +- app/modules/inout/templates/inout/index.html | 4 +- .../inout/templates/inout/order_detail.html | 84 ++++++- .../inout/templates/inout/order_form.html | 4 +- .../inout/templates/inout/pending.html | 4 +- app/static/inout.css | 74 +++++- app/static/inout.js | 230 +++++++++++++++++ docs/DEPLOYMENT.md | 14 ++ docs/INOUT_MODULE.md | 45 +++- scripts/sql/inout_db_003_mail_photos.sql | 63 +++++ scripts/sql/inout_db_init.sql | 49 +++- tests/test_inout_db.py | 63 +++++ tests/test_inout_mail_photo.py | 158 ++++++++++++ tests/test_inout_web.py | 95 ++++++- 19 files changed, 1520 insertions(+), 50 deletions(-) create mode 100644 app/modules/inout/gmail.py create mode 100644 scripts/sql/inout_db_003_mail_photos.sql create mode 100644 tests/test_inout_mail_photo.py diff --git a/CLAUDE.md b/CLAUDE.md index dd59db4..fd3cdc8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py index 939f537..1858856 100644 --- a/app/modules/inout/db.py +++ b/app/modules/inout/db.py @@ -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건을 지운다(그 수량만큼 다시 미입고).""" diff --git a/app/modules/inout/gmail.py b/app/modules/inout/gmail.py new file mode 100644 index 0000000..f7a0002 --- /dev/null +++ b/app/modules/inout/gmail.py @@ -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()) diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py index 4a66d2c..1e209c0 100644 --- a/app/modules/inout/router.py +++ b/app/modules/inout/router.py @@ -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: diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py index f240f60..228e4d6 100644 --- a/app/modules/inout/store.py +++ b/app/modules/inout/store.py @@ -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'{e(k)}' + f'{e(str(v))}' for k, v in facts) + item_rows = "".join( + f'{i}{e(x["item_code"])}' + f'{e(x["item_name"])}{int(x["qty"]):,}' + f'{e(x.get("memo") or "")}' for i, x in enumerate(lines, start=1)) + html = ( + '
' + f"

{e(greet)}
아래와 같이 제품 제작을 발주합니다.

" + f'{fact_rows}
' + '' + f'' + f'{item_rows}' + f'' + f'
No제품 코드제품명수량비고
합계{total:,}
' + "

입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.

" + f'

발주 담당: {e(who)} ({e(sender_email)})

' + ) + 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 diff --git a/app/modules/inout/templates/inout/_options_panel.html b/app/modules/inout/templates/inout/_options_panel.html index fa1e0d0..6385167 100644 --- a/app/modules/inout/templates/inout/_options_panel.html +++ b/app/modules/inout/templates/inout/_options_panel.html @@ -33,12 +33,12 @@