diff --git a/app/modules/inout/CLAUDE.md b/app/modules/inout/CLAUDE.md
index 1344ab7..833cccb 100644
--- a/app/modules/inout/CLAUDE.md
+++ b/app/modules/inout/CLAUDE.md
@@ -56,6 +56,8 @@
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
+- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
+ 사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
## 상품 정보 (004, 옵션 세 번째 탭)
diff --git a/app/modules/inout/db.py b/app/modules/inout/db.py
index 79868b9..0e5a25e 100644
--- a/app/modules/inout/db.py
+++ b/app/modules/inout/db.py
@@ -432,6 +432,19 @@ class InoutDBStore:
if not row:
raise ValueError("사진을 찾을 수 없습니다.")
+ def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
+ """저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
+ with self._pool.connection() as conn, conn.transaction():
+ head = self._lock_order(conn, order_id)
+ if head["cancelled_at"]:
+ raise ValueError("취소된 발주서입니다.")
+ row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
+ "WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
+ if not row:
+ raise ValueError("사진을 찾을 수 없습니다.")
+ data = store.rotate_image(bytes(row["data"]), degrees)
+ conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
+
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
"""사진 내용(+ 발주서 id) — 보여 주기용."""
try:
diff --git a/app/modules/inout/router.py b/app/modules/inout/router.py
index e482e83..81f9b55 100644
--- a/app/modules/inout/router.py
+++ b/app/modules/inout/router.py
@@ -11,7 +11,7 @@
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
- POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
+ POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete|rotate · GET /inout/photos/{pid} 입고증 사진
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
@@ -486,7 +486,7 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
_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",
+ "Cache-Control": "private, no-cache",
}
@@ -530,6 +530,21 @@ def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
+@router.post("/orders/{order_id}/photos/{photo_id}/rotate")
+def receipt_photo_rotate(request: Request, order_id: int, photo_id: int, degrees: int = Query(...)) -> Any:
+ """크게 보기 창의 회전 버튼 — 창을 닫지 않게 JSON 으로 답한다(화면이 사진을 다시 받아 그림)."""
+ got = _ctx(request)
+ if not isinstance(got, tuple):
+ return got
+ st, user = got
+ _require(st, user, "receive")
+ try:
+ st.rotate_receipt_photo(order_id, photo_id, degrees)
+ except (ValueError, LookupError) as exc:
+ return JSONResponse({"error": str(exc)}, status_code=400)
+ return JSONResponse({"ok": True})
+
+
@router.get("/photos/{photo_id}")
def photo_view(request: Request, photo_id: int) -> Response:
_user(request)
@@ -537,12 +552,18 @@ def photo_view(request: Request, photo_id: int) -> Response:
row = st.get_photo(photo_id) if st is not None else None
if row is None:
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
+ from hashlib import md5 # noqa: WPS433
from urllib.parse import quote # noqa: WPS433
+ data = bytes(row["data"])
+ # 돌린 사진이 하루 동안 예전 모습으로 남지 않게 — 브라우저가 매번 내용이 같은지 묻는다(no-cache + ETag)
+ etag = '"' + md5(data, usedforsecurity=False).hexdigest() + '"'
+ if request.headers.get("if-none-match") == etag:
+ return Response(status_code=304, headers={"ETag": etag, "Cache-Control": _PHOTO_HEADERS["Cache-Control"]})
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}"})
+ return Response(content=data, media_type=row["content_type"],
+ headers={**_PHOTO_HEADERS, "ETag": etag, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
# ────────────────────────────────────────────────────────────
diff --git a/app/modules/inout/store.py b/app/modules/inout/store.py
index 14989da..54c33c9 100644
--- a/app/modules/inout/store.py
+++ b/app/modules/inout/store.py
@@ -700,6 +700,41 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
return out
+def rotate_image(data: bytes, degrees: int) -> bytes:
+ """사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
+ from io import BytesIO # noqa: WPS433
+
+ from PIL import Image, ImageOps # noqa: WPS433
+
+ if degrees not in (90, 270):
+ raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
+ kind = sniff_image(data)
+ if kind == "image/heic":
+ raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
+ try:
+ im = Image.open(BytesIO(data))
+ if getattr(im, "n_frames", 1) > 1:
+ raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
+ icc = im.info.get("icc_profile")
+ im = ImageOps.exif_transpose(im)
+ # PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
+ im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
+ fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
+ opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
+ if fmt in ("JPEG", "WEBP"):
+ opts["quality"] = 92
+ buf = BytesIO()
+ im.save(buf, format=fmt, **opts)
+ except ValueError:
+ raise
+ except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
+ raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
+ out = buf.getvalue()
+ if len(out) > MAX_PHOTO_BYTES:
+ raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
+ return out
+
+
# ════════════════════════════════════════════════════════════
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
diff --git a/app/modules/inout/templates/inout/index.html b/app/modules/inout/templates/inout/index.html
index 002f538..ec20dc1 100644
--- a/app/modules/inout/templates/inout/index.html
+++ b/app/modules/inout/templates/inout/index.html
@@ -1,6 +1,6 @@
{% extends "erp_base.html" %}
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{% block content %}
{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
@@ -71,4 +71,4 @@
{% include "inout/_calendar.html" %}
{% endblock %}
-{% block scripts %}{% endblock %}
+{% block scripts %}{% endblock %}
diff --git a/app/modules/inout/templates/inout/order_detail.html b/app/modules/inout/templates/inout/order_detail.html
index 9f3ad06..9f1045d 100644
--- a/app/modules/inout/templates/inout/order_detail.html
+++ b/app/modules/inout/templates/inout/order_detail.html
@@ -20,7 +20,7 @@
{%- endmacro -%}
-{% block head_extra %}{% endblock %}
+{% block head_extra %}{% endblock %}
{% block content %}
{% set active = order.status in ('open', 'partial') %}
@@ -232,6 +232,10 @@