// KJC 고객 A/S 접수 사이트 — CRM 화면(app.jsx)과 코드를 나누지 않는 단독 화면. // 서버 주소는 /api/portal (로컬 http://localhost:8030/, 운영은 이 폴더가 사이트의 /). const { useState, useEffect, useRef, useCallback } = React; const API = "/api/portal"; const TOKEN_KEY = "kjc_as_token"; const DRAFT_KEY = "kjc_as_draft"; const REPORTER_KEY = "kjc_as_reporter"; const NET_MSG = "연결이 원활하지 않습니다. 잠시 후 다시 시도해 주세요"; const MUST_CHANGE_MSG = "비밀번호를 먼저 변경해 주세요"; const BAD_PHOTO_MSG = "이 사진은 올릴 수 없습니다"; const PHOTO_MAX = 10; const PHOTO_LONG_SIDE = 1600; const PW_MIN = 8; const QTY_MAX = 9999; const FILTERS = [["all", "전체"], ["progress", "진행 중"], ["done", "완료·취소"]]; // ---- 브라우저 저장소 (사생활 보호 모드 등에서 막혀도 화면은 동작) ---- function readStore(kind, key) { try { return window[kind].getItem(key); } catch (e) { return null; } } function writeStore(kind, key, value) { try { if (value == null) window[kind].removeItem(key); else window[kind].setItem(key, value); } catch (e) { /* 저장 못 해도 화면은 계속 */ } } function readJson(kind, key) { const s = readStore(kind, key); if (!s) return null; try { return JSON.parse(s); } catch (e) { return null; } } // ---- 서버 호출 ---- // 401·403(비밀번호 변경 필요)은 App 이 받아 화면을 바꾼다 const authEvents = { onLost: null, onMustChange: null }; function apiError(status, message) { const e = new Error(message); e.status = status; return e; } async function api(path, opts = {}) { const { method = "GET", body, form, blob } = opts; const headers = {}; const token = readStore("localStorage", TOKEN_KEY); if (token) headers.Authorization = `Bearer ${token}`; let payload; if (form) payload = form; else if (body !== undefined) { headers["Content-Type"] = "application/json"; payload = JSON.stringify(body); } let res; try { res = await fetch(API + path, { method, headers, body: payload, cache: "no-store" }); } catch (e) { throw apiError(0, NET_MSG); } if (res.ok) { try { return blob ? await res.blob() : await res.json(); } catch (e) { throw apiError(0, NET_MSG); } } let detail = ""; try { const j = await res.json(); if (j && typeof j.detail === "string") detail = j.detail; } catch (e) { /* 본문이 JSON 이 아니면 아래 기본 문구 */ } if (res.status === 401 && path !== "/login") { if (authEvents.onLost) authEvents.onLost(detail); } else if (res.status === 403 && detail === MUST_CHANGE_MSG) { if (authEvents.onMustChange) authEvents.onMustChange(); } if (!detail) detail = res.status >= 502 ? NET_MSG : `요청을 처리하지 못했습니다 (오류 ${res.status})`; throw apiError(res.status, detail); } function uploadPhoto(caseId, blob, n) { const form = new FormData(); form.append("file", blob, `photo-${n}.jpg`); return api(`/cases/${caseId}/photos`, { method: "POST", form }); } function newClientKey() { try { if (window.crypto && typeof window.crypto.randomUUID === "function") return window.crypto.randomUUID(); } catch (e) { /* 아래 방식으로 */ } return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`; } // ---- 사진 줄이기 (긴 변 1600px, JPEG 0.8) ---- async function decodeImage(file) { if (typeof window.createImageBitmap === "function") { try { const bmp = await window.createImageBitmap(file); return { src: bmp, w: bmp.width, h: bmp.height, release: () => { if (bmp.close) bmp.close(); } }; } catch (e) { /* 아래 방식으로 다시 시도 */ } } const url = URL.createObjectURL(file); try { const img = await new Promise((resolve, reject) => { const im = new Image(); im.onload = () => resolve(im); im.onerror = () => reject(new Error("decode")); im.src = url; }); return { src: img, w: img.naturalWidth, h: img.naturalHeight, release: () => URL.revokeObjectURL(url) }; } catch (e) { URL.revokeObjectURL(url); throw e; } } async function shrinkImage(file) { const d = await decodeImage(file); const canvas = document.createElement("canvas"); try { if (!d.w || !d.h) throw new Error("size"); const scale = Math.min(1, PHOTO_LONG_SIDE / Math.max(d.w, d.h)); canvas.width = Math.max(1, Math.round(d.w * scale)); canvas.height = Math.max(1, Math.round(d.h * scale)); const ctx = canvas.getContext("2d"); if (!ctx) throw new Error("canvas"); ctx.fillStyle = "#ffffff"; // 투명 PNG 는 흰 바탕으로 ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(d.src, 0, 0, canvas.width, canvas.height); const out = await new Promise((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.8)); if (!out) throw new Error("encode"); return out; } finally { d.release(); canvas.width = 0; // 폰 메모리 반환 canvas.height = 0; } } // 고른 파일들을 줄인다: 10장 넘는 몫은 받지 않고, 줄이지 못한 파일은 이름을 모아 알린다 async function shrinkFiles(files, room) { const take = files.slice(0, Math.max(room, 0)); const over = files.length - take.length; const blobs = []; const bad = []; for (const f of take) { try { blobs.push(await shrinkImage(f)); } catch (e) { bad.push(f.name || "사진"); } } const notes = []; if (bad.length) notes.push({ kind: "warn", text: `${BAD_PHOTO_MSG} — ${bad.join(", ")}` }); if (over > 0) notes.push({ kind: "warn", text: `사진은 최대 ${PHOTO_MAX}장까지 올릴 수 있습니다. ${over}장은 넣지 않았습니다` }); return { blobs, notes }; } // ---- 화면 전환 (location.hash — 폰 뒤로 가기 동작) ---- function parseHash() { const h = (window.location.hash || "").replace(/^#/, ""); if (h === "/new") return { name: "new", key: "new" }; if (h === "/password") return { name: "password", key: "password" }; const m = h.match(/^\/case\/(\d+)$/); if (m) return { name: "case", id: Number(m[1]), key: `case:${m[1]}` }; return { name: "list", key: "list" }; } function go(hash, replace) { if (replace) window.location.replace(hash); else window.location.hash = hash; } function useRoute() { const [route, setRoute] = useState(parseHash); useEffect(() => { const on = () => setRoute(parseHash()); window.addEventListener("hashchange", on); return () => window.removeEventListener("hashchange", on); }, []); return route; } // 다음 화면에 넘길 안내 문구 (접수 완료 → 상세 등) let pendingFlash = null; function setFlash(target, items) { pendingFlash = { target, items }; } function takeFlash(target) { if (pendingFlash && pendingFlash.target === target) { const items = pendingFlash.items; pendingFlash = null; return items; } return []; } // ---- 공통 조각 ---- function Banner({ kind, children, action }) { return (
{children}
{action}
); } function Messages({ items }) { if (!items || !items.length) return null; return items.map((m, i) => {m.text}); } function Spinner() { return