feat(inout): 발주 메일(발주 담당 본인 Gmail) · 공장 이메일 · 입고증 사진

- inout_db 003: 공장 이메일, 사람별 Gmail 연결(갱신 토큰 암호문만), 발주 메일 기록, 입고증 사진(bytea). init 에도 같게.
- 발주 메일: 새 발주서 저장 → 미리보기 팝업(받는 사람 = 공장 이메일, 요약 표 HTML + 글 본문) → 사람이 [메일 발송]을
  눌러야 Gmail API(gmail.send)로 본인 Gmail 에서 발송. [Gmail 연결]은 사람마다 1회 — 고른 구글 계정 = ERP 계정 확인,
  APP_ENCRYPTION_KEY(AES-GCM, AAD inout:gmail:{email})로 암호화 저장. 보낸 기록, 재발송은 확인 후(resend),
  연결 끊김(invalid_grant)은 토큰 삭제 후 재연결 안내.
- 입고증 사진: 입고 저장 때 첨부(브라우저가 긴 변 2000px JPEG 로 줄임 — 7.9MB → 0.8MB), 10장·10MB, 파일 머리로 형식 검사,
  입고와 한 트랜잭션. 썸네일·크게 보기(←/→)·나중에 더하기·지우기, 보기는 nosniff·CSP sandbox. 초과 확인은 브라우저가 먼저(사진 유지).
- 테스트: 메일 본문·escape·받는 주소·Gmail 연결 검사·토큰 갱신/발송(가짜 구글)·암호화, 사진 검사, 실제 PostgreSQL 저장,
  실제 앱 흐름(사진 업로드·보기 헤더·권한, 메일 미리보기·연결·발송·재발송·끊김). 실제 브라우저로 팝업·사진·축소 확인.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 16:41:28 +09:00
parent 2ed275cd80
commit 451b37955e
19 changed files with 1520 additions and 50 deletions
+70 -4
View File
@@ -124,7 +124,7 @@
.io-factory-who { display: block; font-size: 12px; color: var(--color-midtone-gray); margin-top: 2px; }
/* 옵션 팝업 */
.io-dlg { width: min(1040px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
.io-dlg { width: min(1180px, calc(100vw - 40px)); max-height: min(760px, calc(100vh - 40px)); padding: 0; border: 1px solid var(--color-subtle-ash);
border-radius: 12px; box-shadow: 0 12px 40px rgba(0, 0, 0, .2); color: var(--color-rich-black); overflow: hidden; }
.io-dlg[open] { display: flex; flex-direction: column; }
.io-dlg:focus { outline: none; }
@@ -158,9 +158,9 @@
color: var(--color-rich-black); background: #fff; }
.io-in:focus { outline: none; border-color: var(--color-rich-black); box-shadow: 0 0 0 3px rgba(0, 0, 0, .06); }
.io-in-num { text-align: right; }
.io-factory-table col.w-name { width: 18%; }
.io-factory-table col.w-man { width: 12%; }
.io-factory-table col.w-tel { width: 18%; }
.io-factory-table col.w-name { width: 15%; }
.io-factory-table col.w-man { width: 10%; }
.io-factory-table col.w-tel { width: 14%; }
.io-factory-table col.w-memo { width: auto; }
.io-factory-table col.w-sort { width: 64px; }
.io-factory-table col.w-use { width: 48px; }
@@ -180,3 +180,69 @@
.io-dlg-body { overflow-x: auto; }
.io-factory-table { min-width: 860px; }
}
/* ── 발주 메일(003) ── */
.io-mail-btn { display: inline-flex; align-items: center; gap: 6px; }
.io-mail-sent { color: #1e7a34; font-weight: 600; }
.io-mail-dlg { width: min(860px, calc(100vw - 40px)); }
.io-mail-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 14px; margin-bottom: 12px; }
.io-mail-fields label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--color-midtone-gray); }
.io-mail-fields input[readonly] { background: var(--color-ghost-gray); color: #3d3f42; }
.io-mail-sentlist { margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: #f3fbf5; border: 1px solid #cdeed6; font-size: 12.5px; }
.io-mail-sentlist ul { margin: 4px 0 0; padding-left: 18px; }
.io-mail-preview { width: 100%; height: 380px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; }
.io-mail-connect { padding: 8px 2px 4px; font-size: 13.5px; line-height: 1.7; }
.io-mail-connect .erp-btn { margin-top: 6px; }
.io-hint { margin: -4px 0 12px; font-size: 12.5px; color: #9a5b00; }
.io-dlg-footbar { display: flex; align-items: center; gap: 8px; padding: 12px 22px; border-top: 1px solid var(--color-subtle-ash); background: #fafbfc; }
.io-link-btn { border: 0; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--color-midtone-gray); text-decoration: underline; cursor: pointer; }
.io-link-btn:hover { color: var(--color-rich-black); }
/* ── 입고증 사진(003) ── */
.io-photo-field { min-width: 180px; }
.io-photo-pick { position: relative; display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border: 1px dashed #b7bcc4;
border-radius: 8px; background: #fff; color: var(--color-rich-black); font-size: 13px; cursor: pointer; white-space: nowrap; }
.io-photo-pick:hover { border-color: var(--color-rich-black); background: var(--color-ghost-gray); }
.io-photo-pick:focus-within { outline: 2px solid var(--color-rich-black); outline-offset: 2px; }
.io-photo-input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
.io-photo-previews { flex-basis: 100%; display: flex; flex-wrap: wrap; gap: 8px; }
.io-photo-previews:empty { display: none; }
.io-photo-chip { display: inline-flex; align-items: center; gap: 8px; padding: 4px 6px 4px 4px; border: 1px solid var(--color-subtle-ash);
border-radius: 8px; background: #fff; font-size: 12px; color: #3d3f42; max-width: 280px; }
.io-photo-chip img { width: 40px; height: 40px; object-fit: cover; border-radius: 6px; background: var(--color-ghost-gray); }
.io-photo-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.io-photo-chip button { border: 0; background: none; color: #6d6e6f; cursor: pointer; font-size: 13px; padding: 2px 4px; border-radius: 4px; }
.io-photo-chip button:hover { background: var(--color-ghost-gray); color: #c5221f; }
.io-photo-lost { margin: 0 0 8px; font-size: 12.5px; color: #7a1d14; font-weight: 600; }
.io-photos-cell { white-space: normal !important; min-width: 120px; }
.io-photos-cell .io-add-photo-form { display: inline-block; margin: 0; vertical-align: middle; }
.io-thumb { position: relative; display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; margin: 2px 4px 2px 0;
padding: 0; overflow: hidden; border: 1px solid var(--color-subtle-ash); border-radius: 6px; background: var(--color-ghost-gray); cursor: zoom-in; vertical-align: middle; }
.io-thumb img { width: 100%; height: 100%; object-fit: cover; }
.io-thumb:hover { border-color: var(--color-rich-black); }
.io-thumb-heic { font-size: 10px; font-weight: 700; color: #6d6e6f; }
.io-thumb-add { cursor: pointer; border-style: dashed; background: #fff; color: #6d6e6f; font-size: 20px; }
.io-thumb-add:hover { color: var(--color-rich-black); }
.io-viewer { width: min(1100px, calc(100vw - 40px)); height: min(860px, calc(100vh - 40px)); padding: 0; border: 0; border-radius: 12px;
background: #111; color: #fff; overflow: hidden; }
.io-viewer[open] { display: flex; align-items: center; justify-content: center; }
.io-viewer:focus { outline: none; }
.io-viewer::backdrop { background: rgba(0, 0, 0, .7); }
.io-viewer-bar { position: absolute; top: 0; left: 0; right: 0; display: flex; align-items: center; gap: 8px; padding: 10px 14px;
background: linear-gradient(rgba(0, 0, 0, .6), rgba(0, 0, 0, 0)); z-index: 1; }
.io-viewer-bar form { margin: 0; }
.io-viewer-title { flex: 1 1 auto; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.io-viewer-btn { padding: 5px 12px; border: 1px solid rgba(255, 255, 255, .35); border-radius: 6px; background: rgba(0, 0, 0, .35); color: #fff;
font: inherit; font-size: 12.5px; text-decoration: none; cursor: pointer; }
.io-viewer-btn:hover { background: rgba(255, 255, 255, .15); }
.io-viewer-img { max-width: 100%; max-height: 100%; object-fit: contain; }
.io-viewer-heic { padding: 24px; text-align: center; }
.io-viewer-nav { position: absolute; top: 50%; transform: translateY(-50%); width: 44px; height: 64px; border: 0; border-radius: 8px;
background: rgba(0, 0, 0, .45); color: #fff; font-size: 30px; cursor: pointer; z-index: 1; }
.io-viewer-nav:hover { background: rgba(255, 255, 255, .2); }
.io-viewer-nav.is-prev { left: 10px; }
.io-viewer-nav.is-next { right: 10px; }
.io-factory-table col.w-mail { width: 17%; }
@media (max-width: 900px) {
.io-mail-fields { grid-template-columns: 1fr; }
}
+230
View File
@@ -3,6 +3,8 @@
· 발주서 폼: 제품 줄 추가·지우기·번호·합계, 코드표 단품 검색(GET /inout/api/items?q=) 드롭다운
· 발주서 화면: [남은 수량 모두 채우기], 이번 입고 합계
· 옵션 팝업(톱니): 담당자·공장 — 열 때 내용을 받고, 저장은 제자리
· 입고증 사진: 브라우저에서 줄여 올리기·미리보기·크게 보기, 입고 저장 전 초과 확인(사진이 사라지지 않게)
· 발주 메일: 미리보기 팝업 → [메일 발송](발주 담당 본인 Gmail), 처음엔 [Gmail 연결]
· data-erp-confirm-btn: 버튼별 확인(formaction 이 있는 버튼 — 공용 data-erp-confirm 은 form.submit() 이라 누른 버튼이 사라짐) */
(function () {
"use strict";
@@ -307,4 +309,232 @@
});
if (btn.dataset.open === "1") open();
}
// ── 입고증 사진(003) — 브라우저에서 줄여(긴 변 2000px JPEG) 올린다. 못 줄이는 형식(HEIC 등)은 원본 그대로 ──
const PHOTO_MAX_SIDE = 2000;
async function shrinkPhoto(file) {
if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) return file; // GIF(움직임)·HEIC 등은 그대로
try {
const bmp = await createImageBitmap(file);
const scale = Math.min(1, PHOTO_MAX_SIDE / Math.max(bmp.width, bmp.height));
if (scale === 1 && file.size < 1.5 * 1024 * 1024) { bmp.close && bmp.close(); return file; }
const cv = document.createElement("canvas");
cv.width = Math.round(bmp.width * scale);
cv.height = Math.round(bmp.height * scale);
cv.getContext("2d").drawImage(bmp, 0, 0, cv.width, cv.height);
bmp.close && bmp.close();
const blob = await new Promise(function (r) { cv.toBlob(r, "image/jpeg", 0.85); });
if (!blob || blob.size >= file.size) return file;
return new File([blob], file.name.replace(/\.[^.]+$/, "") + ".jpg", { type: "image/jpeg", lastModified: file.lastModified });
} catch (_) { return file; }
}
async function prepare(input) {
const max = parseInt(input.dataset.max || "10", 10);
let files = Array.from(input._ioFiles || []).concat(Array.from(input.files || []));
if (files.length > max) {
alertMsg("입고증 사진은 " + max + "장까지 올릴 수 있습니다 — 앞의 " + max + "장만 넣습니다.");
files = files.slice(0, max);
}
input.disabled = true;
const done = [];
for (const f of files) done.push(f._ioShrunk ? f : Object.assign(await shrinkPhoto(f), { _ioShrunk: true }));
input.disabled = false;
setFiles(input, done);
return done;
}
function setFiles(input, files) {
input._ioFiles = files;
try {
const dt = new DataTransfer();
files.forEach(function (f) { dt.items.add(f); });
input.files = dt.files;
} catch (_) { /* 아주 옛 브라우저 — 고른 원본 그대로 올라간다 */ }
}
function paintPreviews(input, box) {
box.innerHTML = "";
(input._ioFiles || []).forEach(function (f, i) {
const chip = document.createElement("span");
chip.className = "io-photo-chip";
const img = document.createElement("img");
img.alt = "";
if (/^image\/(jpeg|png|webp|gif)$/i.test(f.type)) img.src = URL.createObjectURL(f);
chip.appendChild(img);
const meta = document.createElement("span");
meta.textContent = f.name + " · " + Math.max(1, Math.round(f.size / 1024)) + "KB";
chip.appendChild(meta);
const x = document.createElement("button");
x.type = "button";
x.textContent = "✕";
x.setAttribute("aria-label", f.name + " 빼기");
x.addEventListener("click", function () {
const left = input._ioFiles.filter(function (_f, k) { return k !== i; });
input.value = "";
setFiles(input, left);
paintPreviews(input, box);
});
chip.appendChild(x);
box.appendChild(chip);
});
}
document.addEventListener("change", async function (e) {
const input = e.target;
if (!input.classList || !input.classList.contains("io-photo-input")) return;
if (input.classList.contains("io-photo-auto")) { // 입고 기록 [+] — 고르면 바로 올림
input._ioFiles = [];
const files = await prepare(input);
if (files.length) input.form.submit();
return;
}
const fresh = Array.from(input.files || []);
input._ioFiles = (input._ioFiles || []).filter(function () { return true; });
input.value = "";
try { const dt = new DataTransfer(); fresh.forEach(function (f) { dt.items.add(f); }); input.files = dt.files; } catch (_) {}
await prepare(input);
const box = document.getElementById("io-photo-previews");
if (box) paintPreviews(input, box);
});
// ── 입고 저장 전 초과 확인(브라우저) — 서버까지 갔다 오면 고른 사진이 사라지므로 여기서 먼저 묻는다 ──
const recvForm2 = document.getElementById("io-receipt-form");
if (recvForm2) recvForm2.addEventListener("submit", function (e) {
const flag = document.getElementById("io-confirm-over");
if (!flag || flag.value === "1" || (e.submitter && e.submitter.name === "confirm_over")) return;
const overs = Array.from(recvForm2.querySelectorAll(".io-recv")).map(function (i) {
const after = num(i.dataset.received) + num(i.value);
return { code: i.dataset.code, name: i.dataset.name, ordered: num(i.dataset.ordered), after: after, add: num(i.value) };
}).filter(function (x) { return x.add && x.after > x.ordered; });
if (!overs.length) return;
e.preventDefault();
const lines = overs.map(function (x) { return x.code + " " + x.name + " — 발주 " + fmt(x.ordered) + "개, 입고 후 " + fmt(x.after) + "개(+" + fmt(x.after - x.ordered) + ")"; });
confirmMsg("발주보다 많이 입고하려고 합니다.\n\n" + lines.join("\n") + "\n\n초과 입고로 저장할까요?").then(function (ok) {
if (!ok) return;
flag.value = "1";
if (recvForm2.requestSubmit) recvForm2.requestSubmit(); else recvForm2.submit();
});
});
// ── 입고증 사진 크게 보기 ──
const viewer = document.getElementById("io-viewer");
if (viewer) {
const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic");
const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open");
const del = document.getElementById("io-viewer-del");
let list = [], at = 0;
function show(i) {
at = (i + list.length) % list.length;
const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic";
img.hidden = isHeic;
heic.hidden = !isHeic;
if (!isHeic) img.src = "/inout/photos/" + id;
openA.href = "/inout/photos/" + id;
title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")";
if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete";
viewer.querySelectorAll(".io-viewer-nav").forEach(function (n) { n.hidden = list.length < 2; });
}
document.addEventListener("click", function (e) {
const b = e.target.closest(".io-thumb[data-photo]");
if (!b) return;
list = Array.from(document.querySelectorAll('.io-thumb[data-receipt="' + b.dataset.receipt + '"][data-photo]'));
show(list.indexOf(b));
viewer.showModal();
viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음)
});
viewer.addEventListener("click", function (e) {
if (e.target === viewer || e.target.closest("[data-close]")) viewer.close();
const step = e.target.closest("[data-step]");
if (step) show(at + parseInt(step.dataset.step, 10));
});
viewer.addEventListener("keydown", function (e) {
if (e.key === "ArrowLeft") show(at - 1);
if (e.key === "ArrowRight") show(at + 1);
});
}
// ── 발주 메일(003) — 미리보기를 받아 보여 주고, [메일 발송]을 눌러야 보낸다 ──
const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail");
if (mailBtn && mailDlg) initMail(mailBtn, mailDlg);
function initMail(btn, dlg) {
const body = document.getElementById("io-mail-body"), foot = document.getElementById("io-mail-foot");
const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = document.getElementById("io-mail-send");
const base = "/inout/orders/" + btn.dataset.order + "/mail";
let data = null, sent = false;
function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); }
function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }
async function load() {
const res = await fetch(base, { headers: { Accept: "application/json" } });
data = await res.json();
if (!res.ok) throw new Error(data.detail || "HTTP " + res.status);
if (!data.connected) {
foot.hidden = true;
body.innerHTML = '<div class="io-mail-connect">' +
"<p><b>발주 메일은 내 Gmail(" + esc(data.from) + ")로 보냅니다.</b> 처음 한 번만 Gmail 연결이 필요합니다.</p>" +
"<p class=\"erp-muted\">구글 화면에서 <b>같은 계정</b>을 고르고 '메일 보내기' 권한을 허락하세요. 보내기 권한만 받으며, 메일함은 읽지 않습니다.</p>" +
(data.configured ? "" : '<p class="io-error">서버 설정(APP_ENCRYPTION_KEY·구글 OAuth)이 없어 연결할 수 없습니다 — 관리자에게 알려 주세요.</p>') +
'<a class="erp-btn erp-btn-primary" href="' + esc(data.connect_url) + '">Gmail 연결</a></div>';
return;
}
foot.hidden = false;
const sentList = (data.sent || []).map(function (m) { return "<li>" + esc(m.at) + " · " + esc(m.by) + " → " + esc(m.to) + "</li>"; }).join("");
body.innerHTML =
'<div class="io-mail-fields">' +
"<label><span>보내는 사람</span><input class=\"io-in\" value=\"" + esc(data.from) + "\" readonly /></label>" +
"<label><span>받는 사람 *</span><input class=\"io-in\" id=\"io-mail-to\" value=\"" + esc(data.to) + "\" placeholder=\"공장 이메일 — 옵션에서 넣어 두면 자동\" /></label>" +
"<label><span>참조</span><input class=\"io-in\" id=\"io-mail-cc\" placeholder=\"여러 개는 쉼표로\" /></label>" +
"<label><span>제목</span><input class=\"io-in\" value=\"" + esc(data.subject) + "\" readonly /></label></div>" +
(data.to ? "" : '<p class="io-hint">' + esc(data.factory) + " 이메일이 옵션에 없습니다 — 받는 사람을 직접 넣거나, 관리자가 옵션 → 공장에 넣어 두세요.</p>") +
(sentList ? '<div class="io-mail-sentlist"><b>보낸 기록</b><ul>' + sentList + "</ul></div>" : "") +
'<iframe class="io-mail-preview" sandbox title="메일 본문 미리보기"></iframe>';
body.querySelector(".io-mail-preview").srcdoc = data.html;
sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송";
}
async function open() {
say("");
sent = false;
if (!dlg.open) dlg.showModal();
dlg.focus({ preventScroll: true });
body.innerHTML = '<p class="erp-muted">불러오는 중…</p>';
try { await load(); } catch (err) { body.innerHTML = '<p class="io-error">' + esc(err.message) + "</p>"; foot.hidden = true; }
}
async function send(resend) {
const to = document.getElementById("io-mail-to").value, cc = document.getElementById("io-mail-cc").value;
sendBtn.disabled = true;
say("보내는 중…");
try {
const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) });
const out = await res.json();
if (out.resend_needed) {
say("");
if (await confirmMsg(out.message)) return send(true);
return;
}
if (out.reconnect) { say(out.message, true); await load(); return; }
if (!res.ok || !out.ok) { say(out.message || out.detail || "보내지 못했습니다.", true); return; }
sent = true;
say(out.message);
await load();
} catch (_) {
say("보내지 못했습니다(연결 오류). 다시 눌러 주세요.", true);
} finally { sendBtn.disabled = false; }
}
btn.addEventListener("click", open);
sendBtn.addEventListener("click", function () { send(false); });
document.getElementById("io-gmail-disconnect").addEventListener("click", async function () {
if (!(await confirmMsg("Gmail 연결을 끊을까요? 다음에 보낼 때 다시 연결해야 합니다."))) return;
await fetch("/inout/gmail/disconnect", { method: "POST" });
await load();
say("Gmail 연결을 끊었습니다.");
});
dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); });
dlg.addEventListener("close", function () {
const url = new URL(location.href);
const had = url.searchParams.has("mail");
url.searchParams.delete("mail");
url.searchParams.delete("msg");
if (sent) location.href = url.toString(); // 머리의 '발주 메일' 기록이 바뀌었다
else if (had) history.replaceState(null, "", url.toString());
});
if (btn.dataset.open === "1") open();
}
})();