feat(pop): add COMPANY_7 POP foundation (shell, layout, inbound, outbound, main)

이전 세션 작업물 일괄 커밋. POP.md 2~6차 로그 기록 내용.
3cd3eed7(공정실행 이식) 커밋의 선행 의존성.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
kmh
2026-04-20 16:55:35 +09:00
parent 3cd3eed71d
commit f01dde1132
54 changed files with 18910 additions and 0 deletions
@@ -0,0 +1,420 @@
"use client";
import React, { useState, useRef, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { Camera, CameraOff, CheckCircle2, AlertCircle, Scan } from "lucide-react";
import Webcam from "react-webcam";
import { BrowserMultiFormatReader, NotFoundException } from "@zxing/library";
export interface BarcodeScanModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
targetField?: string;
barcodeFormat?: "all" | "1d" | "2d";
autoSubmit?: boolean;
onScanSuccess: (barcode: string) => void;
userId?: string;
}
export const BarcodeScanModal: React.FC<BarcodeScanModalProps> = ({
open,
onOpenChange,
targetField,
barcodeFormat = "all",
autoSubmit = false,
onScanSuccess,
userId = "guest",
}) => {
const [isScanning, setIsScanning] = useState(false);
const [scannedCode, setScannedCode] = useState<string>("");
const [manualInput, setManualInput] = useState<string>("");
const [error, setError] = useState<string>("");
const [hasPermission, setHasPermission] = useState<boolean | null>(null);
const webcamRef = useRef<Webcam>(null);
const codeReaderRef = useRef<BrowserMultiFormatReader | null>(null);
const scanIntervalRef = useRef<NodeJS.Timeout | null>(null);
const manualInputRef = useRef<HTMLInputElement>(null);
// 바코드 리더 초기화 + 모달 열릴 때 상태 리셋
useEffect(() => {
if (open) {
setScannedCode("");
setManualInput("");
setError("");
setIsScanning(false);
setHasPermission(null);
codeReaderRef.current = new BrowserMultiFormatReader();
}
return () => {
stopScanning();
if (codeReaderRef.current) {
codeReaderRef.current.reset();
}
};
}, [open]);
// 카메라 권한 요청
const requestCameraPermission = async () => {
// navigator.mediaDevices 지원 확인
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
setHasPermission(false);
setError(
"이 브라우저는 카메라 접근을 지원하지 않거나, 보안 컨텍스트(HTTPS 또는 localhost)가 아닙니다. " +
"현재 프로토콜: " + window.location.protocol
);
toast.error("카메라 접근이 불가능합니다.");
return;
}
try {
// 후면 카메라 먼저 시도, 실패하면 전면 카메라 fallback
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
} catch {
stream = await navigator.mediaDevices.getUserMedia({ video: true });
}
setHasPermission(true);
stream.getTracks().forEach((track) => track.stop());
} catch (err: any) {
setHasPermission(false);
if (err.name === "NotAllowedError") {
setError("카메라 접근이 거부되었습니다. 브라우저 설정에서 카메라 권한을 허용해주세요.");
toast.error("카메라 권한이 거부되었습니다.");
} else if (err.name === "NotFoundError") {
setError("카메라를 찾을 수 없습니다. 카메라가 연결되어 있는지 확인해주세요.");
toast.error("카메라를 찾을 수 없습니다.");
} else if (err.name === "NotReadableError") {
setError("카메라가 이미 다른 애플리케이션에서 사용 중입니다.");
toast.error("카메라가 사용 중입니다.");
} else if (err.name === "NotSupportedError") {
setError("보안 컨텍스트(HTTPS 또는 localhost)가 아니어서 카메라를 사용할 수 없습니다.");
toast.error("HTTPS 환경이 필요합니다.");
} else {
setError(`카메라 접근 오류: ${err.name} - ${err.message}`);
toast.error("카메라 접근 중 오류가 발생했습니다.");
}
}
};
// 스캔 시작
const startScanning = () => {
setIsScanning(true);
setError("");
setScannedCode("");
scanIntervalRef.current = setInterval(() => {
scanBarcode();
}, 500);
};
// 스캔 중지
const stopScanning = () => {
setIsScanning(false);
if (scanIntervalRef.current) {
clearInterval(scanIntervalRef.current);
scanIntervalRef.current = null;
}
};
// 바코드 스캔
const scanBarcode = async () => {
if (!webcamRef.current || !codeReaderRef.current) return;
try {
const imageSrc = webcamRef.current.getScreenshot();
if (!imageSrc) return;
const img = new Image();
img.src = imageSrc;
await new Promise((resolve) => {
img.onload = resolve;
});
const result = await codeReaderRef.current.decodeFromImageElement(img);
if (result) {
const barcode = result.getText();
setScannedCode(barcode);
stopScanning();
toast.success(`바코드 스캔 완료: ${barcode}`);
if (autoSubmit) {
onScanSuccess(barcode);
}
}
} catch (err) {
if (!(err instanceof NotFoundException)) {
// NotFoundException은 정상 (바코드 미인식)
}
}
};
// 수동 확인 버튼 (스캔 결과 또는 직접 입력)
const handleConfirm = () => {
const code = scannedCode || manualInput.trim();
if (code) {
onScanSuccess(code); // 호출 측에서 검색 필드를 덮어쓰기
onOpenChange(false);
} else {
toast.error("바코드를 스캔하거나 직접 입력해주세요.");
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[95vw] sm:max-w-[600px]">
<DialogHeader>
<DialogTitle className="text-base sm:text-lg"> </DialogTitle>
<DialogDescription className="text-xs sm:text-sm">
.
{targetField && ` (대상 필드: ${targetField})`}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{/* 카메라 권한 요청 대기 중 */}
{hasPermission === null && (
<div className="rounded-md border border-primary bg-primary/10 p-4">
<div className="flex items-start gap-3">
<Camera className="mt-0.5 h-5 w-5 flex-shrink-0 text-primary" />
<div className="flex-1 space-y-3 text-xs sm:text-sm">
<div>
<p className="font-semibold text-primary"> </p>
<p className="mt-1 text-muted-foreground">
.
</p>
</div>
<div className="rounded-md bg-background/50 p-3">
<p className="mb-2 font-medium text-foreground"> :</p>
<ul className="ml-4 list-disc space-y-1 text-muted-foreground">
<li> </li>
<li> <strong>&quot;&quot;</strong> </li>
<li> </li>
</ul>
</div>
<div className="flex items-center gap-2">
<Button
onClick={requestCameraPermission}
className="h-9 text-xs sm:h-10 sm:text-sm"
>
<Camera className="mr-2 h-4 w-4" />
</Button>
</div>
</div>
</div>
</div>
)}
{/* 카메라 권한 거부됨 */}
{hasPermission === false && (
<div className="rounded-md border border-destructive bg-destructive/10 p-4">
<div className="flex items-start gap-3">
<AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-destructive" />
<div className="flex-1 space-y-3 text-xs sm:text-sm">
<div>
<p className="font-semibold text-destructive"> </p>
<p className="mt-1 text-destructive/80">{error}</p>
</div>
<div className="rounded-md bg-background/50 p-3">
<p className="mb-2 font-medium text-foreground"> :</p>
<ol className="ml-4 list-decimal space-y-1 text-muted-foreground">
<li> </li>
<li><strong>&quot;&quot;</strong> <strong>&quot;&quot;</strong> </li>
<li> </li>
</ol>
</div>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="outline"
onClick={requestCameraPermission}
className="h-8 text-xs"
>
</Button>
</div>
</div>
</div>
</div>
)}
{/* 웹캠 뷰 */}
{hasPermission && (
<div className="relative aspect-video overflow-hidden rounded-lg border border-border bg-muted">
<Webcam
ref={webcamRef}
audio={false}
screenshotFormat="image/jpeg"
videoConstraints={{
facingMode: { ideal: "environment" },
}}
onUserMediaError={() => {
// environment 카메라 실패 시 자동 fallback (Webcam 내부 처리)
}}
className="h-full w-full object-cover"
/>
{/* 스캔 가이드 오버레이 */}
{isScanning && (
<div className="absolute inset-0 flex items-center justify-center">
<div className="h-3/5 w-4/5 rounded-lg border-4 border-primary/70 animate-pulse" />
<div className="absolute bottom-4 left-0 right-0 text-center">
<div className="inline-flex items-center gap-2 rounded-full bg-background/80 px-4 py-2 text-xs font-medium">
<Scan className="h-4 w-4 animate-pulse text-primary" />
...
</div>
</div>
</div>
)}
{/* 스캔 완료 오버레이 */}
{scannedCode && (
<div className="absolute inset-0 flex items-center justify-center bg-background/80">
<div className="text-center">
<CheckCircle2 className="mx-auto h-16 w-16 text-success" />
<p className="mt-2 text-sm font-medium"> !</p>
<p className="mt-1 font-mono text-lg font-bold text-primary">{scannedCode}</p>
</div>
</div>
)}
</div>
)}
{/* 수동 입력 (카메라 사용 불가 시 또는 외장 스캐너 사용 시) */}
<div className="rounded-md border border-border bg-muted/30 p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground"> </p>
<div className="flex gap-2">
<input
ref={manualInputRef}
type="text"
value={manualInput}
onChange={(e) => setManualInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && manualInput.trim()) {
e.preventDefault();
onScanSuccess(manualInput.trim());
onOpenChange(false);
}
}}
placeholder="바코드/QR 번호 입력 후 Enter"
className="flex-1 h-11 rounded-lg border border-border px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
autoFocus={hasPermission === false}
/>
<Button
onClick={() => {
if (manualInput.trim()) {
onScanSuccess(manualInput.trim());
onOpenChange(false);
}
}}
disabled={!manualInput.trim()}
className="h-11 px-4"
>
</Button>
</div>
</div>
{/* 바코드 포맷 정보 */}
<div className="rounded-md border border-border bg-muted/50 p-3">
<div className="flex items-start gap-2">
<AlertCircle className="mt-0.5 h-4 w-4 text-muted-foreground" />
<div className="text-[10px] text-muted-foreground sm:text-xs">
<p className="font-medium"> </p>
<p className="mt-1">
{barcodeFormat === "all" && "1D/2D 바코드 모두 지원 (Code 128, QR Code 등)"}
{barcodeFormat === "1d" && "1D 바코드 (Code 128, Code 39, EAN-13, UPC-A)"}
{barcodeFormat === "2d" && "2D 바코드 (QR Code, Data Matrix)"}
</p>
</div>
</div>
</div>
{/* 에러 메시지 */}
{error && (
<div className="rounded-md border border-destructive bg-destructive/10 p-3">
<div className="flex items-start gap-2">
<AlertCircle className="mt-0.5 h-4 w-4 text-destructive" />
<p className="text-xs text-destructive">{error}</p>
</div>
</div>
)}
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
</Button>
{!isScanning && !scannedCode && hasPermission && (
<Button
onClick={startScanning}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
<Camera className="mr-2 h-4 w-4" />
</Button>
)}
{isScanning && (
<Button
variant="destructive"
onClick={stopScanning}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
<CameraOff className="mr-2 h-4 w-4" />
</Button>
)}
{scannedCode && (
<Button
variant="outline"
onClick={() => {
setScannedCode("");
startScanning();
}}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
<Camera className="mr-2 h-4 w-4" />
</Button>
)}
{scannedCode && !autoSubmit && (
<Button
onClick={handleConfirm}
className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
>
<CheckCircle2 className="mr-2 h-4 w-4" />
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,82 @@
"use client";
import React from "react";
export interface ConfirmModalProps {
open: boolean;
title?: string;
message: string;
confirmText?: string;
cancelText?: string;
variant?: "primary" | "danger" | "success";
onConfirm: () => void;
onCancel: () => void;
}
/**
* POP 공용 확인 모달 (native confirm() 대체)
* 모바일 친화 디자인, bottom-sheet 스타일
*/
export function ConfirmModal({
open,
title,
message,
confirmText = "확인",
cancelText = "취소",
variant = "primary",
onConfirm,
onCancel,
}: ConfirmModalProps) {
if (!open) return null;
const confirmBg =
variant === "danger"
? "bg-gradient-to-b from-red-500 to-red-600 hover:from-red-600 hover:to-red-700"
: variant === "success"
? "bg-gradient-to-b from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700"
: "bg-gradient-to-b from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700";
return (
<div className="fixed inset-0 z-[100]" onClick={onCancel}>
{/* Overlay */}
<div className="absolute inset-0 bg-black/50" />
{/* Center modal */}
<div className="absolute inset-0 flex items-center justify-center p-6">
<div
className="w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden"
onClick={(e) => e.stopPropagation()}
>
{/* Body */}
<div className="px-6 py-7 text-center">
{title && (
<h3 className="text-lg font-bold text-gray-900 mb-3">{title}</h3>
)}
<p className="text-base text-gray-700 whitespace-pre-line leading-relaxed">
{message}
</p>
</div>
{/* Buttons */}
<div className="flex border-t border-gray-100">
<button
type="button"
onClick={onCancel}
className="flex-1 py-4 text-base font-semibold text-gray-600 hover:bg-gray-50 active:bg-gray-100 transition-colors"
>
{cancelText}
</button>
<div className="w-px bg-gray-100" />
<button
type="button"
onClick={onConfirm}
className={`flex-1 py-4 text-base font-bold text-white transition-all active:scale-[0.98] ${confirmBg}`}
>
{confirmText}
</button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,195 @@
"use client";
import React, { useState, useEffect, useMemo } from "react";
import { getChosung } from "../inbound/SupplierModal";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface EquipmentItem {
id: string;
equipment_code: string;
equipment_name: string;
}
interface EquipmentModalProps {
open: boolean;
onClose: () => void;
onSelect: (equipment: EquipmentItem) => void;
items: EquipmentItem[];
loading?: boolean;
title?: string;
searchPlaceholder?: string;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
const AVATAR_COLORS = [
"#3b82f6", "#22c55e", "#f59e0b", "#ef4444", "#8b5cf6",
"#06b6d4", "#ec4899", "#14b8a6", "#f97316", "#6366f1",
"#84cc16", "#e11d48", "#0ea5e9", "#a855f7", "#10b981",
];
function getAvatarColor(name: string): string {
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = name.charCodeAt(i) + ((hash << 5) - hash);
}
return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function EquipmentModal({
open,
onClose,
onSelect,
items,
loading = false,
title = "설비 선택",
searchPlaceholder = "설비명 또는 코드 검색...",
}: EquipmentModalProps) {
const [search, setSearch] = useState("");
const [sortMode, setSortMode] = useState<"korean" | "abc">("korean");
useEffect(() => {
if (open) setSearch("");
}, [open]);
const grouped = useMemo(() => {
const filtered = items.filter((e) =>
e.equipment_name.toLowerCase().includes(search.toLowerCase()) ||
e.equipment_code.toLowerCase().includes(search.toLowerCase())
);
const sorted = [...filtered].sort((a, b) => {
if (sortMode === "abc") return a.equipment_name.localeCompare(b.equipment_name, "en");
return a.equipment_name.localeCompare(b.equipment_name, "ko");
});
const groups: { letter: string; items: EquipmentItem[] }[] = [];
const map = new Map<string, EquipmentItem[]>();
for (const e of sorted) {
const first = e.equipment_name.trim().charAt(0);
const letter = getChosung(first);
if (!map.has(letter)) map.set(letter, []);
map.get(letter)!.push(e);
}
for (const [letter, list] of map) {
groups.push({ letter, items: list });
}
return groups;
}, [items, search, sortMode]);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
<div className="relative bg-white rounded-2xl w-[80vw] h-[80vh] flex flex-col shadow-2xl overflow-hidden z-10">
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<h3 className="text-lg font-bold text-gray-900">{title}</h3>
<div className="flex gap-1.5">
<button
onClick={() => setSortMode("korean")}
className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
sortMode === "korean"
? "bg-gray-900 text-white border-gray-900"
: "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
}`}
>
</button>
<button
onClick={() => setSortMode("abc")}
className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
sortMode === "abc"
? "bg-gray-900 text-white border-gray-900"
: "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
}`}
>
ABC
</button>
</div>
</div>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="px-5 py-3">
<div className="relative">
<svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={searchPlaceholder}
className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-xl text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all"
/>
</div>
</div>
<div className="flex-1 overflow-y-auto px-5 pb-5">
{loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
...
</div>
) : grouped.length === 0 ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
{search ? "검색 결과가 없습니다" : "등록된 설비가 없습니다"}
</div>
) : (
grouped.map((group) => (
<div key={group.letter} className="mb-2">
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-bold text-blue-500 min-w-[20px]">{group.letter}</span>
<div className="flex-1 h-px bg-gray-100" />
</div>
<div className="grid grid-cols-4 min-[900px]:grid-cols-5 gap-x-2 gap-y-1">
{group.items.map((equipment) => {
const displayName = equipment.equipment_name.trim();
const initial = displayName.charAt(0);
const color = getAvatarColor(equipment.equipment_name);
return (
<button
key={equipment.id}
onClick={() => { onSelect(equipment); onClose(); }}
className="flex flex-col items-center gap-1 py-1.5 px-3 w-full rounded-xl hover:bg-gray-50 active:scale-95 transition-all cursor-pointer border-none bg-transparent"
>
<div
className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl flex items-center justify-center text-white text-xl sm:text-2xl font-bold shadow-sm shrink-0"
style={{ background: color }}
>
{initial}
</div>
<span className="text-xs sm:text-sm font-medium text-gray-700 text-center leading-tight w-full truncate px-1">
{equipment.equipment_name}
</span>
</button>
);
})}
</div>
</div>
))
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,188 @@
"use client";
import React, { useState, useCallback, useEffect } from "react";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface SimpleKeypadModalProps {
open: boolean;
onClose: () => void;
onConfirm: (qty: number) => void;
maxQty: number;
itemName: string;
initialQty?: number;
}
/* ------------------------------------------------------------------ */
/* Numpad Keys */
/* ------------------------------------------------------------------ */
const KEYS = [
{ label: "7", action: "7" },
{ label: "8", action: "8" },
{ label: "9", action: "9" },
{ label: "\u2190", action: "backspace" },
{ label: "4", action: "4" },
{ label: "5", action: "5" },
{ label: "6", action: "6" },
{ label: "C", action: "clear" },
{ label: "1", action: "1" },
{ label: "2", action: "2" },
{ label: "3", action: "3" },
{ label: "MAX", action: "max" },
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function SimpleKeypadModal({
open,
onClose,
onConfirm,
maxQty,
itemName,
initialQty,
}: SimpleKeypadModalProps) {
const [qty, setQty] = useState("0");
/* Reset on open */
useEffect(() => {
if (open) {
setQty(initialQty !== undefined && initialQty > 0 ? String(initialQty) : "0");
}
}, [open, initialQty]);
const qtyNum = parseInt(qty, 10) || 0;
const isOverMax = qtyNum > maxQty;
/* Numpad input handler */
const handleInput = useCallback(
(key: string) => {
setQty((prev) => {
switch (key) {
case "backspace":
return prev.length <= 1 ? "0" : prev.slice(0, -1);
case "clear":
return "0";
case "max":
return String(maxQty);
default: {
const next = prev === "0" ? key : prev + key;
const num = parseInt(next, 10);
if (isNaN(num)) return prev;
return next;
}
}
});
},
[maxQty],
);
const handleConfirm = () => {
if (qtyNum <= 0) return;
const finalQty = Math.min(qtyNum, maxQty);
onConfirm(finalQty);
onClose();
};
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
{/* Overlay */}
<div className="absolute inset-0 bg-black/40" onClick={onClose} />
{/* Panel */}
<div className="relative bg-white w-[90%] max-w-[360px] rounded-2xl shadow-2xl z-10 overflow-hidden">
{/* Header - blue gradient */}
<div
className="flex items-center justify-between px-4 py-3"
style={{ background: "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)" }}
>
<span className="text-[13px] text-white/90 bg-white/20 px-3 py-1 rounded-full">
{maxQty.toLocaleString()} EA
</span>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-white/20 flex items-center justify-center text-white hover:bg-white/30 active:scale-95 transition-all"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Body */}
<div className="p-4">
<p className="text-center text-sm font-semibold text-gray-700 mb-1">
</p>
<p className="text-center text-xs text-gray-400 mb-3 truncate px-2">
{itemName}
</p>
{/* Display */}
<input
type="text"
readOnly
value={qtyNum.toLocaleString()}
className={`w-full px-4 py-3 text-right text-3xl font-bold border-2 rounded-xl bg-gray-50 mb-3 ${
isOverMax ? "border-red-300 text-red-500" : "border-gray-200 text-gray-900"
}`}
style={{ fontVariantNumeric: "tabular-nums" }}
/>
{isOverMax && (
<p className="text-center text-xs text-red-500 font-medium mb-2">
{maxQty.toLocaleString()}EA ({maxQty.toLocaleString()}EA)
</p>
)}
{/* Numpad grid: 4x3 + bottom row */}
<div className="grid grid-cols-4 gap-2.5">
{KEYS.map((key) => (
<button
key={key.action}
onClick={() => handleInput(key.action)}
className={`h-14 rounded-xl text-lg font-semibold active:scale-95 transition-all ${
key.action === "backspace" || key.action === "clear"
? "bg-amber-100 text-amber-700 hover:bg-amber-200"
: key.action === "max"
? "bg-blue-100 text-blue-700 hover:bg-blue-200 text-sm"
: "bg-gray-100 text-gray-900 hover:bg-gray-200"
}`}
>
{key.label}
</button>
))}
{/* Bottom row: 0 (span 2) + Confirm (span 2) */}
<button
onClick={() => handleInput("0")}
className="col-span-2 h-14 rounded-xl text-lg font-semibold bg-gray-100 text-gray-900 hover:bg-gray-200 active:scale-95 transition-all"
>
0
</button>
<button
onClick={handleConfirm}
disabled={qtyNum <= 0}
className={`col-span-2 h-14 rounded-xl text-lg font-bold text-white active:scale-95 transition-all ${
qtyNum <= 0 ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: qtyNum <= 0
? "#9ca3af"
: "linear-gradient(135deg, #10b981 0%, #059669 100%)",
}}
>
</button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,27 @@
/**
* useCartSync - 장바구니 DB 동기화 훅 (hardcoded 컴포넌트용 re-export)
*
* 실제 구현은 @/hooks/pop/useCartSync 에 있고,
* 여기서는 hardcoded 입고 컴포넌트들이 쉽게 import할 수 있도록 re-export한다.
*
* 사용법:
* ```typescript
* import { useCartSync } from "../common/useCartSync";
* const cart = useCartSync("inbound");
* ```
*/
export { useCartSync } from "@/hooks/pop/useCartSync";
export type {
UseCartSyncReturn,
CartChanges,
CartCategory,
} from "@/hooks/pop/useCartSync";
// 타입도 함께 re-export (hardcoded 컴포넌트에서 필요할 수 있음)
export type {
CartItem,
CartItemWithId,
CartSyncStatus,
CartItemStatus,
} from "@/lib/registry/pop-components/types";
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ChangeOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ChangeInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_change";
export function ChangeInbound({ cart, onCartClick, saving, inboundType, sourceTable }: ChangeInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<ChangeOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<ChangeOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 교환입고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 교환입고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: ChangeOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 교환입고 라인, 발주품목 위. 테마 teal */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #2dd4bf, #0d9488)",
boxShadow: "0 4px 12px rgba(13,148,136,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #2dd4bf, #0d9488)",
boxShadow: "0 4px 12px rgba(20,184,166,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-teal-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-teal-400 focus:ring-2 focus:ring-teal-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #2dd4bf, #0d9488)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(20,184,166,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-teal-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 교환 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-teal-500 rounded-lg hover:bg-teal-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-teal-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-teal-100 text-teal-700 border border-teal-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-teal-50 border-teal-200 hover:bg-teal-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-teal-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #14b8a6 0%, #0d9488 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="교환 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ErrorOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ErrorInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_error";
export function ErrorInbound({ cart, onCartClick, saving, inboundType, sourceTable }: ErrorInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<ErrorOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<ErrorOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 불량입고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 불량입고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: ErrorOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 불량입고 라인, 발주품목 위. 테마 red */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #f87171, #dc2626)",
boxShadow: "0 4px 12px rgba(220,38,38,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #f87171, #dc2626)",
boxShadow: "0 4px 12px rgba(239,68,68,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-red-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-red-400 focus:ring-2 focus:ring-red-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #f87171, #dc2626)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(239,68,68,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-red-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 불량 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-red-500 rounded-lg hover:bg-red-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-red-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-red-100 text-red-700 border border-red-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-red-50 border-red-200 hover:bg-red-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-red-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #ef4444 0%, #dc2626 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="불량 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,735 @@
"use client";
import { useRouter } from "next/navigation";
import React, { useCallback, useEffect, useState } from "react";
import { apiClient } from "@/lib/api/client";
import { InspectionModal, type InspectionResult } from "./InspectionModal";
import type { PackageEntry } from "./NumberPadModal";
/* ------------------------------------------------------------------ */
/* Warehouse type */
/* ------------------------------------------------------------------ */
interface Warehouse {
warehouse_code: string;
warehouse_name: string;
warehouse_type?: string;
}
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface CartItem {
id: string;
/** cart_items 테이블의 PK (UUID) — DB 삭제용 */
dbId?: string;
/** purchase_detail or purchase_order_mng */
source_table: string;
/** PK of the source row */
source_id: string;
purchase_no: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
remain_qty: number;
/** User-entered quantity */
inbound_qty: number;
unit_price: number;
supplier_code: string;
supplier_name: string;
order_date: string;
inspection_required?: boolean;
inspection_type?: "self" | "request" | null;
packages?: PackageEntry[];
inspectionResult?: InspectionResult | null;
}
interface InboundCartProps {
open: boolean;
onClose: () => void;
items: CartItem[];
onUpdateQty: (id: string, qty: number) => void;
onRemove: (id: string) => void;
onClear: () => void;
supplierName?: string;
onUpdateItems?: (items: CartItem[]) => void;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function InboundCart({
open,
onClose,
items,
onUpdateQty,
onRemove,
onClear,
supplierName,
onUpdateItems,
}: InboundCartProps) {
const router = useRouter();
const [confirming, setConfirming] = useState(false);
const [resultMsg, setResultMsg] = useState<string | null>(null);
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
const [inspectionModalOpen, setInspectionModalOpen] = useState(false);
const [inspectionTarget, setInspectionTarget] = useState<CartItem | null>(
null,
);
/* Warehouse state */
const [warehouses, setWarehouses] = useState<Warehouse[]>([]);
const [selectedWarehouse, setSelectedWarehouse] = useState<string>("");
/* Fetch warehouses on mount */
const fetchWarehouses = useCallback(async () => {
try {
const res = await apiClient.get("/receiving/warehouses");
const data: Warehouse[] = res.data?.data ?? [];
setWarehouses(data);
if (data.length > 0 && !selectedWarehouse) {
setSelectedWarehouse(data[0].warehouse_code);
}
} catch {
// Keep empty - user can still confirm without warehouse
}
}, [selectedWarehouse]);
useEffect(() => {
if (open) {
fetchWarehouses();
}
}, [open, fetchWarehouses]);
const totalQty = items.reduce((s, i) => s + i.inbound_qty, 0);
const totalAmount = items.reduce(
(s, i) => s + i.inbound_qty * i.unit_price,
0,
);
/* Toggle select */
const toggleSelect = (id: string) => {
setSelectedItems((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const toggleSelectAll = () => {
if (selectedItems.size === items.length) {
setSelectedItems(new Set());
} else {
setSelectedItems(new Set(items.map((i) => i.id)));
}
};
/* Open inspection modal */
const openInspection = (item: CartItem) => {
setInspectionTarget(item);
setInspectionModalOpen(true);
};
/* Handle inspection complete */
const handleInspectionComplete = (result: InspectionResult) => {
if (!inspectionTarget || !onUpdateItems) return;
const updated = items.map((item) =>
item.id === inspectionTarget.id
? { ...item, inspectionResult: result }
: item,
);
onUpdateItems(updated);
setInspectionTarget(null);
};
/* Confirm inbound — PC receivingController.create 와 동일한 body 구조 */
const handleConfirm = async () => {
if (items.length === 0) return;
if (!selectedWarehouse) {
setResultMsg("오류: 입고 창고를 선택해주세요.");
return;
}
setConfirming(true);
setResultMsg(null);
try {
// 1. 입고번호 채번 (RCV-YYYY-XXXX)
let inboundNumber: string | undefined;
try {
const numRes = await apiClient.get("/receiving/generate-number");
if (numRes.data?.success && numRes.data?.data) {
inboundNumber = numRes.data.data;
}
} catch {
// 채번 실패 시 백엔드가 처리
}
// 2. POST /api/receiving — PC create 와 동일한 payload
const payload = {
inbound_number: inboundNumber,
inbound_date: new Date().toISOString().slice(0, 10),
warehouse_code: selectedWarehouse,
inbound_type: "구매입고",
items: items.map((item, idx) => ({
inbound_type: "구매입고",
item_number: item.item_code,
item_name: item.item_name,
spec: item.spec || "",
material: item.material || "",
unit: "EA",
inbound_qty: String(item.inbound_qty),
unit_price: String(item.unit_price || 0),
total_amount: String(
(item.inbound_qty || 0) * (item.unit_price || 0),
),
reference_number: item.purchase_no,
supplier_code: item.supplier_code,
supplier_name: item.supplier_name,
inspection_status: item.inspectionResult?.completed
? "검사완료"
: item.inspection_required
? "검사대기"
: "합격",
source_table: item.source_table,
source_id: item.source_id || item.id,
seq_no: idx + 1,
})),
};
const res = await apiClient.post("/receiving", payload);
if (res.data?.success) {
// 2-1. 검사 결과가 있는 항목 → inspection_result에 저장
const insertedDetails: any[] =
res.data?.data?.details ?? res.data?.data?.items ?? [];
const inboundHeaderNo =
res.data?.data?.header?.inbound_number || inboundNumber || "";
const inspectionPromises = items
.map((item, idx) => {
if (!item.inspectionResult?.completed) return null;
const matchedDetail = insertedDetails[idx] ?? {};
const referenceId =
matchedDetail.id ||
matchedDetail.detail_id ||
`${inboundHeaderNo}-${idx + 1}`;
const goodQty = item.inspectionResult.goodQty || 0;
const badQty = item.inspectionResult.badQty || 0;
const totalQty = goodQty + badQty;
const overallJudgment = badQty === 0 ? "합격" : "불합격";
return apiClient
.post("/pop/inspection-result", {
inspectionNumber: item.inspectionResult.inspectionNumber, // 카트에서 받은 검사번호 재사용
referenceTable: "inbound_mng",
referenceId,
screenId: "pop_inbound_inspection",
itemId: item.item_id || null,
itemCode: item.item_code,
itemName: item.item_name,
inspectionType: "입고검사",
overallJudgment,
totalQty,
goodQty,
badQty,
defectDescription: badQty > 0 ? `불량 ${badQty}` : "",
memo: item.inspectionResult.remark || "",
supplierCode: item.supplier_code || null,
supplierName: item.supplier_name || null,
isCompleted: true,
items: item.inspectionResult.items.map((insp: any) => ({
inspectionInfoId: insp.id || null,
inspectionItemName: insp.inspection_item_name,
inspectionStandard: insp.inspection_standard,
passCriteria: insp.pass_criteria,
isRequired: insp.is_required || "Y",
measuredValue: insp.measured_value || "",
judgment: insp.result || null,
})),
})
.catch((err) => {
console.error(
"[inspection_result 저장 실패]",
item.item_code,
err?.message,
);
});
})
.filter(Boolean);
if (inspectionPromises.length > 0) {
await Promise.allSettled(inspectionPromises);
}
// 3. cart_items DB 정리 (백그라운드, 논블로킹)
// cart_items.row_key 로 삭제 (row_key = source_id 로 저장됨)
const rowKeys = items
.map((item) => item.source_id || item.id)
.filter(Boolean);
if (rowKeys.length > 0) {
apiClient
.post("/pop/execute-action", {
tasks: [{ type: "cart-save" }],
cartChanges: {
toDelete: rowKeys,
},
})
.catch(() => {
// cart cleanup 실패 시 무시
});
}
const inboundNo =
res.data?.data?.header?.inbound_number || inboundNumber || "";
setResultMsg(`${items.length}건 입고 등록 완료! (${inboundNo})`);
setTimeout(() => {
onClear();
onClose();
router.push("/COMPANY_7/pop/inbound");
}, 1500);
} else {
setResultMsg(
`오류: ${res.data?.message || "입고 등록에 실패했습니다."}`,
);
}
} catch (err: unknown) {
const msg =
err instanceof Error ? err.message : "입고 등록에 실패했습니다.";
setResultMsg(`오류: ${msg}`);
} finally {
setConfirming(false);
}
};
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
{/* Overlay */}
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
{/* Panel */}
<div className="relative bg-white w-full sm:max-w-lg sm:rounded-2xl rounded-t-2xl max-h-[90vh] flex flex-col shadow-2xl z-10 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-blue-500 flex items-center justify-center">
<svg
className="w-5 h-5 text-white"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22"
/>
</svg>
</div>
<div>
<h3 className="text-lg font-bold text-gray-900"> </h3>
{supplierName && (
<p className="text-xs text-gray-400">{supplierName}</p>
)}
</div>
</div>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Select all bar */}
{items.length > 0 && (
<div className="flex items-center gap-3 px-5 py-2 border-b border-gray-50 bg-gray-50/50">
<button
onClick={toggleSelectAll}
className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all shrink-0 ${
selectedItems.size === items.length
? "bg-blue-500 border-blue-500"
: "border-gray-300 hover:border-blue-400"
}`}
>
{selectedItems.size === items.length && (
<svg
className="w-3 h-3 text-white"
fill="none"
stroke="currentColor"
strokeWidth={3}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M4.5 12.75l6 6 9-13.5"
/>
</svg>
)}
</button>
<span className="text-xs text-gray-500">
({selectedItems.size}/{items.length})
</span>
</div>
)}
{/* Items */}
<div className="flex-1 overflow-y-auto px-5 py-3">
{items.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg
className="w-12 h-12 mb-3 opacity-30"
fill="none"
stroke="currentColor"
strokeWidth={1}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22"
/>
</svg>
<p className="text-sm"> </p>
</div>
) : (
<div className="flex flex-col gap-3">
{items.map((item) => (
<div
key={item.id}
className="bg-gray-50 rounded-xl p-3 border border-gray-100"
>
{/* Top row: checkbox + name + delete */}
<div className="flex items-start gap-2.5 mb-2">
{/* Checkbox */}
<button
onClick={() => toggleSelect(item.id)}
className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all shrink-0 mt-0.5 ${
selectedItems.has(item.id)
? "bg-blue-500 border-blue-500"
: "border-gray-300 hover:border-blue-400"
}`}
>
{selectedItems.has(item.id) && (
<svg
className="w-3 h-3 text-white"
fill="none"
stroke="currentColor"
strokeWidth={3}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M4.5 12.75l6 6 9-13.5"
/>
</svg>
)}
</button>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900 truncate">
{item.item_name}
</p>
<p className="text-[11px] text-gray-400 mt-0.5">
{item.item_code} | {item.purchase_no}
</p>
</div>
{/* Delete button */}
<button
onClick={() => onRemove(item.id)}
className="w-7 h-7 rounded-lg flex items-center justify-center text-white bg-red-400 hover:bg-red-500 transition-colors shrink-0"
>
<svg
className="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"
/>
</svg>
</button>
</div>
{/* Spec row */}
{(item.spec || item.material) && (
<p className="text-[11px] text-gray-400 mb-2 ml-[30px]">
{[item.spec, item.material].filter(Boolean).join(" | ")}
</p>
)}
{/* Package info */}
{item.packages && item.packages.length > 0 && (
<div className="ml-[30px] mb-2 px-2.5 py-2 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg">
<div className="flex items-center gap-2 mb-0.5">
<span className="text-[10px] font-bold text-white bg-green-500 px-1.5 py-0.5 rounded-full">
</span>
<span className="text-[10px] text-green-600 font-semibold">
{"\uD83D\uDCE6"}{" "}
{item.packages
.map(
(p) =>
`${p.count}${p.unit.label} x ${p.qtyPerUnit.toLocaleString()} = ${(p.count * p.qtyPerUnit).toLocaleString()}EA`,
)
.join(", ")}
</span>
</div>
</div>
)}
{/* Inspection row */}
{(item.inspection_type === "self" ||
item.inspection_type === "request") && (
<div className="ml-[30px] mb-2">
<button
onClick={() => openInspection(item)}
className={`flex items-center gap-2 w-full px-3 py-2 rounded-md border text-left transition-all ${
item.inspectionResult?.completed
? "bg-green-50 border-green-300"
: item.inspection_type === "self"
? "bg-blue-50 border-blue-200 hover:bg-blue-100"
: "bg-amber-50 border-amber-200 hover:bg-amber-100"
}`}
>
<span className="text-[13px] font-semibold">
{item.inspection_type === "self"
? "검사"
: "검사의뢰"}
</span>
<span
className={`text-[11px] px-1.5 py-0.5 rounded ${
item.inspection_required
? "bg-red-100 text-red-600"
: "bg-blue-100 text-blue-600"
}`}
>
{item.inspection_required ? "필수" : "선택"}
</span>
<span
className={`ml-auto text-[12px] font-semibold ${
item.inspectionResult?.completed
? "text-green-600"
: "text-gray-400"
}`}
>
{item.inspectionResult?.completed ? "완료" : "대기"}
</span>
<svg
className="w-4 h-4 text-gray-400 shrink-0"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 4.5l7.5 7.5-7.5 7.5"
/>
</svg>
</button>
</div>
)}
{/* Qty controls */}
<div className="flex items-center justify-between ml-[30px]">
<div className="flex items-center gap-2">
<span className="text-xs text-gray-400">
: {item.remain_qty.toLocaleString()}
</span>
</div>
<div className="flex items-center gap-1.5">
<button
onClick={() =>
onUpdateQty(
item.id,
Math.max(1, item.inbound_qty - 1),
)
}
className="w-8 h-8 rounded-lg bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg
className="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19.5 12h-15"
/>
</svg>
</button>
<input
type="number"
value={item.inbound_qty}
onChange={(e) => {
const v = parseInt(e.target.value, 10);
if (!isNaN(v) && v >= 0)
onUpdateQty(item.id, Math.min(v, item.remain_qty));
}}
className="w-16 h-8 text-center text-sm font-semibold border border-gray-200 rounded-lg outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100"
style={{ fontVariantNumeric: "tabular-nums" }}
/>
<button
onClick={() =>
onUpdateQty(
item.id,
Math.min(item.remain_qty, item.inbound_qty + 1),
)
}
className="w-8 h-8 rounded-lg bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg
className="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 4.5v15m7.5-7.5h-15"
/>
</svg>
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Footer summary + confirm */}
{items.length > 0 && (
<div className="border-t border-gray-100 px-5 py-4">
{/* Result message */}
{resultMsg && (
<div
className={`mb-3 p-3 rounded-xl text-sm font-medium ${
resultMsg.startsWith("오류")
? "bg-red-50 text-red-700"
: "bg-green-50 text-green-700"
}`}
>
{resultMsg}
</div>
)}
{/* Warehouse selection */}
<div className="mb-3">
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<select
value={selectedWarehouse}
onChange={(e) => setSelectedWarehouse(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100 bg-white"
>
{warehouses.length === 0 ? (
<option value=""> </option>
) : (
warehouses.map((wh) => (
<option key={wh.warehouse_code} value={wh.warehouse_code}>
{wh.warehouse_name} ({wh.warehouse_code})
</option>
))
)}
</select>
</div>
{/* Summary */}
<div className="flex items-center justify-between mb-3 text-sm">
<span className="text-gray-500">
{" "}
<span className="font-bold text-gray-900">{items.length}</span>
</span>
<div className="flex items-center gap-3">
<span className="text-gray-500">
:{" "}
<span className="font-bold text-blue-600">
{totalQty.toLocaleString()}
</span>
</span>
{totalAmount > 0 && (
<span className="text-gray-400 text-xs">
({totalAmount.toLocaleString()})
</span>
)}
</div>
</div>
{/* Buttons */}
<div className="flex gap-3">
<button
onClick={() => {
onClear();
}}
className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-50 active:scale-[0.98] transition-all"
>
</button>
<button
onClick={handleConfirm}
disabled={confirming || items.length === 0}
className="flex-[2] h-12 rounded-xl text-sm font-bold text-white active:scale-[0.98] transition-all disabled:opacity-50"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
boxShadow: "0 4px 12px rgba(59,130,246,.3)",
}}
>
{confirming ? "처리 중..." : `입고 확정 (${items.length}건)`}
</button>
</div>
</div>
)}
</div>
{/* Inspection Modal */}
{inspectionTarget && (
<InspectionModal
open={inspectionModalOpen}
onClose={() => {
setInspectionModalOpen(false);
setInspectionTarget(null);
}}
onComplete={handleInspectionComplete}
itemCode={inspectionTarget.item_code}
itemName={inspectionTarget.item_name}
totalQty={inspectionTarget.inbound_qty}
initialResult={inspectionTarget.inspectionResult}
/>
)}
</div>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,891 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier } from "./SupplierModal";
import {
getReceivingList,
updateReceiving,
deleteReceiving,
getReceivingWarehouses,
type InboundItem,
type WarehouseOption,
} from "@/lib/api/receiving";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface InboundRecord extends InboundItem {
detail_id?: string;
seq_no?: number;
detail_inbound_type?: string;
header_memo?: string;
}
const STATUS_OPTIONS = ["입고완료", "부분입고", "대기"];
const INSPECTION_OPTIONS = ["대기", "검사완료", "합격", "불합격"];
const INBOUND_TYPE_OPTIONS = [
{ value: "all", label: "전체" },
{ value: "구매입고", label: "구매입고" },
{ value: "생산입고", label: "생산입고" },
{ value: "외주입고", label: "외주입고" },
{ value: "사급자재입고", label: "사급자재입고" },
{ value: "반품입고", label: "반품입고" },
{ value: "반납입고", label: "반납입고" },
{ value: "불량입고", label: "불량입고" },
{ value: "교환입고", label: "교환입고" },
{ value: "외주자재회수", label: "외주자재회수" },
{ value: "기타입고", label: "기타입고" },
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function InboundManage() {
const router = useRouter();
const today = new Date().toISOString().slice(0, 10);
/* ── Filters ── */
const [inboundDate, setInboundDate] = useState(today);
const [inboundType, setInboundType] = useState("all");
const [keyword, setKeyword] = useState("");
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(
null,
);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
/* ── Data ── */
const [records, setRecords] = useState<InboundRecord[]>([]);
const [loading, setLoading] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [warehouses, setWarehouses] = useState<WarehouseOption[]>([]);
/* ── Edit modal ── */
const [editRecord, setEditRecord] = useState<InboundRecord | null>(null);
const [editForm, setEditForm] = useState<Record<string, any>>({});
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
/* ── Helpers ── */
const getRowKey = (r: InboundRecord) => r.detail_id || r.id;
/* ---------------------------------------------------------------- */
/* Fetch */
/* ---------------------------------------------------------------- */
const fetchRecords = useCallback(async () => {
setLoading(true);
try {
const params: Record<string, string> = {};
if (inboundDate) {
params.date_from = inboundDate;
params.date_to = inboundDate;
}
if (inboundType !== "all") params.inbound_type = inboundType;
if (keyword.trim()) params.search_keyword = keyword.trim();
const res = await getReceivingList(params);
if (res.success) {
let data = res.data as unknown as InboundRecord[];
if (selectedSupplier?.customer_code) {
data = data.filter(
(r) => r.supplier_code === selectedSupplier.customer_code,
);
}
setRecords(data);
setSelectedIds(new Set());
}
} catch (e) {
console.error("입고 목록 조회 실패", e);
} finally {
setLoading(false);
}
}, [inboundDate, inboundType, keyword, selectedSupplier]);
useEffect(() => {
getReceivingWarehouses()
.then((res) => {
if (res.success) setWarehouses(res.data);
})
.catch(() => {});
}, []);
useEffect(() => {
fetchRecords();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/* ---------------------------------------------------------------- */
/* Selection */
/* ---------------------------------------------------------------- */
const toggleSelect = (key: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
const toggleSelectAll = () => {
if (selectedIds.size === records.length) setSelectedIds(new Set());
else setSelectedIds(new Set(records.map(getRowKey)));
};
/* ---------------------------------------------------------------- */
/* Delete */
/* ---------------------------------------------------------------- */
const handleDelete = async () => {
if (selectedIds.size === 0) return;
const headerIds = new Set<string>();
records.forEach((r) => {
if (selectedIds.has(getRowKey(r))) headerIds.add(r.id);
});
if (
!confirm(
`선택한 ${headerIds.size}건의 입고를 삭제하시겠습니까?\n(재고가 롤백됩니다)`,
)
)
return;
setDeleting(true);
try {
for (const hid of headerIds) {
await deleteReceiving(hid);
}
await fetchRecords();
} catch (e: any) {
alert(`삭제 실패: ${e?.message || "알 수 없는 오류"}`);
} finally {
setDeleting(false);
}
};
/* ---------------------------------------------------------------- */
/* Edit */
/* ---------------------------------------------------------------- */
const openEdit = (record: InboundRecord) => {
setEditRecord(record);
setEditForm({
inbound_date: record.inbound_date?.slice(0, 10) || today,
inbound_qty: record.inbound_qty ?? 0,
unit_price: record.unit_price ?? 0,
total_amount: record.total_amount ?? 0,
lot_number: record.lot_number || "",
warehouse_code: record.warehouse_code || "",
location_code: record.location_code || "",
inbound_status: record.inbound_status || "입고완료",
inspection_status: record.inspection_status || "대기",
inspector: record.inspector || "",
manager: record.manager || "",
memo: record.memo || "",
});
};
const handleEditFromSelection = () => {
if (selectedIds.size !== 1) {
alert("수정할 항목을 1건만 선택해주세요.");
return;
}
const key = Array.from(selectedIds)[0];
const rec = records.find((r) => getRowKey(r) === key);
if (rec) openEdit(rec);
};
const updateField = (key: string, value: any) => {
setEditForm((prev) => {
const next = { ...prev, [key]: value };
if (key === "inbound_qty" || key === "unit_price") {
next.total_amount =
Math.round(
(Number(next.inbound_qty) || 0) *
(Number(next.unit_price) || 0) *
100,
) / 100;
}
return next;
});
};
const handleSave = async () => {
if (!editRecord) return;
setSaving(true);
try {
const payload: Record<string, any> = { ...editForm };
if (editRecord.detail_id) payload.detail_id = editRecord.detail_id;
await updateReceiving(editRecord.id, payload as Partial<InboundItem>);
setEditRecord(null);
await fetchRecords();
} catch (e: any) {
alert(`수정 실패: ${e?.message || "알 수 없는 오류"}`);
} finally {
setSaving(false);
}
};
/* ---------------------------------------------------------------- */
/* Render */
/* ---------------------------------------------------------------- */
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15.75 19.5L8.25 12l7.5-7.5"
/>
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight">
</h1>
<p className="text-xs text-gray-400 mt-0.5">
, ,
</p>
</div>
</div>
{/* ===== Search / Filter ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
{/* 입고일 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<input
type="date"
value={inboundDate}
onChange={(e) => setInboundDate(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
/>
</div>
{/* 입고유형 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<select
value={inboundType}
onChange={(e) => setInboundType(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 bg-white"
>
{INBOUND_TYPE_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
{/* 거래처 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<button
onClick={() => setSupplierModalOpen(true)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-left outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 bg-white flex items-center justify-between"
>
<span
className={
selectedSupplier
? "text-gray-900 truncate"
: "text-gray-400"
}
>
{selectedSupplier ? selectedSupplier.customer_name : "전체"}
</span>
{selectedSupplier ? (
<span
onClick={(e) => {
e.stopPropagation();
setSelectedSupplier(null);
}}
className="text-gray-400 hover:text-gray-600 ml-1 shrink-0"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</span>
) : (
<svg
className="w-4 h-4 text-gray-400 shrink-0"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9"
/>
</svg>
)}
</button>
</div>
{/* 검색어 + 검색버튼 */}
<div className="col-span-2">
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") fetchRecords();
}}
placeholder="입고번호, 품목명, 거래처명..."
className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
/>
<button
onClick={fetchRecords}
disabled={loading}
className="min-w-[48px] min-h-[40px] rounded-lg flex items-center justify-center text-white active:scale-95 transition-all disabled:opacity-50"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
}}
>
{loading ? (
<svg
className="w-5 h-5 animate-spin"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
) : (
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
/>
</svg>
)}
</button>
</div>
</div>
</div>
</div>
{/* ===== Action buttons ===== */}
<div className="flex items-center justify-between">
<span className="text-sm text-gray-500">
{selectedIds.size > 0
? `${selectedIds.size}건 선택`
: `${records.length}`}
</span>
<div className="flex items-center gap-2">
<button
disabled={selectedIds.size !== 1}
onClick={handleEditFromSelection}
className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
}}
>
</button>
<button
disabled={selectedIds.size === 0 || deleting}
onClick={handleDelete}
className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
style={{
background: "linear-gradient(to bottom, #f87171, #dc2626)",
}}
>
{deleting ? "삭제 중..." : "삭제"}
</button>
</div>
</div>
{/* ===== Record list ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={
records.length > 0 && selectedIds.size === records.length
}
onChange={toggleSelectAll}
className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<span className="text-xs font-semibold text-gray-500">
</span>
</div>
<span className="text-[11px] text-gray-400">{records.length}</span>
</div>
{loading && records.length === 0 ? (
<div className="flex items-center justify-center py-16">
<svg
className="w-8 h-8 animate-spin text-blue-500"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
</div>
) : records.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg
className="w-16 h-16 mb-4 opacity-20"
fill="none"
stroke="currentColor"
strokeWidth={1}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 11.625a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
/>
</svg>
<p className="text-sm font-medium text-gray-500 mb-1">
</p>
<p className="text-xs text-gray-400">
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{records.map((record) => {
const key = getRowKey(record);
return (
<div
key={key}
className={`relative rounded-xl border p-3 transition-all cursor-pointer ${
selectedIds.has(key)
? "ring-2 ring-blue-500 border-blue-300 bg-blue-50/30"
: "border-gray-200 bg-white hover:border-blue-300"
}`}
onClick={() => toggleSelect(key)}
>
{/* Card header */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<input
type="checkbox"
checked={selectedIds.has(key)}
onChange={() => toggleSelect(key)}
onClick={(e) => e.stopPropagation()}
className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<span className="text-[11px] text-gray-400 font-medium">
{record.inbound_number}
</span>
<span className="text-[11px] font-semibold px-1.5 py-0.5 rounded-full bg-blue-50 text-blue-600">
{record.detail_inbound_type || record.inbound_type}
</span>
<span
className={`ml-auto text-[11px] font-semibold px-1.5 py-0.5 rounded-full ${
record.inbound_status === "입고완료"
? "bg-green-50 text-green-600"
: record.inbound_status === "부분입고"
? "bg-amber-50 text-amber-600"
: "bg-gray-50 text-gray-500"
}`}
>
{record.inbound_status || "입고"}
</span>
<button
onClick={(e) => {
e.stopPropagation();
openEdit(record);
}}
className="ml-1 w-7 h-7 rounded-lg bg-gray-50 hover:bg-blue-50 flex items-center justify-center text-gray-400 hover:text-blue-600 transition-colors"
>
<svg
className="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"
/>
</svg>
</button>
</div>
{/* Card body */}
<div className="flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700 truncate">
{record.item_name || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-500 truncate">
{record.item_number || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{record.supplier_name || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-bold text-blue-700">
{Number(record.inbound_qty).toLocaleString()}{" "}
{record.unit || "EA"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{record.inbound_date?.slice(0, 10) || "-"}
</span>
</div>
{(record as any).warehouse_name && (
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{(record as any).warehouse_name}
</span>
</div>
)}
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Edit Modal ===== */}
{editRecord && (
<div
className="fixed inset-0 z-50 bg-black/40"
onClick={() => setEditRecord(null)}
>
<div
className="absolute inset-x-0 bottom-0 sm:inset-auto sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 bg-white w-full sm:max-w-lg max-h-[90vh] rounded-t-2xl sm:rounded-2xl overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Modal header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-100 bg-gradient-to-b from-blue-50 to-white shrink-0">
<div className="min-w-0">
<h2 className="text-lg font-bold text-gray-900"> </h2>
<p className="text-[11px] text-gray-400 truncate">
{editRecord.inbound_number} | {editRecord.item_name}
</p>
</div>
<button
onClick={() => setEditRecord(null)}
className="w-9 h-9 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-600 shrink-0 ml-2"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Modal body */}
<div className="flex-1 overflow-y-auto px-4 py-4 space-y-5">
{/* 기본 정보 */}
<FieldGroup title="기본 정보">
<FormField
label="입고일"
type="date"
value={editForm.inbound_date}
onChange={(v) => updateField("inbound_date", v)}
/>
<FormField
label="입고상태"
type="select"
value={editForm.inbound_status}
onChange={(v) => updateField("inbound_status", v)}
options={STATUS_OPTIONS}
/>
</FieldGroup>
{/* 수량/금액 */}
<FieldGroup title="수량/금액">
<FormField
label="수량"
type="number"
value={editForm.inbound_qty}
onChange={(v) => updateField("inbound_qty", v)}
/>
<FormField
label="단가"
type="number"
value={editForm.unit_price}
onChange={(v) => updateField("unit_price", v)}
/>
<FormField
label="금액"
type="number"
value={editForm.total_amount}
onChange={(v) => updateField("total_amount", v)}
readOnly
/>
</FieldGroup>
{/* 입고 상세 */}
<FieldGroup title="입고 상세">
<FormField
label="LOT번호"
value={editForm.lot_number}
onChange={(v) => updateField("lot_number", v)}
/>
<FormField
label="창고"
type="select"
value={editForm.warehouse_code}
onChange={(v) => updateField("warehouse_code", v)}
options={warehouses.map((w) => ({
value: w.warehouse_code,
label: w.warehouse_name,
}))}
emptyLabel="선택..."
/>
<FormField
label="위치"
value={editForm.location_code}
onChange={(v) => updateField("location_code", v)}
/>
<FormField
label="검사상태"
type="select"
value={editForm.inspection_status}
onChange={(v) => updateField("inspection_status", v)}
options={INSPECTION_OPTIONS}
/>
<FormField
label="검사자"
value={editForm.inspector}
onChange={(v) => updateField("inspector", v)}
/>
<FormField
label="담당자"
value={editForm.manager}
onChange={(v) => updateField("manager", v)}
/>
</FieldGroup>
{/* 메모 */}
<div>
<h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
</h3>
<textarea
value={editForm.memo}
onChange={(e) => updateField("memo", e.target.value)}
rows={3}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 resize-none"
placeholder="메모 입력..."
/>
</div>
</div>
{/* Modal footer */}
<div className="flex items-center gap-3 px-4 py-3 border-t border-gray-100 bg-gray-50/50 shrink-0">
<button
onClick={() => setEditRecord(null)}
className="flex-1 py-3 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 active:scale-95 transition-all"
>
</button>
<button
onClick={handleSave}
disabled={saving}
className="flex-1 py-3 rounded-xl text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-50"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
}}
>
{saving ? "저장 중..." : "저장"}
</button>
</div>
</div>
</div>
)}
{/* ===== Supplier Modal ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(supplier) => setSelectedSupplier(supplier)}
/>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Sub-components */
/* ------------------------------------------------------------------ */
function FieldGroup({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
<div>
<h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
{title}
</h3>
<div className="grid grid-cols-2 gap-3">{children}</div>
</div>
);
}
interface FormFieldProps {
label: string;
value: any;
onChange: (v: any) => void;
type?: "text" | "number" | "date" | "select";
options?: string[] | { value: string; label: string }[];
emptyLabel?: string;
readOnly?: boolean;
}
function FormField({
label,
value,
onChange,
type = "text",
options,
emptyLabel,
readOnly,
}: FormFieldProps) {
const baseClass =
"w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100";
return (
<div>
<label className="text-[11px] font-semibold text-gray-400 mb-1 block">
{label}
</label>
{type === "select" && options ? (
<select
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${baseClass} bg-white`}
>
{emptyLabel && <option value="">{emptyLabel}</option>}
{options.map((opt) => {
const v = typeof opt === "string" ? opt : opt.value;
const l = typeof opt === "string" ? opt : opt.label;
return (
<option key={v} value={v}>
{l}
</option>
);
})}
</select>
) : (
<input
type={type}
value={value}
onChange={(e) =>
onChange(
type === "number" ? Number(e.target.value) : e.target.value,
)
}
readOnly={readOnly}
className={`${baseClass} ${readOnly ? "bg-gray-50 text-gray-500" : ""}`}
/>
)}
</div>
);
}
@@ -0,0 +1,727 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { apiClient } from "@/lib/api/client";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface InspectionItem {
id: string;
inspection_item_name: string;
inspection_standard: string;
inspection_method: string;
pass_criteria: string;
is_required: string;
/** User-entered measured value */
measured_value: string;
/** "pass" | "fail" | null */
result: "pass" | "fail" | null;
}
export interface InspectionResult {
items: InspectionItem[];
goodQty: number;
badQty: number;
remark: string;
completed: boolean;
inspectionNumber?: string; // 검사 완료 시 채번 받음 (재사용)
}
interface InspectionModalProps {
open: boolean;
onClose: () => void;
onComplete: (result: InspectionResult) => void;
onCancel?: () => void; // 취소 = 검사 무효화 (완료 → 대기)
itemCode: string;
itemName: string;
totalQty: number;
initialResult?: InspectionResult | null;
}
/* ------------------------------------------------------------------ */
/* Dummy inspection items (fallback) */
/* ------------------------------------------------------------------ */
const DUMMY_INSPECTION_ITEMS: InspectionItem[] = [
{
id: "dummy-1",
inspection_item_name: "외관 검사",
inspection_standard: "스크래치, 변색, 찍힘 없음",
inspection_method: "육안 검사",
pass_criteria: "이상 없음",
is_required: "Y",
measured_value: "",
result: null,
},
{
id: "dummy-2",
inspection_item_name: "치수 검사",
inspection_standard: "규격 +-0.5mm",
inspection_method: "캘리퍼스 측정",
pass_criteria: "허용 오차 이내",
is_required: "Y",
measured_value: "",
result: null,
},
{
id: "dummy-3",
inspection_item_name: "수량 검사",
inspection_standard: "발주 수량과 일치",
inspection_method: "전수 검사",
pass_criteria: "수량 일치",
is_required: "Y",
measured_value: "",
result: null,
},
{
id: "dummy-4",
inspection_item_name: "포장 상태",
inspection_standard: "포장 손상 없음",
inspection_method: "육안 검사",
pass_criteria: "이상 없음",
is_required: "",
measured_value: "",
result: null,
},
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function InspectionModal({
open,
onClose,
onComplete,
onCancel,
itemCode,
itemName,
totalQty,
initialResult,
}: InspectionModalProps) {
const [inspItems, setInspItems] = useState<InspectionItem[]>([]);
const [loading, setLoading] = useState(false);
const [goodQty, setGoodQty] = useState(0);
const [badQty, setBadQty] = useState(0);
/* NumPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTitle, setNumpadTitle] = useState("");
const [numpadValue, setNumpadValue] = useState("");
const [numpadMax, setNumpadMax] = useState<number | undefined>(undefined);
const numpadCallbackRef = React.useRef<((val: string) => void) | null>(null);
const openNumpad = (
title: string,
currentValue: string | number,
onConfirm: (v: string) => void,
max?: number,
) => {
setNumpadTitle(title);
setNumpadValue(String(currentValue || ""));
setNumpadMax(max);
numpadCallbackRef.current = onConfirm;
setNumpadOpen(true);
};
const [remark, setRemark] = useState("");
/* Fetch inspection items from DB */
const fetchInspectionItems = useCallback(async () => {
setLoading(true);
try {
const res = await apiClient.get("/pop/inspection-result/info", {
params: { itemCode },
});
const data = res.data?.data;
if (Array.isArray(data) && data.length > 0) {
setInspItems(
data.map((r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
inspection_item_name: String(r.inspection_item_name ?? ""),
inspection_standard: String(r.inspection_standard ?? ""),
inspection_method: String(r.inspection_method ?? ""),
pass_criteria: String(r.pass_criteria ?? ""),
is_required: String(r.is_required ?? "Y"),
measured_value: "",
result: null,
})),
);
} else {
setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
}
} catch {
setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
} finally {
setLoading(false);
}
}, [itemCode]);
/* Init on open */
useEffect(() => {
if (!open) return;
if (initialResult) {
setInspItems(initialResult.items.map((i) => ({ ...i })));
setGoodQty(initialResult.goodQty);
setBadQty(initialResult.badQty);
setRemark(initialResult.remark);
} else {
fetchInspectionItems();
setGoodQty(totalQty);
setBadQty(0);
setRemark("");
}
}, [open, initialResult, fetchInspectionItems, totalQty]);
/* Update item */
const updateItem = (
id: string,
field: "measured_value" | "result",
value: string,
) => {
setInspItems((prev) =>
prev.map((item) =>
item.id === id
? {
...item,
[field]:
field === "result"
? item.result === value
? null
: value
: value,
}
: item,
),
);
};
/* Handle good/bad qty sync */
const handleGoodQtyChange = (val: number) => {
const v = Math.max(0, Math.min(val, totalQty));
setGoodQty(v);
setBadQty(totalQty - v);
};
const handleBadQtyChange = (val: number) => {
const v = Math.max(0, Math.min(val, totalQty));
setBadQty(v);
setGoodQty(totalQty - v);
};
/* 검사 완료 가능 여부: 필수 항목이 모두 pass */
const canComplete = inspItems
.filter((it) => it.is_required === "Y")
.every((it) => it.result === "pass");
/* Complete */
const [allocating, setAllocating] = useState(false);
const handleComplete = async () => {
if (!canComplete) return;
setAllocating(true);
try {
// 1. 기존 inspectionNumber 있으면 재사용, 없으면 채번 호출
let inspectionNumber = initialResult?.inspectionNumber;
if (!inspectionNumber) {
try {
const res = await apiClient.post(
"/pop/inspection-result/allocate-number",
);
inspectionNumber = res.data?.data?.inspectionNumber;
} catch (err) {
console.error("[검사번호 채번 실패]", err);
}
}
// 2. 결과 전달 (채번 포함)
onComplete({
items: inspItems,
goodQty,
badQty,
remark,
completed: true,
inspectionNumber,
});
onClose();
} finally {
setAllocating(false);
}
};
if (!open) return null;
return (
<div className="fixed inset-0 z-50" onClick={onClose}>
{/* Overlay */}
<div className="absolute inset-0 bg-black/40" />
{/* Bottom sheet */}
<div
className="absolute bottom-0 left-1/2 -translate-x-1/2 w-full max-w-2xl bg-white rounded-t-3xl shadow-2xl flex flex-col z-10"
style={{ maxHeight: "90vh" }}
onClick={(e) => e.stopPropagation()}
>
{/* Handle bar */}
<div className="pt-3 pb-2 flex justify-center rounded-t-3xl shrink-0">
<div className="w-10 h-1 rounded-full bg-gray-300" />
</div>
{/* Header */}
<div className="flex items-center justify-between px-5 pb-3 border-b border-gray-100 shrink-0">
<h3 className="text-lg font-bold text-gray-900"></h3>
<button
onClick={onClose}
className="w-9 h-9 rounded-lg flex items-center justify-center text-gray-400 hover:bg-gray-100 transition-colors"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Scrollable body */}
<div className="flex-1 overflow-y-auto px-5 py-4 bg-gray-50">
{/* Item summary */}
<div
className="flex flex-wrap items-center gap-2 px-3.5 py-2.5 mb-4 rounded-lg border border-sky-200"
style={{
background: "linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)",
}}
>
<span className="text-xs font-semibold text-sky-700 bg-white px-2 py-0.5 rounded shrink-0">
{itemCode}
</span>
<span className="text-sm font-semibold text-gray-900 flex-1 truncate min-w-0">
{itemName}
</span>
<span className="text-sm font-bold text-green-600 shrink-0">
{totalQty.toLocaleString()} EA
</span>
</div>
{/* Inspection items section */}
<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
<div className="flex items-center justify-between mb-3">
<h4 className="text-sm font-semibold text-gray-700"> </h4>
<span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">
{inspItems.length}
</span>
</div>
{loading ? (
<div className="flex items-center justify-center py-8 text-sm text-gray-400">
<svg
className="animate-spin w-5 h-5 mr-2 text-blue-500"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
...
</div>
) : inspItems.length === 0 ? (
<div className="text-center py-6 text-sm text-gray-400">
</div>
) : (
<div className="flex flex-col gap-2.5 max-h-[300px] overflow-y-auto">
{inspItems.map((item) => (
<div
key={item.id}
className={`bg-gray-50 border rounded-lg p-3 ${
item.is_required === "Y"
? "border-l-[3px] border-l-red-400 border-gray-200"
: "border-gray-200"
}`}
>
{/* Item header */}
<div className="flex items-start justify-between mb-2">
<span className="text-[13px] font-semibold text-gray-900">
{item.inspection_item_name}
</span>
{item.is_required === "Y" && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-600 font-semibold shrink-0 ml-2">
</span>
)}
</div>
{/* Info grid */}
<div className="grid grid-cols-[auto_1fr] gap-x-2.5 gap-y-1 text-xs mb-2.5">
{item.inspection_standard && (
<>
<span className="text-gray-400"></span>
<span className="text-gray-700">
{item.inspection_standard}
</span>
</>
)}
{item.inspection_method && (
<>
<span className="text-gray-400"></span>
<span className="text-gray-700">
{item.inspection_method}
</span>
</>
)}
{item.pass_criteria && (
<>
<span className="text-gray-400"></span>
<span className="text-gray-700">
{item.pass_criteria}
</span>
</>
)}
</div>
{/* Input + result buttons */}
<div className="flex items-center gap-2">
<button
type="button"
onClick={() =>
openNumpad(
`${item.inspection_item_name} - 측정값`,
item.measured_value,
(v) => updateItem(item.id, "measured_value", v),
)
}
className={`flex-1 h-9 px-2.5 text-[13px] border rounded-md text-left transition-all ${
item.measured_value
? "bg-blue-50 border-blue-200 text-blue-700 font-semibold"
: "bg-white border-gray-200 text-gray-400 hover:border-blue-300"
}`}
>
{item.measured_value || "측정값 입력"}
</button>
<div className="flex gap-1">
<button
onClick={() => updateItem(item.id, "result", "pass")}
className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
item.result === "pass"
? "bg-green-100 border-green-400 text-green-700"
: "border-gray-200 text-gray-400 hover:bg-green-50 hover:border-green-300"
}`}
>
{"\u2713"}
</button>
<button
onClick={() => updateItem(item.id, "result", "fail")}
className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
item.result === "fail"
? "bg-red-100 border-red-400 text-red-700"
: "border-gray-200 text-gray-400 hover:bg-red-50 hover:border-red-300"
}`}
>
{"\u2717"}
</button>
</div>
{/* Camera placeholder */}
<button
className="w-9 h-9 rounded-md border border-gray-200 text-gray-400 flex items-center justify-center hover:bg-gray-50 transition-colors"
title="사진 촬영 (준비 중)"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z"
/>
</svg>
</button>
</div>
</div>
))}
</div>
)}
</div>
{/* Final judgment section */}
<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
<h4 className="text-sm font-semibold text-gray-700 mb-3">
</h4>
{/* Good / Bad qty */}
<div className="grid grid-cols-2 gap-3 mb-3">
<div className="flex flex-col gap-1">
<label className="text-[11px] font-semibold text-green-600">
</label>
<div className="flex items-center gap-1">
<button
type="button"
onClick={() =>
openNumpad(
"양품 수량",
goodQty,
(v) => handleGoodQtyChange(parseInt(v, 10) || 0),
totalQty,
)
}
className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-green-400 rounded-lg bg-green-50 text-green-700 hover:bg-green-100 transition-all"
>
{goodQty.toLocaleString()}
</button>
<span className="text-[11px] text-gray-500 shrink-0">EA</span>
</div>
</div>
<div className="flex flex-col gap-1">
<label className="text-[11px] font-semibold text-red-600">
</label>
<div className="flex items-center gap-1">
<button
type="button"
onClick={() =>
openNumpad(
"불량 수량",
badQty,
(v) => handleBadQtyChange(parseInt(v, 10) || 0),
totalQty,
)
}
className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-red-400 rounded-lg bg-red-50 text-red-700 hover:bg-red-100 transition-all"
>
{badQty.toLocaleString()}
</button>
<span className="text-[11px] text-gray-500 shrink-0">EA</span>
</div>
</div>
</div>
{/* Total summary */}
<div className="flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg border border-gray-200">
<span className="text-[13px] text-gray-500"> </span>
<span className="text-[15px] font-bold text-gray-900">
{totalQty.toLocaleString()} EA
</span>
</div>
</div>
{/* Remark */}
<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
<h4 className="text-sm font-semibold text-gray-700 mb-2"></h4>
<textarea
value={remark}
onChange={(e) => setRemark(e.target.value)}
placeholder="검사 관련 특이사항 입력"
rows={3}
className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100 resize-none"
/>
</div>
</div>
{/* Footer */}
<div className="flex gap-2.5 px-5 py-4 border-t border-gray-200 bg-white shrink-0">
<button
onClick={() => {
if (initialResult?.completed && onCancel) {
// 이미 완료된 검사 → 무효화 (완료 → 대기로 풀림)
onCancel();
}
onClose();
}}
className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-50 active:scale-[0.98] transition-all"
>
{initialResult?.completed ? "검사 취소" : "취소"}
</button>
<button
className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-500 hover:bg-gray-50 active:scale-[0.98] transition-all"
title="준비 중"
>
</button>
<button
onClick={handleComplete}
disabled={!canComplete || allocating}
className={`flex-[2] h-12 rounded-xl text-sm font-bold text-white transition-all ${
!canComplete || allocating
? "opacity-40 cursor-not-allowed"
: "active:scale-[0.98]"
}`}
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
boxShadow:
!canComplete || allocating
? "none"
: "0 4px 12px rgba(59,130,246,.3)",
}}
title={
!canComplete
? "필수 검사 항목을 모두 합격(✓)으로 체크해주세요"
: ""
}
>
{allocating ? "처리 중..." : "검사 완료"}
</button>
</div>
</div>
{/* ===== NumPad ===== */}
{numpadOpen && (
<div
className="absolute inset-0 z-20 flex items-end justify-center"
onClick={() => setNumpadOpen(false)}
>
<div className="absolute inset-0 bg-black/40" />
<div
className="absolute bottom-0 left-1/2 -translate-x-1/2 w-full max-w-md bg-white rounded-t-3xl shadow-2xl flex flex-col z-30"
onClick={(e) => e.stopPropagation()}
>
<div className="pt-3 pb-2 flex justify-center">
<div className="w-10 h-1 rounded-full bg-gray-300" />
</div>
<div className="flex items-center justify-between px-5 pb-3 border-b border-gray-100">
<h4 className="text-base font-bold text-gray-900">
{numpadTitle}
</h4>
<button
onClick={() => setNumpadOpen(false)}
className="w-8 h-8 rounded-lg flex items-center justify-center text-gray-400 hover:bg-gray-100"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
<div className="px-5 pt-4 pb-2">
<div className="h-16 flex items-center justify-end px-4 bg-gray-50 rounded-xl border-2 border-gray-200 mb-3">
<span
className="text-3xl font-bold text-gray-900"
style={{ fontVariantNumeric: "tabular-nums" }}
>
{numpadValue || "0"}
</span>
</div>
{numpadMax !== undefined && (
<p className="text-[11px] text-gray-400 text-right mb-2">
{numpadMax.toLocaleString()}
</p>
)}
</div>
<div className="px-5 pb-5">
<div className="grid grid-cols-3 gap-2 mb-2">
{["7", "8", "9", "4", "5", "6", "1", "2", "3"].map((k) => (
<button
key={k}
onClick={() =>
setNumpadValue((v) => (v === "0" || v === "" ? k : v + k))
}
className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 active:bg-gray-200 transition-all"
>
{k}
</button>
))}
<button
onClick={() =>
setNumpadValue((v) =>
v.includes(".") ? v : (v || "0") + ".",
)
}
className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 transition-all"
>
.
</button>
<button
onClick={() =>
setNumpadValue((v) =>
v === "0" || v === "" ? "0" : v + "0",
)
}
className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 transition-all"
>
0
</button>
<button
onClick={() =>
setNumpadValue((v) => (v.length <= 1 ? "" : v.slice(0, -1)))
}
className="h-14 rounded-xl bg-gray-200 text-base font-bold text-gray-600 active:scale-95 transition-all"
>
</button>
</div>
<div className="flex gap-2 mb-3">
<button
onClick={() => setNumpadValue("")}
className="flex-1 h-11 rounded-xl bg-gray-100 text-gray-600 text-sm font-bold active:scale-95"
>
</button>
{numpadMax !== undefined && (
<button
onClick={() => setNumpadValue(String(numpadMax))}
className="flex-1 h-11 rounded-xl bg-blue-50 text-blue-600 text-sm font-bold active:scale-95"
>
({numpadMax})
</button>
)}
</div>
<button
onClick={() => {
if (numpadCallbackRef.current) {
let val = numpadValue;
if (numpadMax !== undefined) {
const n = parseInt(val, 10) || 0;
val = String(Math.min(n, numpadMax));
}
numpadCallbackRef.current(val);
}
setNumpadOpen(false);
}}
className="w-full h-12 rounded-xl text-sm font-bold text-white active:scale-95 transition-all"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
}}
>
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,178 @@
"use client";
import React, { useEffect, useState } from "react";
import { getLoadingUnitsByPkg, type LoadingUnitByPkg } from "@/lib/api/packaging";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface LoadingUnitSelection {
loading_code: string;
loading_name: string;
loading_type: string;
max_load_qty: number;
}
interface LoadingUnitModalProps {
open: boolean;
onClose: () => void;
onSelect: (lu: LoadingUnitSelection) => void;
onClear: () => void;
pkgCodes: string[];
currentLoading?: { loading_code: string; loading_name: string } | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function LoadingUnitModal({
open,
onClose,
onSelect,
onClear,
pkgCodes,
currentLoading,
}: LoadingUnitModalProps) {
const [units, setUnits] = useState<LoadingUnitByPkg[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!open || pkgCodes.length === 0) return;
let cancelled = false;
setLoading(true);
const uniqueCodes = [...new Set(pkgCodes)];
Promise.all(uniqueCodes.map((code) => getLoadingUnitsByPkg(code)))
.then((results) => {
if (cancelled) return;
const merged = new Map<string, LoadingUnitByPkg>();
results.forEach((res) => {
res.data.forEach((lu) => {
if (!merged.has(lu.loading_code)) {
merged.set(lu.loading_code, lu);
}
});
});
setUnits(Array.from(merged.values()));
})
.catch(() => {
if (!cancelled) setUnits([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, pkgCodes]);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
<div
className="absolute inset-0 bg-black/50"
onClick={onClose}
/>
<div className="relative bg-white w-full sm:max-w-md sm:rounded-2xl rounded-t-2xl max-h-[80vh] flex flex-col shadow-2xl z-10 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<h3 className="text-lg font-bold text-gray-900">
</h3>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Body */}
<div className="flex-1 overflow-y-auto p-4">
{loading ? (
<div className="flex items-center justify-center py-8">
<div className="w-6 h-6 border-2 border-purple-500 border-t-transparent rounded-full animate-spin" />
<span className="ml-2 text-sm text-gray-500">
...
</span>
</div>
) : units.length === 0 ? (
<p className="text-center text-sm text-gray-400 py-8">
</p>
) : (
<div className="flex flex-col gap-2.5">
{units.map((lu) => (
<button
key={lu.loading_code}
onClick={() => {
onSelect({
loading_code: lu.loading_code,
loading_name: lu.loading_name,
loading_type: lu.loading_type,
max_load_qty: lu.max_load_qty,
});
onClose();
}}
className={`flex items-center gap-3 p-3 border-2 rounded-xl bg-white text-left active:scale-[0.98] transition-all ${
currentLoading?.loading_code === lu.loading_code
? "border-purple-400 bg-purple-50"
: "border-gray-200 hover:border-purple-400 hover:bg-purple-50"
}`}
>
<span className="text-2xl shrink-0">
{"\uD83D\uDEA2"}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-900 truncate">
{lu.loading_name}
</p>
<p className="text-[11px] text-gray-400">
{lu.loading_code} |{" "}
{lu.loading_type || "-"}
</p>
</div>
{lu.max_load_qty > 0 && (
<span className="text-[10px] font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full shrink-0">
{lu.max_load_qty}
</span>
)}
</button>
))}
</div>
)}
</div>
{/* Footer — 해제 버튼 (적재함 이미 선택된 경우) */}
{currentLoading && (
<div className="px-4 pb-4">
<button
onClick={() => {
onClear();
onClose();
}}
className="w-full py-3 rounded-xl border-2 border-dashed border-gray-300 text-sm font-medium text-gray-500 hover:border-gray-400 hover:bg-gray-50 active:scale-[0.98] transition-all"
>
</button>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,598 @@
"use client";
import React, { useState, useCallback, useEffect } from "react";
import type { PackageUnit } from "./PackagingModal";
import { getPkgUnitsByItem, type PkgUnitByItem } from "@/lib/api/packaging";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface PackageEntry {
unit: PackageUnit;
count: number;
qtyPerUnit: number;
}
export interface LoadingUnitSelection {
loading_code: string;
loading_name: string;
loading_type: string;
max_load_qty: number;
}
interface NumberPadModalProps {
open: boolean;
onClose: () => void;
onConfirm: (qty: number, packages: PackageEntry[]) => void;
maxQty: number;
itemName: string;
itemNumber?: string;
initialPackages?: PackageEntry[];
}
type Step =
| "packaging"
| "qty-per-pkg"
| "pkg-count"
| "remainder"
| "rem-packaging"
| "rem-qty-per-pkg"
| "rem-pkg-count"
| "confirm";
/* ------------------------------------------------------------------ */
/* Numpad Keys */
/* ------------------------------------------------------------------ */
const KEYS = [
{ label: "7", action: "7" },
{ label: "8", action: "8" },
{ label: "9", action: "9" },
{ label: "\u2190", action: "backspace" },
{ label: "4", action: "4" },
{ label: "5", action: "5" },
{ label: "6", action: "6" },
{ label: "C", action: "clear" },
{ label: "1", action: "1" },
{ label: "2", action: "2" },
{ label: "3", action: "3" },
{ label: "MAX", action: "max" },
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function NumberPadModal({
open,
onClose,
onConfirm,
maxQty,
itemName,
itemNumber,
initialPackages,
}: NumberPadModalProps) {
const [step, setStep] = useState<Step>("packaging");
// 1차 포장
const [selectedUnit, setSelectedUnit] = useState<PackageUnit | null>(null);
const [pkgCount, setPkgCount] = useState("0");
const [qtyPerPkg, setQtyPerPkg] = useState("0");
// 나머지 포장
const [remUnit, setRemUnit] = useState<PackageUnit | null>(null);
const [remPkgCount, setRemPkgCount] = useState("0");
const [remQtyPerPkg, setRemQtyPerPkg] = useState("0");
const [packageUnits, setPackageUnits] = useState<PackageUnit[]>([]);
const [pkgLoading, setPkgLoading] = useState(false);
/* Fetch packaging units from DB */
useEffect(() => {
if (!open || !itemNumber) {
setPackageUnits([]);
return;
}
let cancelled = false;
setPkgLoading(true);
getPkgUnitsByItem(itemNumber)
.then((res) => {
if (cancelled) return;
setPackageUnits(
res.data.map((pu: PkgUnitByItem) => ({
label: pu.pkg_name,
icon: "\uD83D\uDCE6",
value: pu.pkg_code,
pkg_qty: pu.pkg_qty,
}))
);
})
.catch(() => { if (!cancelled) setPackageUnits([]); })
.finally(() => { if (!cancelled) setPkgLoading(false); });
return () => { cancelled = true; };
}, [open, itemNumber]);
/* Reset on open */
useEffect(() => {
if (open) {
if (initialPackages && initialPackages.length > 0) {
const p = initialPackages[0];
setSelectedUnit(p.unit);
setPkgCount(String(p.count));
setQtyPerPkg(String(p.qtyPerUnit));
if (initialPackages.length > 1) {
const r = initialPackages[1];
setRemUnit(r.unit);
setRemPkgCount(String(r.count));
setRemQtyPerPkg(String(r.qtyPerUnit));
} else {
setRemUnit(null);
setRemPkgCount("0");
setRemQtyPerPkg("0");
}
setStep("confirm");
} else {
setStep("packaging");
setSelectedUnit(null);
setPkgCount("0");
setQtyPerPkg("0");
setRemUnit(null);
setRemPkgCount("0");
setRemQtyPerPkg("0");
}
}
}, [open, initialPackages]);
/* Computed values */
const pkgCountNum = parseInt(pkgCount, 10) || 0;
const qtyPerPkgNum = parseInt(qtyPerPkg, 10) || 0;
const primaryQty = pkgCountNum * qtyPerPkgNum;
const remPkgCountNum = parseInt(remPkgCount, 10) || 0;
const remQtyPerPkgNum = parseInt(remQtyPerPkg, 10) || 0;
const remQty = remUnit ? remPkgCountNum * remQtyPerPkgNum : 0;
const remainder = qtyPerPkgNum > 0 ? maxQty - primaryQty : 0;
const totalQty = primaryQty + remQty;
const isOverMax = totalQty > maxQty;
/* Generic numpad input handler */
const handleInput = useCallback(
(key: string, setter: React.Dispatch<React.SetStateAction<string>>, max?: number) => {
setter((prev) => {
switch (key) {
case "backspace":
return prev.length <= 1 ? "0" : prev.slice(0, -1);
case "clear":
return "0";
case "max":
return String(max ?? maxQty);
default: {
const next = prev === "0" ? key : prev + key;
const num = parseInt(next, 10);
if (isNaN(num)) return prev;
if (max !== undefined) return String(Math.min(num, max));
return next;
}
}
});
},
[maxQty]
);
/* 1차 포장 handlers */
const handleSelectPackaging = (unit: PackageUnit) => {
setSelectedUnit(unit);
setPkgCount("0");
setQtyPerPkg(unit.pkg_qty ? String(unit.pkg_qty) : "0");
setStep("qty-per-pkg");
};
const handleQtyPerPkgConfirm = () => {
if (qtyPerPkgNum <= 0) return;
setStep("pkg-count");
};
const handlePkgCountConfirm = () => {
if (pkgCountNum <= 0 || !selectedUnit) return;
const rem = maxQty - pkgCountNum * qtyPerPkgNum;
if (rem > 0) {
setStep("remainder");
} else {
setRemUnit(null);
setRemPkgCount("0");
setRemQtyPerPkg("0");
setStep("confirm");
}
};
/* 나머지 포장 handlers */
const handleRemSelectPackaging = (unit: PackageUnit) => {
if (!selectedUnit) return;
setRemUnit(unit);
setRemQtyPerPkg(String(remainder));
setRemPkgCount("1");
setStep("confirm");
};
const handleRemQtyPerPkgConfirm = () => {
if (remQtyPerPkgNum <= 0) return;
setStep("rem-pkg-count");
};
const handleRemPkgCountConfirm = () => {
if (remPkgCountNum <= 0 || !selectedUnit) return;
setStep("confirm");
};
const handleSkipRemainder = () => {
if (!selectedUnit) return;
setRemUnit(null);
setRemPkgCount("0");
setRemQtyPerPkg("0");
setStep("confirm");
};
/* 최종 확인 */
const handleFinalConfirm = () => {
if (primaryQty <= 0 || !selectedUnit) return;
const finalQty = Math.min(totalQty, maxQty);
const packages: PackageEntry[] = [
{ unit: selectedUnit, count: pkgCountNum, qtyPerUnit: qtyPerPkgNum },
];
if (remUnit && remQty > 0) {
packages.push({ unit: remUnit, count: remPkgCountNum, qtyPerUnit: remQtyPerPkgNum });
}
onConfirm(finalQty, packages);
onClose();
};
/* Back navigation */
const handleBack = () => {
switch (step) {
case "qty-per-pkg": setStep("packaging"); break;
case "pkg-count": setStep("qty-per-pkg"); break;
case "remainder": setStep("pkg-count"); break;
case "rem-packaging": setStep("remainder"); break;
case "rem-qty-per-pkg": setStep("rem-packaging"); break;
case "rem-pkg-count": setStep("rem-qty-per-pkg"); break;
case "confirm":
if (remUnit) setStep("remainder");
else if (remainder > 0) setStep("remainder");
else setStep("pkg-count");
break;
}
};
if (!open) return null;
/* Render numpad grid */
const renderNumpad = (
currentValue: string,
onKey: (key: string) => void,
onConfirmStep: () => void,
confirmLabel: string,
confirmDisabled: boolean,
) => (
<>
<input
type="text"
readOnly
value={parseInt(currentValue, 10).toLocaleString()}
className="w-full px-4 py-3 text-right text-3xl font-bold border-2 border-gray-200 rounded-xl bg-gray-50 text-gray-900 mb-3"
style={{ fontVariantNumeric: "tabular-nums" }}
/>
<div className="grid grid-cols-4 gap-2.5">
{KEYS.map((key) => (
<button
key={key.action}
onClick={() => onKey(key.action)}
className={`h-14 rounded-xl text-lg font-semibold active:scale-95 transition-all ${
key.action === "backspace" || key.action === "clear"
? "bg-amber-100 text-amber-700 hover:bg-amber-200"
: key.action === "max"
? "bg-blue-100 text-blue-700 hover:bg-blue-200 text-sm"
: "bg-gray-100 text-gray-900 hover:bg-gray-200"
}`}
>
{key.label}
</button>
))}
<button
onClick={() => onKey("0")}
className="col-span-2 h-14 rounded-xl text-lg font-semibold bg-gray-100 text-gray-900 hover:bg-gray-200 active:scale-95 transition-all"
>
0
</button>
<button
onClick={onConfirmStep}
disabled={confirmDisabled}
className={`col-span-2 h-14 rounded-xl text-lg font-bold text-white active:scale-95 transition-all ${
confirmDisabled ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: confirmDisabled
? "#9ca3af"
: "linear-gradient(135deg, #10b981 0%, #059669 100%)",
}}
>
{confirmLabel}
</button>
</div>
</>
);
/* Render packaging grid */
const renderPackagingGrid = (onSelect: (unit: PackageUnit) => void) => (
<>
{pkgLoading ? (
<div className="flex items-center justify-center py-8">
<div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
<span className="ml-2 text-sm text-gray-500"> ...</span>
</div>
) : packageUnits.length === 0 ? (
<div className="text-center py-8 text-sm text-gray-400">
</div>
) : (
<div className="grid grid-cols-3 gap-3">
{packageUnits.map((unit) => (
<button
key={unit.value}
onClick={() => onSelect(unit)}
className="flex flex-col items-center gap-2 py-4 px-3 border-2 border-gray-200 rounded-xl bg-white text-sm font-medium text-gray-700 hover:border-blue-400 hover:bg-blue-50 active:scale-95 transition-all min-h-[80px]"
>
<span className="text-2xl">{unit.icon}</span>
<span className="text-center leading-tight">{unit.label}</span>
{unit.pkg_qty && unit.pkg_qty > 0 && (
<span className="text-[10px] text-gray-400">{unit.pkg_qty}EA/</span>
)}
</button>
))}
</div>
)}
</>
);
/* Header color */
const isRemStep = step.startsWith("rem") || step === "remainder";
const headerBg = isRemStep
? "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)"
: "linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)";
return (
<div className="fixed inset-0 z-50 flex items-center justify-center">
<div className="absolute inset-0 bg-black/40" onClick={onClose} />
<div className="relative bg-white w-[90%] max-w-[360px] rounded-2xl shadow-2xl z-10 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3" style={{ background: headerBg }}>
<div className="flex items-center gap-2">
{step !== "packaging" && (
<button
onClick={handleBack}
className="w-8 h-8 rounded-lg bg-white/20 flex items-center justify-center text-white hover:bg-white/30 active:scale-95 transition-all"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
)}
<span className="text-[13px] text-white/90 bg-white/20 px-3 py-1 rounded-full">
{isRemStep ? `나머지 ${remainder.toLocaleString()} EA`
: `최대 ${maxQty.toLocaleString()} EA`
}
</span>
</div>
</div>
{/* Body */}
<div className="p-4">
{/* ====== 1차: 포장 선택 ====== */}
{step === "packaging" && (
<>
<p className="text-center text-sm font-semibold text-gray-700 mb-4">
</p>
{renderPackagingGrid(handleSelectPackaging)}
</>
)}
{/* ====== 1차: 개당 수량 ====== */}
{step === "qty-per-pkg" && selectedUnit && (
<>
<p className="text-center text-sm font-semibold text-gray-700 mb-1">
{selectedUnit.icon} {selectedUnit.label} 1 ?
</p>
<p className="text-center text-xs text-gray-400 mb-3">
(EA)
</p>
{renderNumpad(
qtyPerPkg,
(key) => handleInput(key, setQtyPerPkg, maxQty),
handleQtyPerPkgConfirm,
"다음",
qtyPerPkgNum <= 0,
)}
</>
)}
{/* ====== 1차: 포장 개수 ====== */}
{step === "pkg-count" && selectedUnit && (
<>
<p className="text-center text-sm font-semibold text-gray-700 mb-1">
{selectedUnit.icon} {selectedUnit.label} ?
</p>
<p className="text-center text-xs text-gray-400 mb-3">
</p>
{renderNumpad(
pkgCount,
(key) => handleInput(key, setPkgCount, qtyPerPkgNum > 0 ? Math.floor(maxQty / qtyPerPkgNum) : 9999),
handlePkgCountConfirm,
"다음",
pkgCountNum <= 0,
)}
{pkgCountNum > 0 && qtyPerPkgNum > 0 && (
<div className={`mt-3 text-center text-sm font-semibold px-3 py-2 rounded-lg ${
pkgCountNum * qtyPerPkgNum > maxQty
? "bg-red-50 text-red-600 border border-red-200"
: "bg-blue-50 text-blue-700 border border-blue-200"
}`}>
{pkgCountNum}{selectedUnit.label} x {qtyPerPkgNum.toLocaleString()}EA = {(pkgCountNum * qtyPerPkgNum).toLocaleString()}EA
{pkgCountNum * qtyPerPkgNum > maxQty && (
<span className="block text-xs mt-0.5"> </span>
)}
</div>
)}
</>
)}
{/* ====== 나머지 안내 ====== */}
{step === "remainder" && selectedUnit && (
<div className="text-center py-2">
<div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 border border-blue-200 rounded-lg mb-4">
<span className="text-sm font-semibold text-blue-700">
{pkgCountNum}{selectedUnit.label} x {qtyPerPkgNum.toLocaleString()}EA = {primaryQty.toLocaleString()}EA
</span>
</div>
<p className="text-lg font-bold text-amber-600 mb-1">
{remainder.toLocaleString()}EA
</p>
<p className="text-sm text-gray-500 mb-6">
?
</p>
<div className="flex gap-3">
<button
onClick={handleSkipRemainder}
className="flex-1 h-14 rounded-xl text-base font-semibold bg-gray-100 text-gray-700 hover:bg-gray-200 active:scale-95 transition-all"
>
</button>
<button
onClick={() => setStep("rem-packaging")}
className="flex-1 h-14 rounded-xl text-base font-bold text-white active:scale-95 transition-all"
style={{ background: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)" }}
>
</button>
</div>
</div>
)}
{/* ====== 나머지: 포장 선택 ====== */}
{step === "rem-packaging" && (
<>
<p className="text-center text-sm font-semibold text-amber-700 mb-1">
{remainder.toLocaleString()}EA
</p>
<p className="text-center text-xs text-gray-400 mb-4">
1 x {remainder.toLocaleString()}EA로
</p>
{renderPackagingGrid(handleRemSelectPackaging)}
</>
)}
{/* ====== 나머지: 개당 수량 (수동 편집) ====== */}
{step === "rem-qty-per-pkg" && remUnit && (
<>
<p className="text-center text-sm font-semibold text-amber-700 mb-1">
{remUnit.icon} {remUnit.label} 1 ?
</p>
<p className="text-center text-xs text-gray-400 mb-3"> (EA) </p>
{renderNumpad(
remQtyPerPkg,
(key) => handleInput(key, setRemQtyPerPkg, remainder),
handleRemQtyPerPkgConfirm,
"다음",
remQtyPerPkgNum <= 0,
)}
</>
)}
{/* ====== 나머지: 포장 개수 (수동 편집) ====== */}
{step === "rem-pkg-count" && remUnit && (
<>
<p className="text-center text-sm font-semibold text-amber-700 mb-1">
{remUnit.icon} {remUnit.label} ?
</p>
<p className="text-center text-xs text-gray-400 mb-3"> </p>
{renderNumpad(
remPkgCount,
(key) => handleInput(key, setRemPkgCount, remQtyPerPkgNum > 0 ? Math.ceil(remainder / remQtyPerPkgNum) : 9999),
handleRemPkgCountConfirm,
"다음",
remPkgCountNum <= 0,
)}
</>
)}
{/* ====== 최종 확인 ====== */}
{step === "confirm" && selectedUnit && (
<>
<div className="flex flex-col items-center gap-2.5 py-3">
<p className="text-sm font-semibold text-gray-500"> </p>
{/* 1차 포장 */}
<div className="w-full bg-gradient-to-br from-green-50 to-emerald-50 border border-green-200 rounded-xl p-3 text-center">
<p className="text-2xl mb-1">{selectedUnit.icon}</p>
<p className="text-base font-bold text-gray-900">
{pkgCountNum}{selectedUnit.label} x {qtyPerPkgNum.toLocaleString()}EA
</p>
<p className="text-lg font-black text-green-600" style={{ fontVariantNumeric: "tabular-nums" }}>
= {primaryQty.toLocaleString()} EA
</p>
</div>
{/* 나머지 포장 */}
{remUnit && remQty > 0 && (
<div className="w-full bg-gradient-to-br from-amber-50 to-orange-50 border border-amber-200 rounded-xl p-3 text-center">
<p className="text-[10px] font-bold text-amber-600 mb-1"> </p>
<p className="text-2xl mb-1">{remUnit.icon}</p>
<p className="text-base font-bold text-gray-900">
{remPkgCountNum}{remUnit.label} x {remQtyPerPkgNum.toLocaleString()}EA
</p>
<p className="text-lg font-black text-amber-600" style={{ fontVariantNumeric: "tabular-nums" }}>
= {remQty.toLocaleString()} EA
</p>
</div>
)}
{/* 합계 */}
<div className={`w-full py-2 text-center rounded-lg font-black text-xl ${
isOverMax ? "bg-red-50 text-red-500 border border-red-200" : "text-gray-900"
}`} style={{ fontVariantNumeric: "tabular-nums" }}>
{totalQty.toLocaleString()} EA
{isOverMax && (
<p className="text-xs font-medium mt-0.5"> {maxQty.toLocaleString()}EA로 </p>
)}
</div>
<p className="text-xs text-gray-400 truncate max-w-full px-2">{itemName}</p>
</div>
<div className="flex gap-3">
<button
onClick={() => setStep("packaging")}
className="flex-1 h-14 rounded-xl text-base font-semibold bg-gray-100 text-gray-700 hover:bg-gray-200 active:scale-95 transition-all"
>
</button>
<button
onClick={handleFinalConfirm}
className="flex-1 h-14 rounded-xl text-base font-bold text-white active:scale-95 transition-all"
style={{ background: "linear-gradient(135deg, #10b981 0%, #059669 100%)" }}
>
</button>
</div>
</>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,122 @@
"use client";
import React, { useEffect, useState } from "react";
import { getPkgUnitsByItem, type PkgUnitByItem } from "@/lib/api/packaging";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
export interface PackageUnit {
label: string;
icon: string;
value: string;
pkg_qty?: number;
}
interface PackagingModalProps {
open: boolean;
onClose: () => void;
onSelect: (unit: PackageUnit) => void;
itemNumber?: string;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function PackagingModal({ open, onClose, onSelect, itemNumber }: PackagingModalProps) {
const [units, setUnits] = useState<PackageUnit[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!open || !itemNumber) {
setUnits([]);
return;
}
let cancelled = false;
setLoading(true);
getPkgUnitsByItem(itemNumber)
.then((res) => {
if (cancelled) return;
const mapped: PackageUnit[] = res.data.map((pu: PkgUnitByItem) => ({
label: pu.pkg_name,
icon: "\uD83D\uDCE6",
value: pu.pkg_code,
pkg_qty: pu.pkg_qty,
}));
setUnits(mapped);
})
.catch(() => {
if (!cancelled) setUnits([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, [open, itemNumber]);
if (!open) return null;
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center">
{/* Overlay */}
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
{/* Panel */}
<div className="relative bg-white w-[90%] max-w-[360px] rounded-2xl shadow-2xl z-10 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<h3 className="text-lg font-bold text-gray-900">
<span className="mr-1.5">{"\uD83D\uDCE6"}</span>
</h3>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Body */}
<div className="p-5">
{loading ? (
<div className="flex items-center justify-center py-8">
<div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
<span className="ml-2 text-sm text-gray-500"> ...</span>
</div>
) : units.length === 0 ? (
<div className="text-center py-8 text-sm text-gray-400">
</div>
) : (
<div className="grid grid-cols-3 gap-3">
{units.map((unit) => (
<button
key={unit.value}
onClick={() => {
onSelect(unit);
onClose();
}}
className="flex flex-col items-center gap-2 py-4 px-3 border-2 border-gray-200 rounded-xl bg-white text-sm font-medium text-gray-700 hover:border-blue-400 hover:bg-blue-50 active:scale-95 transition-all min-h-[80px]"
>
<span className="text-2xl">{unit.icon}</span>
<span className="text-center leading-tight">{unit.label}</span>
{unit.pkg_qty && unit.pkg_qty > 0 && (
<span className="text-[10px] text-gray-400">{unit.pkg_qty}EA/</span>
)}
</button>
))}
</div>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,688 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { apiClient } from "@/lib/api/client";
import { SupplierModal, type Supplier, type PartnerSourceConfig, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ProductionOrder {
id: string;
work_instruction_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ProductionInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_process_production";
/** process_mng 테이블 소스 설정 — SupplierModal에 전달하여 공정 목록 조회 */
const PROCESS_SOURCE: PartnerSourceConfig = {
tableName: "process_mng",
fields: {
code: "process_code",
name: "process_name",
},
};
export function ProductionInbound({ cart, onCartClick, saving, inboundType, sourceTable }: ProductionInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<ProductionOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<ProductionOrder | null>(null);
/* Per-order edited quantities (before adding to cart) */
const [editedQtys, setEditedQtys] = useState<Record<string, number>>({});
/* Ref to always call the latest saveToDb (avoids stale closure in setTimeout) */
const saveToDbRef = useRef(cart.saveToDb);
useEffect(() => { saveToDbRef.current = cart.saveToDb; });
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all processes for inline search — process_mng 테이블 조회 */
const fetchAllSuppliers = useCallback(async () => {
try {
const res = await apiClient.post("/table-management/tables/process_mng/data", {
page: 1,
size: 500,
autoFilter: true,
sort: { columnName: "process_code", order: "asc" },
});
const data = res.data?.data?.data ?? res.data?.data?.rows ?? [];
const list: Supplier[] = (Array.isArray(data) ? data : []).map((r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
customer_name: String(r.process_name ?? ""),
customer_code: String(r.process_code ?? ""),
}));
setAllSuppliers(list);
} catch {
setAllSuppliers([]);
}
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 공정 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 공정 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch production results — 선택된 공정의 실적 등록된 작업지시 조회 */
const fetchOrders = useCallback(async (searchKeyword?: string) => {
if (!selectedSupplier) {
setOrders([]);
return;
}
setLoading(true);
setFetchError(null);
try {
const params: Record<string, string> = {
processCode: selectedSupplier.customer_code,
pageSize: "50",
};
if (searchKeyword) params.keyword = searchKeyword;
const res = await apiClient.get("/receiving/source/production-results", { params });
const data = res.data?.data;
if (Array.isArray(data) && data.length > 0) {
setOrders(data.map((r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
work_instruction_no: String(r.work_instruction_no ?? ""),
order_date: String(r.order_date ?? "").slice(0, 10),
supplier_code: String(r.process_code ?? ""),
supplier_name: String(r.process_name ?? ""),
item_code: String(r.item_code ?? ""),
item_name: String(r.item_name ?? ""),
spec: String(r.spec ?? ""),
material: String(r.material ?? ""),
order_qty: Number(r.order_qty ?? 0),
received_qty: Number(r.received_qty ?? 0),
remain_qty: Number(r.remain_qty ?? 0),
unit_price: 0,
status: String(r.result_status ?? ""),
due_date: "",
source_table: String(r.source_table ?? "work_order_process"),
inspection_type: r.inspection_type === "self" ? "self"
: r.inspection_type === "request" ? "request"
: null,
image: r.image ? String(r.image) : null,
})));
} else {
setOrders([]);
}
} catch {
setOrders([]);
setFetchError("데이터를 불러오지 못했습니다. 네트워크 상태를 확인해주세요.");
} finally {
setLoading(false);
}
}, [selectedSupplier]);
/* 공정 선택 변경 시 자동 재조회 */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter by keyword (프론트 필터링) */
const displayOrders = keyword
? orders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.work_instruction_no.toLowerCase().includes(keyword.toLowerCase())
)
: orders;
/* Open numpad for an order */
const openNumpad = (order: ProductionOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Numpad confirm: only update local edited qty (do NOT add to cart) */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const finalQty = Math.min(qty, numpadTarget.remain_qty);
setEditedQtys((prev) => ({ ...prev, [numpadTarget.id]: finalQty }));
setNumpadTarget(null);
};
/* Add to cart with currently displayed qty */
const handleAddToCart = (order: ProductionOrder) => {
if (cart.isItemInCart(order.id)) return;
// 공정 검증: 카트에 이미 다른 공정 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 공정의 품목이 이미 장바구니에 있습니다.\n같은 공정의 품목만 담을 수 있습니다.");
return;
}
}
const displayQty = editedQtys[order.id] ?? order.remain_qty;
const finalQty = Math.min(displayQty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.work_instruction_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setEditedQtys((prev) => {
const next = { ...prev };
delete next[order.id];
return next;
});
setTimeout(() => saveToDbRef.current().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => saveToDbRef.current().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 생산입고 라인, 발주품목 위. 테마 green */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #4ade80, #16a34a)",
boxShadow: "0 4px 12px rgba(22,163,74,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "공정을 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #4ade80, #16a34a)",
boxShadow: "0 4px 12px rgba(34,197,94,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-green-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 생산지시번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-green-400 focus:ring-2 focus:ring-green-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #4ade80, #16a34a)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(34,197,94,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-green-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 공정의 생산 품목이 없습니다" : "공정을 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-green-500 rounded-lg hover:bg-green-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-green-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-green-100 text-green-700 border border-green-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.work_instruction_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad (edit qty before adding) */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: editedQtys[order.id] !== undefined
? "bg-green-50 border-green-300 hover:bg-green-100 cursor-pointer active:scale-95"
: "bg-green-50 border-green-200 hover:bg-green-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${
inCart ? "text-gray-400"
: editedQtys[order.id] !== undefined ? "text-green-700"
: "text-green-700"
}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: (editedQtys[order.id] ?? order.remain_qty).toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => handleAddToCart(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
source={PROCESS_SOURCE}
title="공정 선택"
searchPlaceholder="공정명 또는 코드 검색..."
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="공정"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="생산 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,693 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { apiClient } from "@/lib/api/client";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface PurchaseOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Dummy data (fallback) */
/* ------------------------------------------------------------------ */
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface PurchaseInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 (예: "구매입고") — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 (예: "purchase_detail") — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_purchase";
export function PurchaseInbound({ cart, onCartClick, saving, inboundType, sourceTable }: PurchaseInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<PurchaseOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<PurchaseOrder | null>(null);
/* Per-order edited quantities (before adding to cart) */
const [editedQtys, setEditedQtys] = useState<Record<string, number>>({});
/* Ref to always call the latest saveToDb (avoids stale closure in setTimeout) */
const saveToDbRef = useRef(cart.saveToDb);
useEffect(() => { saveToDbRef.current = cart.saveToDb; });
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search (supplier_mng = 공급사)
* 구매관리 > 공급업체관리 화면과 동일한 API로 맞춤 (autoFilter 적용)
*/
const fetchAllSuppliers = useCallback(async () => {
try {
const res = await apiClient.post("/table-management/tables/supplier_mng/data", {
page: 1,
size: 500,
autoFilter: true,
sort: { columnName: "supplier_code", order: "desc" },
});
const data =
res.data?.data?.data ?? res.data?.data?.rows ?? [];
const list: Supplier[] = (Array.isArray(data) ? data : []).map((r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
customer_name: String(r.supplier_name ?? r.customer_name ?? r.name ?? ""),
customer_code: String(r.supplier_code ?? r.customer_code ?? r.code ?? ""),
business_number: String(r.business_number ?? ""),
phone: String(r.contact_phone ?? r.phone ?? ""),
address: String(r.address ?? ""),
}));
setAllSuppliers(list);
} catch {
setAllSuppliers([]);
}
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch purchase orders */
const fetchOrders = useCallback(async (searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
const params: Record<string, string> = { pageSize: "50" };
if (searchKeyword) params.keyword = searchKeyword;
const res = await apiClient.get("/receiving/source/purchase-orders", { params });
const data = res.data?.data;
if (Array.isArray(data) && data.length > 0) {
setOrders(data.map((r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
purchase_no: String(r.purchase_no ?? ""),
order_date: String(r.order_date ?? "").slice(0, 10),
supplier_code: String(r.supplier_code ?? ""),
supplier_name: String(r.supplier_name ?? ""),
item_code: String(r.item_code ?? ""),
item_name: String(r.item_name ?? ""),
spec: String(r.spec ?? ""),
material: String(r.material ?? ""),
order_qty: Number(r.order_qty ?? 0),
received_qty: Number(r.received_qty ?? 0),
remain_qty: Number(r.remain_qty ?? 0),
unit_price: Number(r.unit_price ?? 0),
status: String(r.status ?? ""),
due_date: String(r.due_date ?? "").slice(0, 10),
source_table: String(r.source_table ?? "purchase_detail"),
inspection_type: r.inspection_type === "self" ? "self"
: r.inspection_type === "request" ? "request"
: null,
image: r.image ? String(r.image) : null,
})));
} else {
setOrders([]);
}
} catch {
setOrders([]);
setFetchError("데이터를 불러오지 못했습니다. 네트워크 상태를 확인해주세요.");
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: PurchaseOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Numpad confirm: only update local edited qty (do NOT add to cart) */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const finalQty = Math.min(qty, numpadTarget.remain_qty);
setEditedQtys((prev) => ({ ...prev, [numpadTarget.id]: finalQty }));
setNumpadTarget(null);
};
/* Add to cart with currently displayed qty */
const handleAddToCart = (order: PurchaseOrder) => {
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
return;
}
}
const displayQty = editedQtys[order.id] ?? order.remain_qty;
const finalQty = Math.min(displayQty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
// 담긴 후 editedQtys에서 제거
setEditedQtys((prev) => {
const next = { ...prev };
delete next[order.id];
return next;
});
setTimeout(() => saveToDbRef.current().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => saveToDbRef.current().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 구매입고 라인, 발주품목 위. 스캐너 버튼(48px) 대비 3배 너비(144px), 장바구니 라벨 */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
boxShadow: "0 4px 12px rgba(59,130,246,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
boxShadow: "0 4px 12px rgba(59,130,246,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-blue-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-blue-400 focus:ring-2 focus:ring-blue-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(59,130,246,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-blue-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 미입고 발주가 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-blue-500 rounded-lg hover:bg-blue-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-blue-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad (edit qty before adding) */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: editedQtys[order.id] !== undefined
? "bg-green-50 border-green-300 hover:bg-green-100 cursor-pointer active:scale-95"
: "bg-blue-50 border-blue-200 hover:bg-blue-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${
inCart ? "text-gray-400"
: editedQtys[order.id] !== undefined ? "text-green-700"
: "text-blue-700"
}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: (editedQtys[order.id] ?? order.remain_qty).toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => handleAddToCart(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="발주 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface RecoveryOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface RecoveryInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_recovery";
export function RecoveryInbound({ cart, onCartClick, saving, inboundType, sourceTable }: RecoveryInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<RecoveryOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<RecoveryOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 외주자재회수용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 외주자재회수 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: RecoveryOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 외주자재회수 라인, 발주품목 위. 테마 pink */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #f472b6, #db2777)",
boxShadow: "0 4px 12px rgba(219,39,119,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #f472b6, #db2777)",
boxShadow: "0 4px 12px rgba(236,72,153,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-pink-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-pink-400 focus:ring-2 focus:ring-pink-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #f472b6, #db2777)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(236,72,153,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-pink-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 회수 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-pink-500 rounded-lg hover:bg-pink-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-pink-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-pink-100 text-pink-700 border border-pink-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-pink-50 border-pink-200 hover:bg-pink-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-pink-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #ec4899 0%, #db2777 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="회수 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ReturnOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ReturnExternalInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_return-external";
export function ReturnExternalInbound({ cart, onCartClick, saving, inboundType, sourceTable }: ReturnExternalInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<ReturnOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<ReturnOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 반품입고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 반품입고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: ReturnOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 반품입고 라인, 발주품목 위. 테마 amber */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #fbbf24, #d97706)",
boxShadow: "0 4px 12px rgba(217,119,6,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #fbbf24, #d97706)",
boxShadow: "0 4px 12px rgba(245,158,11,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-amber-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-amber-400 focus:ring-2 focus:ring-amber-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #fbbf24, #d97706)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(245,158,11,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-amber-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 반품 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-amber-500 rounded-lg hover:bg-amber-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-amber-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-amber-50 border-amber-200 hover:bg-amber-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-amber-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #f59e0b 0%, #d97706 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="반품 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ReturnOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ReturnInternalInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_return-internal";
export function ReturnInternalInbound({ cart, onCartClick, saving, inboundType, sourceTable }: ReturnInternalInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<ReturnOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<ReturnOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 반납입고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 반납입고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: ReturnOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 반납입고 라인, 발주품목 위. 테마 orange */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #fb923c, #ea580c)",
boxShadow: "0 4px 12px rgba(234,88,12,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #fb923c, #ea580c)",
boxShadow: "0 4px 12px rgba(249,115,22,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-orange-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-orange-400 focus:ring-2 focus:ring-orange-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #fb923c, #ea580c)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(249,115,22,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-orange-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 반납 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-orange-500 rounded-lg hover:bg-orange-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-orange-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-orange-100 text-orange-700 border border-orange-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-orange-50 border-orange-200 hover:bg-orange-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-orange-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #f97316 0%, #ea580c 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="반납 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface SubcontractorOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface SubcontractorInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_subcontractor";
export function SubcontractorInbound({ cart, onCartClick, saving, inboundType, sourceTable }: SubcontractorInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<SubcontractorOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<SubcontractorOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 외주입고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 외주입고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: SubcontractorOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 외주입고 라인, 발주품목 위. 테마 purple */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #a78bfa, #7c3aed)",
boxShadow: "0 4px 12px rgba(124,58,237,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #a78bfa, #7c3aed)",
boxShadow: "0 4px 12px rgba(139,92,246,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-purple-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-purple-400 focus:ring-2 focus:ring-purple-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #a78bfa, #7c3aed)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(139,92,246,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-purple-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 외주 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-purple-500 rounded-lg hover:bg-purple-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-purple-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-purple-100 text-purple-700 border border-purple-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-purple-50 border-purple-200 hover:bg-purple-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-purple-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="외주 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,610 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "./SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface SuppliedOrder {
id: string;
purchase_no: string;
order_date: string;
supplier_code: string;
supplier_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
received_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface SuppliedInboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 입고 유형 — 카트 품목에 기록됨 */
inboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_supplier_supplied";
export function SuppliedInbound({ cart, onCartClick, saving, inboundType, sourceTable }: SuppliedInboundProps) {
const router = useRouter();
/* State */
const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null);
const [supplierModalOpen, setSupplierModalOpen] = useState(false);
const [orders, setOrders] = useState<SuppliedOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<SuppliedOrder | null>(null);
/* Barcode scan modal state */
const [supplierScanOpen, setSupplierScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline supplier search state */
const [supplierSearchText, setSupplierSearchText] = useState("");
const [supplierDropdownOpen, setSupplierDropdownOpen] = useState(false);
const [allSuppliers, setAllSuppliers] = useState<Supplier[]>([]);
const supplierInputRef = useRef<HTMLInputElement>(null);
const supplierDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all suppliers for inline search
* TODO: API 연결 — 사급자재용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllSuppliers = useCallback(async () => {
setAllSuppliers([]);
}, []);
useEffect(() => { fetchAllSuppliers(); }, [fetchAllSuppliers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedSupplier(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectSupplier = (s: Supplier | null) => {
setSelectedSupplier(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered suppliers for inline dropdown */
const filteredSuppliers = useMemo(() => {
if (!supplierSearchText.trim()) return [];
return allSuppliers.filter((s) => matchChosung(s.customer_name, supplierSearchText.trim()));
}, [allSuppliers, supplierSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
supplierDropdownRef.current &&
!supplierDropdownRef.current.contains(e.target as Node) &&
supplierInputRef.current &&
!supplierInputRef.current.contains(e.target as Node)
) {
setSupplierDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch return orders
* TODO: API 연결 — 사급자재 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected supplier */
const filteredOrders = selectedSupplier
? orders.filter((o) =>
o.supplier_code === selectedSupplier.customer_code ||
o.supplier_name === selectedSupplier.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.purchase_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: SuppliedOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 공급사 검증: 카트에 이미 다른 공급사 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingSupplier = String(cart.cartItems[0].row.supplier_code || "");
if (existingSupplier && existingSupplier !== order.supplier_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
supplier_code: order.supplier_code,
supplier_name: order.supplier_name,
purchase_no: order.purchase_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
inbound_type: inboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/inbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button — 사급입고 라인, 발주품목 위. 테마 cyan */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #22d3ee, #0891b2)",
boxShadow: "0 4px 12px rgba(8,145,178,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Supplier search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedSupplier && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedSupplier.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setSupplierModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedSupplier
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedSupplier ? selectedSupplier.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setSupplierScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #22d3ee, #0891b2)",
boxShadow: "0 4px 12px rgba(6,182,212,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedSupplier && (
<button
onClick={() => { selectSupplier(null); setSupplierSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
{/* Supplier dropdown removed — use modal instead */}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-cyan-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedSupplier ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 발주번호 검색..."
disabled={!selectedSupplier}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedSupplier
? "focus:border-cyan-400 focus:ring-2 focus:ring-cyan-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button - glossy v3 */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedSupplier}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedSupplier ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #22d3ee, #0891b2)",
boxShadow: selectedSupplier ? "0 4px 12px rgba(6,182,212,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedSupplier ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedSupplier ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-cyan-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedSupplier ? "해당 거래처의 사급 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-cyan-500 rounded-lg hover:bg-cyan-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-cyan-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-cyan-100 text-cyan-700 border border-cyan-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.purchase_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-cyan-50 border-cyan-200 hover:bg-cyan-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-cyan-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #06b6d4 0%, #0891b2 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={supplierModalOpen}
onClose={() => setSupplierModalOpen(false)}
onSelect={(s) => selectSupplier(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for supplier */}
<BarcodeScanModal
open={supplierScanOpen}
onOpenChange={setSupplierScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setSupplierScanOpen(false);
// 스캔 결과로 거래처 검색 (거래처명 또는 코드 매칭)
const match = allSuppliers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectSupplier(match);
setSupplierSearchText("");
} else {
// 매칭 안 되면 검색 텍스트에 넣어서 드롭다운 표시
setSupplierSearchText(barcode);
setSupplierDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="사급 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
// 스캔 결과로 품목 필터
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,329 @@
"use client";
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { apiClient } from "@/lib/api/client";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
/**
* 범용 거래처 표현형.
* customer_name / customer_code 필드명은 기존 호환성을 위해 유지하지만,
* 실제 원본 테이블(공급사/고객사/외주업체 등)은 호출부에서 지정한다.
*/
export interface Supplier {
id: string;
customer_name: string;
customer_code?: string;
business_number?: string;
phone?: string;
address?: string;
}
/**
* 모달이 접속할 테이블과 컬럼 매핑.
* 예) supplier_mng + { code: "supplier_code", name: "supplier_name", ... }
* customer_mng + { code: "customer_code", name: "customer_name", ... }
*/
export interface PartnerSourceConfig {
/** 조회할 테이블명 (GET /api/data/:tableName 으로 조회됨) */
tableName: string;
/** 필드 매핑 */
fields: {
code: string;
name: string;
businessNumber?: string;
phone?: string;
address?: string;
};
}
interface SupplierModalProps {
open: boolean;
onClose: () => void;
onSelect: (supplier: Supplier) => void;
/** 테이블/필드 매핑. 미지정 시 supplier_mng 기본값 사용(하위호환) */
source?: PartnerSourceConfig;
/** 모달 타이틀 (기본: "거래처 선택") */
title?: string;
/** 검색 플레이스홀더 (기본: "거래처명 또는 코드 검색...") */
searchPlaceholder?: string;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
const AVATAR_COLORS = [
"#3b82f6", "#22c55e", "#f59e0b", "#ef4444", "#8b5cf6",
"#06b6d4", "#ec4899", "#14b8a6", "#f97316", "#6366f1",
"#84cc16", "#e11d48", "#0ea5e9", "#a855f7", "#10b981",
];
function getAvatarColor(name: string): string {
let hash = 0;
for (let i = 0; i < name.length; i++) {
hash = name.charCodeAt(i) + ((hash << 5) - hash);
}
return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
}
/** Get the Korean initial consonant (Chosung) for sorting */
export function getChosung(char: string): string {
const code = char.charCodeAt(0);
if (code < 0xAC00 || code > 0xD7A3) {
// Not Korean -- group by uppercase letter
const upper = char.toUpperCase();
if (/[A-Z]/.test(upper)) return upper;
return "#";
}
const chosungList = [
"ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ",
"ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ",
];
const idx = Math.floor((code - 0xAC00) / 588);
return chosungList[idx] ?? "#";
}
/** Check if a query (possibly chosung-only) matches a Korean string */
export function matchChosung(text: string, query: string): boolean {
if (!query) return true;
// Normal substring match first
if (text.toLowerCase().includes(query.toLowerCase())) return true;
// Check if query is all chosung characters
const chosungChars = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ";
const isChosungQuery = [...query].every((c) => chosungChars.includes(c));
if (!isChosungQuery) return false;
// Extract chosung from text (strip prefixes like (주))
const cleaned = text.replace(/^\(주\)|\(유\)|\(합\)/g, "").trim();
const textChosung = [...cleaned].map((c) => getChosung(c)).join("");
return textChosung.includes(query);
}
/* ------------------------------------------------------------------ */
/* Defaults (하위호환: source 미지정 시 supplier_mng 사용) */
/* ------------------------------------------------------------------ */
const DEFAULT_SOURCE: PartnerSourceConfig = {
tableName: "supplier_mng",
fields: {
code: "supplier_code",
name: "supplier_name",
businessNumber: "business_number",
phone: "contact_phone",
address: "address",
},
};
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function SupplierModal({
open,
onClose,
onSelect,
source,
title = "거래처 선택",
searchPlaceholder = "거래처명 또는 코드 검색...",
}: SupplierModalProps) {
const [suppliers, setSuppliers] = useState<Supplier[]>([]);
const [search, setSearch] = useState("");
const [sortMode, setSortMode] = useState<"korean" | "abc">("korean");
const [loading, setLoading] = useState(false);
// 지정된 소스가 없으면 기본값(supplier_mng) 사용
const activeSource = source ?? DEFAULT_SOURCE;
// Fetch partners from the configured table
// 구매관리 > 공급업체관리 화면과 동일한 API 사용 (POST /table-management/tables/{table}/data, autoFilter 적용)
const fetchSuppliers = useCallback(async () => {
setLoading(true);
try {
const res = await apiClient.post(
`/table-management/tables/${activeSource.tableName}/data`,
{
page: 1,
size: 500,
autoFilter: true,
sort: { columnName: activeSource.fields.code, order: "desc" },
},
);
const data =
res.data?.data?.data ?? res.data?.data?.rows ?? [];
const f = activeSource.fields;
const list: Supplier[] = (Array.isArray(data) ? data : []).map(
(r: Record<string, unknown>) => ({
id: String(r.id ?? ""),
customer_name: String(r[f.name] ?? ""),
customer_code: String(r[f.code] ?? ""),
business_number: f.businessNumber
? String(r[f.businessNumber] ?? "")
: "",
phone: f.phone ? String(r[f.phone] ?? "") : "",
address: f.address ? String(r[f.address] ?? "") : "",
}),
);
setSuppliers(list);
} catch {
setSuppliers([]);
} finally {
setLoading(false);
}
}, [activeSource.tableName, activeSource.fields]);
useEffect(() => {
if (open) {
fetchSuppliers();
setSearch("");
}
}, [open, fetchSuppliers]);
/* Filtered + grouped */
const grouped = useMemo(() => {
const filtered = suppliers.filter((s) =>
s.customer_name.toLowerCase().includes(search.toLowerCase()) ||
(s.customer_code ?? "").toLowerCase().includes(search.toLowerCase())
);
// Sort — 접두사 제거 후 비교 (그룹핑 기준과 일치)
const stripPrefix = (name: string) =>
name.replace(/^\(주\)|\(유\)|\(합\)/g, "").trim();
const sorted = [...filtered].sort((a, b) => {
const an = stripPrefix(a.customer_name);
const bn = stripPrefix(b.customer_name);
if (sortMode === "abc") return an.localeCompare(bn, "en");
return an.localeCompare(bn, "ko");
});
// Group by chosung
const groups: { letter: string; items: Supplier[] }[] = [];
const map = new Map<string, Supplier[]>();
for (const s of sorted) {
const first = s.customer_name.replace(/^\(주\)|\(유\)|\(합\)/g, "").trim().charAt(0);
const letter = getChosung(first);
if (!map.has(letter)) map.set(letter, []);
map.get(letter)!.push(s);
}
for (const [letter, items] of map) {
groups.push({ letter, items });
}
return groups;
}, [suppliers, search, sortMode]);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
{/* Overlay */}
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
{/* Modal */}
<div className="relative bg-white rounded-2xl w-[80vw] h-[80vh] flex flex-col shadow-2xl overflow-hidden z-10">
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<div className="flex items-center gap-3">
<h3 className="text-lg font-bold text-gray-900">{title}</h3>
{/* Sort tabs */}
<div className="flex gap-1.5">
<button
onClick={() => setSortMode("korean")}
className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
sortMode === "korean"
? "bg-gray-900 text-white border-gray-900"
: "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
}`}
>
</button>
<button
onClick={() => setSortMode("abc")}
className={`px-3 py-1 rounded-full text-xs font-medium border transition-all ${
sortMode === "abc"
? "bg-gray-900 text-white border-gray-900"
: "bg-white text-gray-500 border-gray-200 hover:bg-gray-50"
}`}
>
ABC
</button>
</div>
</div>
<button
onClick={onClose}
className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Search */}
<div className="px-5 py-3">
<div className="relative">
<svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={searchPlaceholder}
className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-xl text-sm outline-none focus:border-blue-400 focus:ring-2 focus:ring-blue-100 transition-all"
/>
</div>
</div>
{/* Supplier list */}
<div className="flex-1 overflow-y-auto px-5 pb-5">
{loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
...
</div>
) : grouped.length === 0 ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
{search ? "검색 결과가 없습니다" : "거래처가 없습니다"}
</div>
) : (
grouped.map((group) => (
<div key={group.letter} className="mb-2">
{/* Group header */}
<div className="flex items-center gap-2 mb-1">
<span className="text-sm font-bold text-blue-500 min-w-[20px]">{group.letter}</span>
<div className="flex-1 h-px bg-gray-100" />
</div>
{/* Grid — 뷰포트 900px 미만 4개(25%), 이상 5개(20%), 셀 전체 클릭 가능 */}
<div className="grid grid-cols-4 min-[900px]:grid-cols-5 gap-x-2 gap-y-1">
{group.items.map((supplier) => {
const displayName = supplier.customer_name.replace(/^\(주\)|\(유\)|\(합\)/g, "").trim();
const initial = displayName.charAt(0);
const color = getAvatarColor(supplier.customer_name);
return (
<button
key={supplier.id}
onClick={() => { onSelect(supplier); onClose(); }}
className="flex flex-col items-center gap-1 py-1.5 px-3 w-full rounded-xl hover:bg-gray-50 active:scale-95 transition-all cursor-pointer border-none bg-transparent"
>
<div
className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl flex items-center justify-center text-white text-xl sm:text-2xl font-bold shadow-sm shrink-0"
style={{ background: color }}
>
{initial}
</div>
<span className="text-xs sm:text-sm font-medium text-gray-700 text-center leading-tight w-full truncate px-1">
{supplier.customer_name}
</span>
</button>
);
})}
</div>
</div>
))
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,562 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
inspection_type: "self" | "request" | null;
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface EtcOutboundProps {
cart: import("../common/useCartSync").UseCartSyncReturn;
onCartClick: () => void;
saving: boolean;
outboundType: string;
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_etc";
export function EtcOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: EtcOutboundProps) {
const router = useRouter();
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers
* TODO: API 연결 — 기타출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 기타출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #475569, #1e293b)",
boxShadow: "0 4px 12px rgba(30,41,59,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-gray-50/50 border-gray-300 text-gray-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #475569, #1e293b)",
boxShadow: "0 4px 12px rgba(30,41,59,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-gray-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-gray-400 focus:ring-2 focus:ring-gray-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #475569, #1e293b)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(30,41,59,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-gray-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-gray-500 rounded-lg hover:bg-gray-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-gray-400"
}`}
>
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
<div className="flex gap-2.5">
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
<button
onClick={() => { if (!inCart) openNumpad(order); }}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-gray-100 border-gray-300 hover:bg-gray-200 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-gray-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #475569 0%, #1e293b 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) => s.customer_code === barcode || s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,874 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier } from "../inbound/SupplierModal";
import {
getOutboundList,
updateOutbound,
deleteOutbound,
getOutboundWarehouses,
type OutboundItem,
type WarehouseOption,
} from "@/lib/api/outbound";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundRecord extends OutboundItem {
detail_id?: string;
seq_no?: number;
detail_outbound_type?: string;
header_memo?: string;
item_number?: string;
}
const STATUS_OPTIONS = ["출고완료", "부분출고", "대기"];
const OUTBOUND_TYPE_OPTIONS = [
{ value: "all", label: "전체" },
{ value: "판매출고", label: "판매출고" },
{ value: "생산출고", label: "생산출고" },
{ value: "외주출고", label: "외주출고" },
{ value: "사급출고", label: "사급출고" },
{ value: "반품출고", label: "반품출고" },
{ value: "기타출고", label: "기타출고" },
{ value: "재고이동", label: "재고이동" },
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
export function OutboundManage() {
const router = useRouter();
const today = new Date().toISOString().slice(0, 10);
/* ── Filters ── */
const [outboundDate, setOutboundDate] = useState(today);
const [outboundType, setOutboundType] = useState("all");
const [keyword, setKeyword] = useState("");
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(
null,
);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
/* ── Data ── */
const [records, setRecords] = useState<OutboundRecord[]>([]);
const [loading, setLoading] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [warehouses, setWarehouses] = useState<WarehouseOption[]>([]);
/* ── Edit modal ── */
const [editRecord, setEditRecord] = useState<OutboundRecord | null>(null);
const [editForm, setEditForm] = useState<Record<string, any>>({});
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
/* ── Helpers ── */
const getRowKey = (r: OutboundRecord) => r.detail_id || r.id;
/* ---------------------------------------------------------------- */
/* Fetch */
/* ---------------------------------------------------------------- */
const fetchRecords = useCallback(async () => {
setLoading(true);
try {
const params: Record<string, string> = {};
if (outboundDate) {
params.date_from = outboundDate;
params.date_to = outboundDate;
}
if (outboundType !== "all") params.outbound_type = outboundType;
if (keyword.trim()) params.search_keyword = keyword.trim();
const res = await getOutboundList(params);
if (res.success) {
let data = res.data as unknown as OutboundRecord[];
if (selectedCustomer?.customer_code) {
data = data.filter(
(r) => r.customer_code === selectedCustomer.customer_code,
);
}
setRecords(data);
setSelectedIds(new Set());
}
} catch (e) {
console.error("출고 목록 조회 실패", e);
} finally {
setLoading(false);
}
}, [outboundDate, outboundType, keyword, selectedCustomer]);
useEffect(() => {
getOutboundWarehouses()
.then((res) => {
if (res.success) setWarehouses(res.data);
})
.catch(() => {});
}, []);
useEffect(() => {
fetchRecords();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/* ---------------------------------------------------------------- */
/* Selection */
/* ---------------------------------------------------------------- */
const toggleSelect = (key: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
const toggleSelectAll = () => {
if (selectedIds.size === records.length) setSelectedIds(new Set());
else setSelectedIds(new Set(records.map(getRowKey)));
};
/* ---------------------------------------------------------------- */
/* Delete */
/* ---------------------------------------------------------------- */
const handleDelete = async () => {
if (selectedIds.size === 0) return;
const headerIds = new Set<string>();
records.forEach((r) => {
if (selectedIds.has(getRowKey(r))) headerIds.add(r.id);
});
if (
!confirm(
`선택한 ${headerIds.size}건의 출고를 삭제하시겠습니까?\n(재고가 롤백됩니다)`,
)
)
return;
setDeleting(true);
try {
for (const hid of headerIds) {
await deleteOutbound(hid);
}
await fetchRecords();
} catch (e: any) {
alert(`삭제 실패: ${e?.message || "알 수 없는 오류"}`);
} finally {
setDeleting(false);
}
};
/* ---------------------------------------------------------------- */
/* Edit */
/* ---------------------------------------------------------------- */
const openEdit = (record: OutboundRecord) => {
setEditRecord(record);
setEditForm({
outbound_date: record.outbound_date?.slice(0, 10) || today,
outbound_qty: record.outbound_qty ?? 0,
unit_price: record.unit_price ?? 0,
total_amount: record.total_amount ?? 0,
lot_number: record.lot_number || "",
warehouse_code: record.warehouse_code || "",
location_code: record.location_code || "",
outbound_status: record.outbound_status || "출고완료",
manager_id: record.manager_id || "",
memo: record.memo || "",
});
};
const handleEditFromSelection = () => {
if (selectedIds.size !== 1) {
alert("수정할 항목을 1건만 선택해주세요.");
return;
}
const key = Array.from(selectedIds)[0];
const rec = records.find((r) => getRowKey(r) === key);
if (rec) openEdit(rec);
};
const updateField = (key: string, value: any) => {
setEditForm((prev) => {
const next = { ...prev, [key]: value };
if (key === "outbound_qty" || key === "unit_price") {
next.total_amount =
Math.round(
(Number(next.outbound_qty) || 0) *
(Number(next.unit_price) || 0) *
100,
) / 100;
}
return next;
});
};
const handleSave = async () => {
if (!editRecord) return;
setSaving(true);
try {
const payload: Record<string, any> = { ...editForm };
if (editRecord.detail_id) payload.detail_id = editRecord.detail_id;
await updateOutbound(editRecord.id, payload as Partial<OutboundItem>);
setEditRecord(null);
await fetchRecords();
} catch (e: any) {
alert(`수정 실패: ${e?.message || "알 수 없는 오류"}`);
} finally {
setSaving(false);
}
};
/* ---------------------------------------------------------------- */
/* Render */
/* ---------------------------------------------------------------- */
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15.75 19.5L8.25 12l7.5-7.5"
/>
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight">
</h1>
<p className="text-xs text-gray-400 mt-0.5">
, ,
</p>
</div>
</div>
{/* ===== Search / Filter ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="grid grid-cols-2 lg:grid-cols-5 gap-3">
{/* 출고일 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<input
type="date"
value={outboundDate}
onChange={(e) => setOutboundDate(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100"
/>
</div>
{/* 출고유형 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<select
value={outboundType}
onChange={(e) => setOutboundType(e.target.value)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 bg-white"
>
{OUTBOUND_TYPE_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
{/* 거래처 */}
<div>
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<button
onClick={() => setCustomerModalOpen(true)}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-left outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 bg-white flex items-center justify-between"
>
<span
className={
selectedCustomer
? "text-gray-900 truncate"
: "text-gray-400"
}
>
{selectedCustomer ? selectedCustomer.customer_name : "전체"}
</span>
{selectedCustomer ? (
<span
onClick={(e) => {
e.stopPropagation();
setSelectedCustomer(null);
}}
className="text-gray-400 hover:text-gray-600 ml-1 shrink-0"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</span>
) : (
<svg
className="w-4 h-4 text-gray-400 shrink-0"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M8.25 15L12 18.75 15.75 15m-7.5-6L12 5.25 15.75 9"
/>
</svg>
)}
</button>
</div>
{/* 검색어 + 검색버튼 */}
<div className="col-span-2">
<label className="text-xs font-semibold text-gray-500 mb-1 block">
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") fetchRecords();
}}
placeholder="출고번호, 품목명, 거래처명..."
className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100"
/>
<button
onClick={fetchRecords}
disabled={loading}
className="min-w-[48px] min-h-[40px] rounded-lg flex items-center justify-center text-white active:scale-95 transition-all disabled:opacity-50"
style={{
background: "linear-gradient(to bottom, #34d399, #059669)",
}}
>
{loading ? (
<svg
className="w-5 h-5 animate-spin"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
) : (
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"
/>
</svg>
)}
</button>
</div>
</div>
</div>
</div>
{/* ===== Action buttons ===== */}
<div className="flex items-center justify-between">
<span className="text-sm text-gray-500">
{selectedIds.size > 0
? `${selectedIds.size}건 선택`
: `${records.length}`}
</span>
<div className="flex items-center gap-2">
<button
disabled={selectedIds.size !== 1}
onClick={handleEditFromSelection}
className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
style={{
background: "linear-gradient(to bottom, #34d399, #059669)",
}}
>
</button>
<button
disabled={selectedIds.size === 0 || deleting}
onClick={handleDelete}
className="px-4 py-2 rounded-lg text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
style={{
background: "linear-gradient(to bottom, #f87171, #dc2626)",
}}
>
{deleting ? "삭제 중..." : "삭제"}
</button>
</div>
</div>
{/* ===== Record list ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={
records.length > 0 && selectedIds.size === records.length
}
onChange={toggleSelectAll}
className="w-4 h-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-xs font-semibold text-gray-500">
</span>
</div>
<span className="text-[11px] text-gray-400">{records.length}</span>
</div>
{loading && records.length === 0 ? (
<div className="flex items-center justify-center py-16">
<svg
className="w-8 h-8 animate-spin text-emerald-500"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
</div>
) : records.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg
className="w-16 h-16 mb-4 opacity-20"
fill="none"
stroke="currentColor"
strokeWidth={1}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 11.625a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
/>
</svg>
<p className="text-sm font-medium text-gray-500 mb-1">
</p>
<p className="text-xs text-gray-400">
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{records.map((record) => {
const key = getRowKey(record);
return (
<div
key={key}
className={`relative rounded-xl border p-3 transition-all cursor-pointer ${
selectedIds.has(key)
? "ring-2 ring-emerald-500 border-emerald-300 bg-emerald-50/30"
: "border-gray-200 bg-white hover:border-emerald-300"
}`}
onClick={() => toggleSelect(key)}
>
{/* Card header */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<input
type="checkbox"
checked={selectedIds.has(key)}
onChange={() => toggleSelect(key)}
onClick={(e) => e.stopPropagation()}
className="w-4 h-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
/>
<span className="text-[11px] text-gray-400 font-medium">
{record.outbound_number}
</span>
<span className="text-[11px] font-semibold px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600">
{record.detail_outbound_type || record.outbound_type}
</span>
<span
className={`ml-auto text-[11px] font-semibold px-1.5 py-0.5 rounded-full ${
record.outbound_status === "출고완료"
? "bg-green-50 text-green-600"
: record.outbound_status === "부분출고"
? "bg-amber-50 text-amber-600"
: "bg-gray-50 text-gray-500"
}`}
>
{record.outbound_status || "출고"}
</span>
<button
onClick={(e) => {
e.stopPropagation();
openEdit(record);
}}
className="ml-1 w-7 h-7 rounded-lg bg-gray-50 hover:bg-emerald-50 flex items-center justify-center text-gray-400 hover:text-emerald-600 transition-colors"
>
<svg
className="w-3.5 h-3.5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"
/>
</svg>
</button>
</div>
{/* Card body */}
<div className="flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700 truncate">
{record.item_name || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-500 truncate">
{record.item_code || record.item_number || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{record.customer_name || "-"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-bold text-emerald-700">
{Number(record.outbound_qty).toLocaleString()}{" "}
{record.unit || "EA"}
</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{record.outbound_date?.slice(0, 10) || "-"}
</span>
</div>
{(record as any).warehouse_name && (
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0">
</span>
<span className="font-medium text-gray-700">
{(record as any).warehouse_name}
</span>
</div>
)}
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Edit Modal ===== */}
{editRecord && (
<div
className="fixed inset-0 z-50 bg-black/40"
onClick={() => setEditRecord(null)}
>
<div
className="absolute inset-x-0 bottom-0 sm:inset-auto sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 bg-white w-full sm:max-w-lg max-h-[90vh] rounded-t-2xl sm:rounded-2xl overflow-hidden flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Modal header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-gray-100 bg-gradient-to-b from-emerald-50 to-white shrink-0">
<div className="min-w-0">
<h2 className="text-lg font-bold text-gray-900"> </h2>
<p className="text-[11px] text-gray-400 truncate">
{editRecord.outbound_number} | {editRecord.item_name}
</p>
</div>
<button
onClick={() => setEditRecord(null)}
className="w-9 h-9 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-600 shrink-0 ml-2"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
strokeWidth={2}
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Modal body */}
<div className="flex-1 overflow-y-auto px-4 py-4 space-y-5">
{/* 기본 정보 */}
<FieldGroup title="기본 정보">
<FormField
label="출고일"
type="date"
value={editForm.outbound_date}
onChange={(v) => updateField("outbound_date", v)}
/>
<FormField
label="출고상태"
type="select"
value={editForm.outbound_status}
onChange={(v) => updateField("outbound_status", v)}
options={STATUS_OPTIONS}
/>
</FieldGroup>
{/* 수량/금액 */}
<FieldGroup title="수량/금액">
<FormField
label="수량"
type="number"
value={editForm.outbound_qty}
onChange={(v) => updateField("outbound_qty", v)}
/>
<FormField
label="단가"
type="number"
value={editForm.unit_price}
onChange={(v) => updateField("unit_price", v)}
/>
<FormField
label="금액"
type="number"
value={editForm.total_amount}
onChange={(v) => updateField("total_amount", v)}
readOnly
/>
</FieldGroup>
{/* 출고 상세 */}
<FieldGroup title="출고 상세">
<FormField
label="LOT번호"
value={editForm.lot_number}
onChange={(v) => updateField("lot_number", v)}
/>
<FormField
label="창고"
type="select"
value={editForm.warehouse_code}
onChange={(v) => updateField("warehouse_code", v)}
options={warehouses.map((w) => ({
value: w.warehouse_code,
label: w.warehouse_name,
}))}
emptyLabel="선택..."
/>
<FormField
label="위치"
value={editForm.location_code}
onChange={(v) => updateField("location_code", v)}
/>
<FormField
label="담당자"
value={editForm.manager_id}
onChange={(v) => updateField("manager_id", v)}
/>
</FieldGroup>
{/* 메모 */}
<div>
<h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
</h3>
<textarea
value={editForm.memo}
onChange={(e) => updateField("memo", e.target.value)}
rows={3}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100 resize-none"
placeholder="메모 입력..."
/>
</div>
</div>
{/* Modal footer */}
<div className="flex items-center gap-3 px-4 py-3 border-t border-gray-100 bg-gray-50/50 shrink-0">
<button
onClick={() => setEditRecord(null)}
className="flex-1 py-3 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 active:scale-95 transition-all"
>
</button>
<button
onClick={handleSave}
disabled={saving}
className="flex-1 py-3 rounded-xl text-sm font-semibold text-white active:scale-95 transition-all disabled:opacity-50"
style={{
background: "linear-gradient(to bottom, #34d399, #059669)",
}}
>
{saving ? "저장 중..." : "저장"}
</button>
</div>
</div>
</div>
)}
{/* ===== Customer Modal ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(customer) => setSelectedCustomer(customer)}
/>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Sub-components */
/* ------------------------------------------------------------------ */
function FieldGroup({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
<div>
<h3 className="text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">
{title}
</h3>
<div className="grid grid-cols-2 gap-3">{children}</div>
</div>
);
}
interface FormFieldProps {
label: string;
value: any;
onChange: (v: any) => void;
type?: "text" | "number" | "date" | "select";
options?: string[] | { value: string; label: string }[];
emptyLabel?: string;
readOnly?: boolean;
}
function FormField({
label,
value,
onChange,
type = "text",
options,
emptyLabel,
readOnly,
}: FormFieldProps) {
const baseClass =
"w-full px-3 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-emerald-400 focus:ring-2 focus:ring-emerald-100";
return (
<div>
<label className="text-[11px] font-semibold text-gray-400 mb-1 block">
{label}
</label>
{type === "select" && options ? (
<select
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${baseClass} bg-white`}
>
{emptyLabel && <option value="">{emptyLabel}</option>}
{options.map((opt) => {
const v = typeof opt === "string" ? opt : opt.value;
const l = typeof opt === "string" ? opt : opt.label;
return (
<option key={v} value={v}>
{l}
</option>
);
})}
</select>
) : (
<input
type={type}
value={value}
onChange={(e) =>
onChange(
type === "number" ? Number(e.target.value) : e.target.value,
)
}
readOnly={readOnly}
className={`${baseClass} ${readOnly ? "bg-gray-50 text-gray-500" : ""}`}
/>
)}
</div>
);
}
@@ -0,0 +1,562 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
inspection_type: "self" | "request" | null;
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ProductionOutboundProps {
cart: import("../common/useCartSync").UseCartSyncReturn;
onCartClick: () => void;
saving: boolean;
outboundType: string;
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_production";
export function ProductionOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: ProductionOutboundProps) {
const router = useRouter();
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers
* TODO: API 연결 — 생산출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 생산출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #f97316, #c2410c)",
boxShadow: "0 4px 12px rgba(194,65,12,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-orange-600 bg-orange-50 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-orange-50/50 border-orange-200 text-orange-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #f97316, #c2410c)",
boxShadow: "0 4px 12px rgba(194,65,12,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-orange-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-orange-400 focus:ring-2 focus:ring-orange-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #f97316, #c2410c)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(194,65,12,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-orange-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-orange-500 rounded-lg hover:bg-orange-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-orange-300"
}`}
>
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
<div className="flex gap-2.5">
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
<button
onClick={() => { if (!inCart) openNumpad(order); }}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-orange-50 border-orange-200 hover:bg-orange-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-orange-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #f97316 0%, #c2410c 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) => s.customer_code === barcode || s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,562 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
inspection_type: "self" | "request" | null;
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface ReturnOutboundProps {
cart: import("../common/useCartSync").UseCartSyncReturn;
onCartClick: () => void;
saving: boolean;
outboundType: string;
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_return";
export function ReturnOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: ReturnOutboundProps) {
const router = useRouter();
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers
* TODO: API 연결 — 반품출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 반품출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #64748b, #334155)",
boxShadow: "0 4px 12px rgba(51,65,85,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-slate-600 bg-slate-50 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-slate-50/50 border-slate-200 text-slate-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #64748b, #334155)",
boxShadow: "0 4px 12px rgba(51,65,85,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-slate-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-slate-400 focus:ring-2 focus:ring-slate-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #64748b, #334155)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(51,65,85,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-slate-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-slate-500 rounded-lg hover:bg-slate-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-slate-300"
}`}
>
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
<div className="flex gap-2.5">
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
<button
onClick={() => { if (!inCart) openNumpad(order); }}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-slate-50 border-slate-200 hover:bg-slate-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-slate-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #64748b 0%, #334155 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) => s.customer_code === barcode || s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,605 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
/** Inspection type: "self" = self inspection required, "request" = inspection request optional, null = none */
inspection_type: "self" | "request" | null;
/** Item image URL from item_info.image (may be null) */
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface SalesOutboundProps {
/** useCartSync 훅 인스턴스 (page.tsx에서 생성하여 전달) */
cart: import("../common/useCartSync").UseCartSyncReturn;
/** 장바구니 버튼 클릭 핸들러 (dirty 저장 후 카트 페이지로 이동) */
onCartClick: () => void;
/** 카트 저장 중 상태 (버튼 스피너/비활성화용) */
saving: boolean;
/** 출고 유형 — 카트 품목에 기록됨 */
outboundType: string;
/** 소스 테이블명 — 카트 품목별 sourceTable */
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_sales";
export function SalesOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: SalesOutboundProps) {
const router = useRouter();
/* State */
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
/* NumberPad state */
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
/* Barcode scan modal state */
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
/* Inline customer search state */
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers for inline search
* TODO: API 연결 — 판매출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
/* Filtered customers for inline dropdown */
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
/* Close dropdown on outside click */
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 판매출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
/* Initial load */
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
/* Filter orders by selected customer */
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
/* Filter by keyword */
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
/* Open numpad for an order */
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
/* Add to cart with numpad result */
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
// 거래처 검증: 카트에 이미 다른 거래처 품목이 있으면 차단
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Remove from cart (cancel) */
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
/* Search */
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* Cart button */}
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #22c55e, #15803d)",
boxShadow: "0 4px 12px rgba(21,128,61,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area (2 columns on tablet+) ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Customer search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-green-50/50 border-green-200 text-green-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
{/* QR/Barcode scan button */}
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #22c55e, #15803d)",
boxShadow: "0 4px 12px rgba(21,128,61,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
{/* Item search card */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-green-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-green-400 focus:ring-2 focus:ring-green-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
{/* QR/Barcode scan button */}
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #22c55e, #15803d)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(21,128,61,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500">
</span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-green-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-green-500 rounded-lg hover:bg-green-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-green-300"
}`}
>
{/* Green left bar for in-cart items */}
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
{/* === Header row: item code + item name + inspection badge === */}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
{/* === Body row: image + info + action === */}
<div className="flex gap-2.5">
{/* Product image */}
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
{/* Info columns */}
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
{/* Action column: qty display + add/cancel button */}
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
{/* Qty display - clickable to open numpad */}
<button
onClick={() => {
if (!inCart) openNumpad(order);
}}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-green-50 border-green-200 hover:bg-green-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-green-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{/* Add / Cancel button */}
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #22c55e 0%, #15803d 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
{/* Barcode scan modal for customer */}
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) =>
s.customer_code === barcode ||
s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
{/* Barcode scan modal for item */}
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,562 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
inspection_type: "self" | "request" | null;
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface SubcontractorOutboundProps {
cart: import("../common/useCartSync").UseCartSyncReturn;
onCartClick: () => void;
saving: boolean;
outboundType: string;
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_subcontractor";
export function SubcontractorOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: SubcontractorOutboundProps) {
const router = useRouter();
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers
* TODO: API 연결 — 외주출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 외주출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #8b5cf6, #6d28d9)",
boxShadow: "0 4px 12px rgba(109,40,217,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-purple-600 bg-purple-50 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-purple-50/50 border-purple-200 text-purple-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #8b5cf6, #6d28d9)",
boxShadow: "0 4px 12px rgba(109,40,217,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-purple-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-purple-400 focus:ring-2 focus:ring-purple-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #8b5cf6, #6d28d9)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(109,40,217,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-purple-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-purple-500 rounded-lg hover:bg-purple-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-purple-300"
}`}
>
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
<div className="flex gap-2.5">
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
<button
onClick={() => { if (!inCart) openNumpad(order); }}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-purple-50 border-purple-200 hover:bg-purple-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-purple-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) => s.customer_code === barcode || s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,562 @@
"use client";
import React, { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { SupplierModal, type Supplier, matchChosung } from "../inbound/SupplierModal";
import { SimpleKeypadModal } from "../common/SimpleKeypadModal";
import { BarcodeScanModal } from "../common/BarcodeScanModal";
import type { CartItemWithId } from "../common/useCartSync";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundOrder {
id: string;
reference_no: string;
order_date: string;
customer_code: string;
customer_name: string;
item_code: string;
item_name: string;
spec: string;
material: string;
order_qty: number;
shipped_qty: number;
remain_qty: number;
unit_price: number;
status: string;
due_date: string;
source_table: string;
inspection_type: "self" | "request" | null;
image: string | null;
}
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
interface SuppliedOutboundProps {
cart: import("../common/useCartSync").UseCartSyncReturn;
onCartClick: () => void;
saving: boolean;
outboundType: string;
sourceTable: string;
}
const STORAGE_KEY = "pop_customer_supplied";
export function SuppliedOutbound({ cart, onCartClick, saving, outboundType, sourceTable }: SuppliedOutboundProps) {
const router = useRouter();
const [selectedCustomer, setSelectedCustomer] = useState<Supplier | null>(null);
const [customerModalOpen, setCustomerModalOpen] = useState(false);
const [orders, setOrders] = useState<OutboundOrder[]>([]);
const [loading, setLoading] = useState(false);
const [fetchError, setFetchError] = useState<string | null>(null);
const [keyword, setKeyword] = useState("");
const [numpadOpen, setNumpadOpen] = useState(false);
const [numpadTarget, setNumpadTarget] = useState<OutboundOrder | null>(null);
const [customerScanOpen, setCustomerScanOpen] = useState(false);
const [itemScanOpen, setItemScanOpen] = useState(false);
const [customerSearchText, setCustomerSearchText] = useState("");
const [customerDropdownOpen, setCustomerDropdownOpen] = useState(false);
const [allCustomers, setAllCustomers] = useState<Supplier[]>([]);
const customerInputRef = useRef<HTMLInputElement>(null);
const customerDropdownRef = useRef<HTMLDivElement>(null);
/* Fetch all customers
* TODO: API 연결 — 사급출고용 거래처 조회 엔드포인트 확정 후 연동
*/
const fetchAllCustomers = useCallback(async () => {
setAllCustomers([]);
}, []);
useEffect(() => { fetchAllCustomers(); }, [fetchAllCustomers]);
/* sessionStorage 복원 — 장바구니 갔다 돌아올 때 거래처 선택 유지 */
useEffect(() => {
const saved = sessionStorage.getItem(STORAGE_KEY);
if (saved) {
try {
const parsed = JSON.parse(saved);
setSelectedCustomer(parsed);
} catch {}
}
}, []);
/* 거래처 선택 래퍼 — sessionStorage에도 저장/제거 */
const selectCustomer = (s: Supplier | null) => {
setSelectedCustomer(s);
if (s) {
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s));
} else {
sessionStorage.removeItem(STORAGE_KEY);
}
};
const filteredCustomers = useMemo(() => {
if (!customerSearchText.trim()) return [];
return allCustomers.filter((s) => matchChosung(s.customer_name, customerSearchText.trim()));
}, [allCustomers, customerSearchText]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
customerDropdownRef.current &&
!customerDropdownRef.current.contains(e.target as Node) &&
customerInputRef.current &&
!customerInputRef.current.contains(e.target as Node)
) {
setCustomerDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
/* Fetch outbound orders
* TODO: API 연결 — 사급출고 대상 품목 조회 엔드포인트 확정 후 연동
*/
const fetchOrders = useCallback(async (_searchKeyword?: string) => {
setLoading(true);
setFetchError(null);
try {
setOrders([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchOrders();
}, [fetchOrders]);
const filteredOrders = selectedCustomer
? orders.filter((o) =>
o.customer_code === selectedCustomer.customer_code ||
o.customer_name === selectedCustomer.customer_name
)
: orders;
const displayOrders = keyword
? filteredOrders.filter((o) =>
o.item_name.toLowerCase().includes(keyword.toLowerCase()) ||
o.item_code.toLowerCase().includes(keyword.toLowerCase()) ||
o.reference_no.toLowerCase().includes(keyword.toLowerCase())
)
: filteredOrders;
const openNumpad = (order: OutboundOrder) => {
setNumpadTarget(order);
setNumpadOpen(true);
};
const handleNumpadConfirm = (qty: number) => {
if (!numpadTarget) return;
const order = numpadTarget;
if (cart.isItemInCart(order.id)) return;
if (cart.cartItems.length > 0) {
const existingCustomer = String(cart.cartItems[0].row.customer_code || "");
if (existingCustomer && existingCustomer !== order.customer_code) {
alert("다른 거래처의 품목이 이미 장바구니에 있습니다.\n같은 거래처의 품목만 담을 수 있습니다.");
setNumpadTarget(null);
return;
}
}
const finalQty = Math.min(qty, order.remain_qty);
cart.addItem(
{
row: {
id: order.id,
item_code: order.item_code,
item_name: order.item_name,
customer_code: order.customer_code,
customer_name: order.customer_name,
reference_no: order.reference_no,
unit_price: order.unit_price || 0,
spec: order.spec || "",
material: order.material || "",
order_qty: order.order_qty,
remain_qty: order.remain_qty,
order_date: order.order_date || "",
inspection_type: order.inspection_type,
source_table: order.source_table,
image: order.image || null,
outbound_type: outboundType,
},
quantity: finalQty,
},
order.id,
sourceTable,
);
setNumpadTarget(null);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleRemoveFromCart = (id: string) => {
cart.removeItem(id);
setTimeout(() => cart.saveToDb().catch(() => {}), 300);
};
const handleSearch = () => {
fetchOrders(keyword || undefined);
};
const isInCart = (id: string) => cart.isItemInCart(id);
const getCartItem = (id: string): CartItemWithId | undefined => cart.getCartItem(id);
return (
<div className="flex flex-col gap-4">
{/* ===== Header ===== */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/outbound")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
<button
onClick={onCartClick}
disabled={saving}
className="relative min-w-[144px] min-h-[48px] px-4 rounded-xl flex items-center justify-center gap-2 text-white font-semibold text-sm active:scale-95 transition-all shrink-0 disabled:opacity-60"
style={{
background: "linear-gradient(to bottom, #06b6d4, #0e7490)",
boxShadow: "0 4px 12px rgba(14,116,144,0.3)",
}}
>
{saving ? (
<svg className="animate-spin w-6 h-6" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-6 h-6" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
)}
<span></span>
{cart.cartCount > 0 && (
<span
className={`absolute -top-1 -right-1 min-w-[20px] h-5 px-1 rounded-full text-[10px] font-bold text-white flex items-center justify-center ${
cart.isDirty ? "bg-orange-500 animate-pulse" : "bg-red-500"
}`}
>
{cart.cartCount}
</span>
)}
</button>
</div>
{/* ===== Search area ===== */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"></span>
{selectedCustomer && (
<span className="text-[11px] font-medium text-cyan-600 bg-cyan-50 px-2 py-0.5 rounded-full">
{selectedCustomer.customer_name}
</span>
)}
</div>
<div className="relative flex items-center gap-2">
<button
onClick={() => setCustomerModalOpen(true)}
className={`flex-1 px-3 py-2.5 border rounded-lg text-sm text-left outline-none transition-all ${
selectedCustomer
? "bg-cyan-50/50 border-cyan-200 text-cyan-800 font-medium"
: "border-gray-200 text-gray-500 hover:border-gray-300 hover:bg-gray-50"
}`}
>
{selectedCustomer ? selectedCustomer.customer_name : "거래처를 선택하세요"}
</button>
<button
onClick={() => setCustomerScanOpen(true)}
className="min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0"
style={{
background: "linear-gradient(to bottom, #06b6d4, #0e7490)",
boxShadow: "0 4px 12px rgba(14,116,144,0.3)",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
{selectedCustomer && (
<button
onClick={() => { selectCustomer(null); setCustomerSearchText(""); }}
className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-gray-400 hover:bg-gray-200 transition-colors shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div>
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-1.5">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] font-semibold text-white bg-cyan-500 px-2 py-0.5 rounded-full min-w-[24px] text-center">
{selectedCustomer ? displayOrders.length : 0}
</span>
</div>
<div className="flex items-center gap-2">
<input
type="text"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleSearch(); }}
placeholder="품목명, 품목코드, 주문번호 검색..."
disabled={!selectedCustomer}
className={`flex-1 px-3 py-2.5 border border-gray-200 rounded-lg text-sm outline-none transition-all ${
selectedCustomer
? "focus:border-cyan-400 focus:ring-2 focus:ring-cyan-100"
: "bg-gray-50 text-gray-400 cursor-not-allowed"
}`}
/>
<button
onClick={() => setItemScanOpen(true)}
disabled={!selectedCustomer}
className={`min-w-[48px] min-h-[48px] rounded-xl flex items-center justify-center text-white active:scale-95 transition-all shrink-0 ${
!selectedCustomer ? "opacity-40 cursor-not-allowed" : ""
}`}
style={{
background: "linear-gradient(to bottom, #06b6d4, #0e7490)",
boxShadow: selectedCustomer ? "0 4px 12px rgba(14,116,144,0.3)" : "none",
}}
>
<svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M13.5 14.625v2.25h2.25m-2.25 2.25h4.5v-4.5" />
</svg>
</button>
</div>
</div>
</div>
{/* ===== Order items ===== */}
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
<div className="flex items-center justify-between mb-2 pb-2 border-b border-gray-50">
<span className="text-xs font-semibold text-gray-500"> </span>
<span className="text-[11px] text-gray-400">
{selectedCustomer ? `${displayOrders.length}` : "-"}
</span>
</div>
{!selectedCustomer ? (
<div className="flex flex-col items-center justify-center py-16 text-gray-400">
<svg className="w-16 h-16 mb-4 opacity-20" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
<p className="text-sm font-medium text-gray-500 mb-1"> </p>
<p className="text-xs text-gray-400"> </p>
</div>
) : loading ? (
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
<svg className="animate-spin w-5 h-5 mr-2 text-cyan-500" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
...
</div>
) : displayOrders.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-gray-400">
<svg className="w-12 h-12 mb-3 opacity-30" fill="none" stroke="currentColor" strokeWidth={1} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
<p className="text-sm">
{fetchError ? fetchError : selectedCustomer ? "해당 거래처의 출하 품목이 없습니다" : "거래처를 선택하거나 품목을 검색하세요"}
</p>
{fetchError && (
<button
onClick={() => fetchOrders()}
className="mt-3 px-4 py-2 text-xs font-medium text-white bg-cyan-500 rounded-lg hover:bg-cyan-600 active:scale-95 transition-all"
>
</button>
)}
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{displayOrders.map((order) => {
const inCart = isInCart(order.id);
const cartItem = getCartItem(order.id);
return (
<div
key={order.id}
className={`relative rounded-xl border p-3 transition-all ${
inCart
? "border-green-300 bg-gradient-to-br from-green-50/80 to-emerald-50/50"
: "border-gray-200 bg-white hover:border-cyan-300"
}`}
>
{inCart && (
<div className="absolute top-0 left-0 w-[3px] h-full bg-green-500 rounded-l-xl" />
)}
<div className="flex items-center gap-1.5 mb-2.5 pb-2 border-b border-gray-100">
<span className="text-[11px] text-gray-400 font-medium shrink-0">{order.item_code}</span>
<span className="text-[13px] font-semibold text-gray-900 flex-1 truncate">{order.item_name}</span>
{order.inspection_type === "self" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 shrink-0 whitespace-nowrap">
</span>
)}
{order.inspection_type === "request" && (
<span className="text-[9px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 border border-amber-200 shrink-0 whitespace-nowrap">
</span>
)}
</div>
<div className="flex gap-2.5">
<div className="w-[56px] h-[56px] min-w-[56px] bg-gray-50 border border-gray-200 rounded-lg flex items-center justify-center shrink-0 overflow-hidden">
{order.image ? (
<img src={order.image} alt={order.item_name} className="w-full h-full object-cover rounded-lg" />
) : (
<span className="text-2xl text-gray-300">{"\uD83D\uDCE6"}</span>
)}
</div>
<div className="flex-1 min-w-0 flex flex-col gap-[3px]">
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_date}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700 truncate">{order.reference_no}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-medium text-gray-700">{order.order_qty.toLocaleString()}</span>
</div>
<div className="flex items-center gap-1.5 text-[11px]">
<span className="text-gray-400 min-w-[45px] shrink-0"></span>
<span className="font-bold text-red-500">
{inCart
? (order.remain_qty - (cartItem?.quantity ?? 0)).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
</div>
</div>
<div className="flex flex-col gap-1.5 items-stretch min-w-[80px] shrink-0">
<button
onClick={() => { if (!inCart) openNumpad(order); }}
disabled={inCart}
className={`flex items-center justify-center gap-1 px-2.5 py-2 rounded-md border transition-all ${
inCart
? "bg-gray-50 border-gray-200 cursor-default"
: "bg-cyan-50 border-cyan-200 hover:bg-cyan-100 cursor-pointer active:scale-95"
}`}
>
<span className={`text-sm font-bold ${inCart ? "text-gray-400" : "text-cyan-700"}`}
style={{ fontVariantNumeric: "tabular-nums" }}
>
{inCart
? (cartItem?.quantity ?? order.remain_qty).toLocaleString()
: order.remain_qty.toLocaleString()
}
</span>
<span className="text-[10px] text-gray-400">EA</span>
</button>
{inCart ? (
<button
onClick={() => handleRemoveFromCart(order.id)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md bg-red-500 text-white text-xs font-semibold hover:bg-red-600 active:scale-95 transition-all"
>
</button>
) : (
<button
onClick={() => openNumpad(order)}
className="flex items-center justify-center gap-1 px-2.5 py-2 rounded-md text-white text-xs font-semibold active:scale-95 transition-all"
style={{
background: "linear-gradient(135deg, #06b6d4 0%, #0e7490 100%)",
}}
>
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121 0 2.002-.881 2.002-2.003V6.75m-14.22 0h14.22" />
</svg>
</button>
)}
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* ===== Modals ===== */}
<SupplierModal
open={customerModalOpen}
onClose={() => setCustomerModalOpen(false)}
onSelect={(s) => selectCustomer(s)}
/>
<SimpleKeypadModal
open={numpadOpen}
onClose={() => { setNumpadOpen(false); setNumpadTarget(null); }}
onConfirm={handleNumpadConfirm}
maxQty={numpadTarget?.remain_qty ?? 0}
itemName={numpadTarget?.item_name ?? ""}
/>
<BarcodeScanModal
open={customerScanOpen}
onOpenChange={setCustomerScanOpen}
targetField="거래처"
autoSubmit
onScanSuccess={(barcode) => {
setCustomerScanOpen(false);
const match = allCustomers.find(
(s) => s.customer_code === barcode || s.customer_name.includes(barcode)
);
if (match) {
selectCustomer(match);
setCustomerSearchText("");
} else {
setCustomerSearchText(barcode);
setCustomerDropdownOpen(true);
}
}}
/>
<BarcodeScanModal
open={itemScanOpen}
onOpenChange={setItemScanOpen}
targetField="출하 품목"
autoSubmit
onScanSuccess={(barcode) => {
setItemScanOpen(false);
setKeyword(barcode);
fetchOrders(barcode);
}}
/>
</div>
);
}
@@ -0,0 +1,26 @@
"use client";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { InboundCartPage } from "../../_components/inbound/InboundCartPage";
function InboundCartContent() {
const searchParams = useSearchParams();
const backUrl = searchParams.get("backUrl") || "/COMPANY_7/pop/inbound";
return <InboundCartPage backUrl={backUrl} />;
}
export default function InboundCartRoute() {
return (
<Suspense
fallback={
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
...
</div>
}
>
<InboundCartContent />
</Suspense>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ChangeInbound } from "../../_components/inbound/ChangeInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ChangeInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/change");
};
return (
<ChangeInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="교환입고"
sourceTable="change_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ErrorInbound } from "../../_components/inbound/ErrorInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ErrorInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/error");
};
return (
<ErrorInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="불량입고"
sourceTable="error_detail"
/>
);
}
@@ -0,0 +1,7 @@
"use client";
import { InboundManage } from "../../_components/inbound/InboundManage";
export default function InboundManagePage() {
return <InboundManage />;
}
@@ -0,0 +1,438 @@
"use client";
import React, { useState, useRef, useCallback, useEffect } from "react";
import { useRouter } from "next/navigation";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface InboundMenuItem {
id: string;
title: string;
gradient: string;
shadowColor: string;
icon: React.ReactNode;
href: string;
}
interface RecentInboundItem {
id: string;
time: string;
type: string;
itemName: string;
qty: string;
supplier: string;
statusColor: string;
statusLabel: string;
}
/* ------------------------------------------------------------------ */
/* Static Data (UI만) */
/* ------------------------------------------------------------------ */
const EXTERNAL_ITEMS: InboundMenuItem[] = [
{
id: "purchase",
title: "구매입고",
gradient: "linear-gradient(135deg,#3b82f6,#1d4ed8)",
shadowColor: "rgba(59,130,246,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
),
href: "/COMPANY_7/pop/inbound/purchase",
},
{
id: "outsourcing",
title: "외주입고",
gradient: "linear-gradient(135deg,#8b5cf6,#6d28d9)",
shadowColor: "rgba(139,92,246,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
),
href: "/COMPANY_7/pop/inbound/subcontractor",
},
{
id: "return",
title: "반품입고",
gradient: "linear-gradient(135deg,#f59e0b,#d97706)",
shadowColor: "rgba(245,158,11,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9 15L3 9m0 0l6-6M3 9h12a6 6 0 010 12h-3" />
</svg>
),
href: "/COMPANY_7/pop/inbound/return-external",
},
{
id: "supplied-material",
title: "사급자재",
gradient: "linear-gradient(135deg,#06b6d4,#0e7490)",
shadowColor: "rgba(6,182,212,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9" />
</svg>
),
href: "/COMPANY_7/pop/inbound/supplied",
},
{
id: "defect",
title: "불량입고",
gradient: "linear-gradient(135deg,#ef4444,#b91c1c)",
shadowColor: "rgba(239,68,68,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
</svg>
),
href: "/COMPANY_7/pop/inbound/error",
},
{
id: "outsource-return",
title: "외주자재회수",
gradient: "linear-gradient(135deg,#ec4899,#be185d)",
shadowColor: "rgba(236,72,153,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 12c0-1.232-.046-2.453-.138-3.662a4.006 4.006 0 00-3.7-3.7 48.678 48.678 0 00-7.324 0 4.006 4.006 0 00-3.7 3.7c-.017.22-.032.441-.046.662M19.5 12l3-3m-3 3l-3-3m-12 3c0 1.232.046 2.453.138 3.662a4.006 4.006 0 003.7 3.7 48.656 48.656 0 007.324 0 4.006 4.006 0 003.7-3.7c.017-.22.032-.441.046-.662M4.5 12l3 3m-3-3l-3 3" />
</svg>
),
href: "/COMPANY_7/pop/inbound/recovery",
},
{
id: "exchange",
title: "교환입고",
gradient: "linear-gradient(135deg,#14b8a6,#0f766e)",
shadowColor: "rgba(20,184,166,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
</svg>
),
href: "/COMPANY_7/pop/inbound/change",
},
];
const INTERNAL_ITEMS: InboundMenuItem[] = [
{
id: "production",
title: "생산입고",
gradient: "linear-gradient(135deg,#22c55e,#15803d)",
shadowColor: "rgba(34,197,94,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
),
href: "/COMPANY_7/pop/inbound/production",
},
{
id: "return-internal",
title: "반납입고",
gradient: "linear-gradient(135deg,#f97316,#c2410c)",
shadowColor: "rgba(249,115,22,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182" />
</svg>
),
href: "/COMPANY_7/pop/inbound/return-internal",
},
{
id: "transfer",
title: "재고이동",
gradient: "linear-gradient(135deg,#64748b,#334155)",
shadowColor: "rgba(100,116,139,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M7.5 7.5h-.75A2.25 2.25 0 004.5 9.75v7.5a2.25 2.25 0 002.25 2.25h7.5a2.25 2.25 0 002.25-2.25v-7.5a2.25 2.25 0 00-2.25-2.25h-.75m0-3l-3-3m0 0l-3 3m3-3v11.25m6-2.25h.75a2.25 2.25 0 012.25 2.25v7.5a2.25 2.25 0 01-2.25 2.25h-7.5a2.25 2.25 0 01-2.25-2.25v-7.5a2.25 2.25 0 012.25-2.25H12m-3 0V5.25" />
</svg>
),
href: "#",
},
{
id: "inbound-manage",
title: "입고관리",
gradient: "linear-gradient(135deg,#3b82f6,#1e40af)",
shadowColor: "rgba(59,130,246,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 11.625a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" />
</svg>
),
href: "/COMPANY_7/pop/inbound/inbound-manage",
},
];
/* 최근 입고 정적 목업 데이터 */
const RECENT_ITEMS: RecentInboundItem[] = [
{
id: "1",
time: "10:14",
type: "구매입고",
itemName: "데모제일 20L (3공정 시연용)",
qty: "20 EA",
supplier: "거래처테스트(발주처)",
statusColor: "text-green-600 bg-green-50",
statusLabel: "완료",
},
{
id: "2",
time: "09:52",
type: "구매입고",
itemName: "용주N_CTG28_반투명",
qty: "10 EA",
supplier: "거래처테스트(발주처)",
statusColor: "text-gray-600 bg-gray-50",
statusLabel: "대기",
},
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
function InboundTypeSelect() {
const router = useRouter();
/* KPI carousel */
const [kpiIdx, setKpiIdx] = useState(1);
const kpiTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const startKpiAuto = useCallback(() => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
kpiTimerRef.current = setInterval(() => setKpiIdx((p) => (p + 1) % 3), 4000);
}, []);
useEffect(() => {
startKpiAuto();
return () => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
};
}, [startKpiAuto]);
const handleMenuClick = (item: InboundMenuItem) => {
if (item.href === "#") {
alert(`${item.title} 화면은 준비 중입니다.`);
} else {
router.push(item.href);
}
};
return (
<div className="flex flex-col gap-5">
{/* ===== Back + Title ===== */}
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/main")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* ===== KPI Carousel ===== */}
<div className="relative overflow-hidden">
<div
className="flex select-none"
style={{
transform: `translateX(-${kpiIdx * 100}%)`,
transition: "transform 0.4s cubic-bezier(.25,.46,.45,.94)",
}}
>
{/* Slide 1 — 금일 입고 현황 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 입고" color="text-blue-600" />
<KpiCell value="0" label="검수 대기" color="text-amber-600" />
<KpiCell value="0" label="완료" color="text-green-600" />
</div>
</div>
</div>
{/* Slide 2 — 유형별 건수 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="완료" color="text-blue-600" />
<KpiCell value="0" label="구매입고" color="text-purple-600" />
<KpiCell value="0" label="외주입고" color="text-gray-600" />
</div>
</div>
</div>
{/* Slide 3 — 수량/품질 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 수량" color="text-blue-600" unit="EA" />
<KpiCell value="0" label="합격률" color="text-green-600" unit="%" />
<KpiCell value="0" label="불량" color="text-red-600" unit="건" />
</div>
</div>
</div>
</div>
{/* Dots */}
<div className="flex justify-center gap-2 mt-3">
{[0, 1, 2].map((idx) => (
<button
key={idx}
onClick={() => {
setKpiIdx(idx);
startKpiAuto();
}}
className="border-none p-0 transition-all duration-300 cursor-pointer"
style={{
width: kpiIdx === idx ? 24 : 8,
height: 8,
borderRadius: kpiIdx === idx ? 4 : "50%",
background: kpiIdx === idx ? "#3b82f6" : "#D1D5DB",
}}
aria-label={`KPI 슬라이드 ${idx + 1}`}
/>
))}
</div>
</div>
{/* ===== External Inbound ===== */}
<section>
<div className="flex items-center gap-2 mb-3">
<div className="w-1 h-5 rounded-full bg-blue-500" />
<h2 className="text-base sm:text-lg font-bold text-gray-900"> </h2>
</div>
<div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
{EXTERNAL_ITEMS.map((item) => (
<MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
))}
</div>
</section>
{/* ===== Internal Inbound ===== */}
<section>
<div className="flex items-center gap-2 mb-3">
<div className="w-1 h-5 rounded-full bg-green-500" />
<h2 className="text-base sm:text-lg font-bold text-gray-900"> </h2>
</div>
<div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
{INTERNAL_ITEMS.map((item) => (
<MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
))}
</div>
</section>
{/* ===== Recent Inbound ===== */}
<section>
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
<h3 className="text-base sm:text-lg font-bold text-gray-900"> </h3>
<span className="text-xs text-gray-400"> 5</span>
</div>
<div className="flex flex-col gap-2">
{RECENT_ITEMS.map((item) => (
<div
key={item.id}
className="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition-colors"
>
<span
className="text-xs font-semibold text-gray-400 min-w-[44px] text-right"
style={{ fontVariantNumeric: "tabular-nums" }}
>
{item.time}
</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-gray-900 truncate">{item.itemName}</span>
<span
className={`text-[10px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${item.statusColor}`}
>
{item.statusLabel}
</span>
</div>
<div className="text-xs text-gray-400 mt-0.5 truncate">
{item.type} | {item.supplier} | {item.qty}
</div>
</div>
</div>
))}
</div>
</div>
</section>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Sub-components */
/* ------------------------------------------------------------------ */
function KpiCell({
value,
label,
color,
unit,
}: {
value: string;
label: string;
color: string;
unit?: string;
}) {
return (
<div className="flex flex-col items-center py-2">
<div className="flex items-end gap-0.5">
<span
className={`text-2xl sm:text-3xl font-extrabold leading-none ${color}`}
style={{ fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}
>
{value}
</span>
{unit && <span className="text-xs text-gray-400 mb-0.5">{unit}</span>}
</div>
<span className="text-[11px] font-medium text-gray-400 mt-1">{label}</span>
</div>
);
}
function MenuIcon({
item,
onClick,
}: {
item: InboundMenuItem;
onClick: (item: InboundMenuItem) => void;
}) {
return (
<div
className="flex flex-col items-center gap-2 w-16 sm:w-[72px] cursor-pointer group"
style={{ WebkitTapHighlightColor: "transparent" }}
onClick={() => onClick(item)}
>
<div
className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center transition-transform duration-150 group-hover:scale-105 group-active:scale-[0.93]"
style={{ background: item.gradient, boxShadow: `0 4px 12px ${item.shadowColor}` }}
>
{item.icon}
</div>
<span className="text-[11px] sm:text-xs font-semibold text-gray-700 text-center leading-tight">
{item.title}
</span>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Page */
/* ------------------------------------------------------------------ */
export default function InboundPage() {
return <InboundTypeSelect />;
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ProductionInbound } from "../../_components/inbound/ProductionInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ProductionInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/production");
};
return (
<ProductionInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="생산입고"
sourceTable="production_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { PurchaseInbound } from "../../_components/inbound/PurchaseInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function PurchaseInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/purchase");
};
return (
<PurchaseInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="구매입고"
sourceTable="purchase_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { RecoveryInbound } from "../../_components/inbound/RecoveryInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function RecoveryInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/recovery");
};
return (
<RecoveryInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="외주자재회수"
sourceTable="recovery_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ReturnExternalInbound } from "../../_components/inbound/ReturnExternalInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ReturnExternalInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/return-external");
};
return (
<ReturnExternalInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="반품입고"
sourceTable="return_external_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ReturnInternalInbound } from "../../_components/inbound/ReturnInternalInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ReturnInternalInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/return-internal");
};
return (
<ReturnInternalInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="반납입고"
sourceTable="return_internal_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SubcontractorInbound } from "../../_components/inbound/SubcontractorInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function SubcontractorInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/subcontractor");
};
return (
<SubcontractorInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="외주입고"
sourceTable="subcontractor_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SuppliedInbound } from "../../_components/inbound/SuppliedInbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function SuppliedInboundPage() {
const router = useRouter();
const cart = useCartSync("inbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/inbound/cart?backUrl=/COMPANY_7/pop/inbound/supplied");
};
return (
<SuppliedInbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
inboundType="사급자재"
sourceTable="supplied_detail"
/>
);
}
@@ -0,0 +1,19 @@
"use client";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { PopShell } from "@/components/pop/hardcoded";
/**
* COMPANY_7 POP 전용 layout
*
* - PopShell을 한 번만 렌더링하여 navigation 간 시계/상태/전체화면 스플래시 유지
* - 타이틀: 업체명 고정 (PopShell 기본값 user?.companyName 사용 → title prop 미전달)
* - 공지 배너: main 화면(/pop/main)에서만 표시
* - 카트 버튼은 각 inbound 컴포넌트가 content 내부에서 렌더링 (테마 색상별)
*/
export default function PopLayout({ children }: { children: ReactNode }) {
const pathname = usePathname();
const isMain = pathname.endsWith("/pop/main");
return <PopShell showBanner={isMain}>{children}</PopShell>;
}
@@ -0,0 +1,148 @@
"use client";
import { useRouter } from "next/navigation";
import type React from "react";
import { KpiCarousel, RecentActivity } from "@/components/pop/hardcoded";
interface MenuIconItem {
id: string;
title: string;
gradient: string;
shadowColor: string;
icon: React.ReactNode;
href: string;
}
const MENU_ITEMS: MenuIconItem[] = [
{
id: "incoming",
title: "입고",
gradient: "linear-gradient(135deg,#3b82f6,#1d4ed8)",
shadowColor: "rgba(59,130,246,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
</svg>
),
href: "/COMPANY_7/pop/inbound",
},
{
id: "outgoing",
title: "출고",
gradient: "linear-gradient(135deg,#22c55e,#15803d)",
shadowColor: "rgba(34,197,94,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0H6.75m11.25 0h2.625c.621 0 1.125-.504 1.125-1.125v-4.875c0-.621-.504-1.125-1.125-1.125H17.25m-13.5-.375V6.375c0-.621.504-1.125 1.125-1.125h7.5c.621 0 1.125.504 1.125 1.125v7.125" />
</svg>
),
href: "/COMPANY_7/pop/outbound",
},
{
id: "production",
title: "생산",
gradient: "linear-gradient(135deg,#f59e0b,#d97706)",
shadowColor: "rgba(245,158,11,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
),
href: "/COMPANY_7/pop/production",
},
{
id: "quality",
title: "품질",
gradient: "linear-gradient(135deg,#ef4444,#b91c1c)",
shadowColor: "rgba(239,68,68,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
),
href: "#",
},
{
id: "equipment",
title: "설비",
gradient: "linear-gradient(135deg,#8b5cf6,#6d28d9)",
shadowColor: "rgba(139,92,246,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
),
href: "#",
},
{
id: "inventory",
title: "재고",
gradient: "linear-gradient(135deg,#06b6d4,#0e7490)",
shadowColor: "rgba(6,182,212,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
</svg>
),
href: "#",
},
{
id: "safety",
title: "안전관리",
gradient: "linear-gradient(135deg,#f97316,#c2410c)",
shadowColor: "rgba(249,115,22,.3)",
icon: (
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m0-10.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.75c0 5.592 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.57-.598-3.75h-.152c-3.196 0-6.1-1.249-8.25-3.286zm0 13.036h.008v.008H12v-.008z" />
</svg>
),
href: "#",
},
];
function LocalMenuIcons() {
const router = useRouter();
const handleClick = (item: MenuIconItem) => {
if (item.href === "#") {
alert(`${item.title} 화면은 준비 중입니다.`);
return;
}
router.push(item.href);
};
return (
<section>
<h2 className="text-xl sm:text-[22px] font-bold text-gray-900 tracking-tight mb-4"></h2>
<div className="flex flex-wrap justify-center gap-x-6 gap-y-5 sm:gap-x-8 sm:gap-y-6 lg:gap-x-10">
{MENU_ITEMS.map((item) => (
<div
key={item.id}
className="flex flex-col items-center gap-2 w-16 sm:w-20 cursor-pointer group"
style={{ WebkitTapHighlightColor: "transparent" }}
onClick={() => handleClick(item)}
>
<div
className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center transition-transform duration-150 group-hover:scale-110 group-active:scale-[0.93]"
style={{ background: item.gradient, boxShadow: `0 4px 12px ${item.shadowColor}` }}
>
{item.icon}
</div>
<span className="text-xs sm:text-sm font-semibold text-gray-700">{item.title}</span>
</div>
))}
</div>
</section>
);
}
export default function PopMainPage() {
return (
<>
<KpiCarousel />
<LocalMenuIcons />
<RecentActivity />
</>
);
}
@@ -0,0 +1,26 @@
"use client";
import { useSearchParams } from "next/navigation";
import { Suspense } from "react";
import { OutboundCartPage } from "../../_components/outbound/OutboundCartPage";
function OutboundCartContent() {
const searchParams = useSearchParams();
const backUrl = searchParams.get("backUrl") || "/COMPANY_7/pop/outbound";
return <OutboundCartPage backUrl={backUrl} />;
}
export default function OutboundCartRoute() {
return (
<Suspense
fallback={
<div className="flex items-center justify-center py-12 text-sm text-gray-400">
...
</div>
}
>
<OutboundCartContent />
</Suspense>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { EtcOutbound } from "../../_components/outbound/EtcOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function EtcOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/etc");
};
return (
<EtcOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="기타출고"
sourceTable="etc_outbound_detail"
/>
);
}
@@ -0,0 +1,7 @@
"use client";
import { OutboundManage } from "../../_components/outbound/OutboundManage";
export default function OutboundManagePage() {
return <OutboundManage />;
}
@@ -0,0 +1,402 @@
"use client";
import React, { useState, useRef, useCallback, useEffect } from "react";
import { useRouter } from "next/navigation";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface OutboundMenuItem {
id: string;
title: string;
gradient: string;
shadowColor: string;
icon: React.ReactNode;
href: string;
}
interface RecentOutboundItem {
id: string;
time: string;
type: string;
itemName: string;
qty: string;
supplier: string;
statusColor: string;
statusLabel: string;
}
/* ------------------------------------------------------------------ */
/* Static Data (UI만) */
/* ------------------------------------------------------------------ */
const EXTERNAL_ITEMS: OutboundMenuItem[] = [
{
id: "sales",
title: "판매출고",
gradient: "linear-gradient(135deg,#22c55e,#15803d)",
shadowColor: "rgba(34,197,94,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
</svg>
),
href: "/COMPANY_7/pop/outbound/sales",
},
{
id: "return",
title: "반품출고",
gradient: "linear-gradient(135deg,#64748b,#334155)",
shadowColor: "rgba(100,116,139,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9 15L3 9m0 0l6-6M3 9h12a6 6 0 010 12h-3" />
</svg>
),
href: "/COMPANY_7/pop/outbound/return",
},
{
id: "subcontractor",
title: "외주출고",
gradient: "linear-gradient(135deg,#8b5cf6,#6d28d9)",
shadowColor: "rgba(139,92,246,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
</svg>
),
href: "/COMPANY_7/pop/outbound/subcontractor",
},
{
id: "supplied",
title: "사급출고",
gradient: "linear-gradient(135deg,#06b6d4,#0e7490)",
shadowColor: "rgba(6,182,212,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9" />
</svg>
),
href: "/COMPANY_7/pop/outbound/supplied",
},
{
id: "etc",
title: "기타출고",
gradient: "linear-gradient(135deg,#475569,#1e293b)",
shadowColor: "rgba(71,85,105,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
</svg>
),
href: "/COMPANY_7/pop/outbound/etc",
},
];
const INTERNAL_ITEMS: OutboundMenuItem[] = [
{
id: "production",
title: "생산출고",
gradient: "linear-gradient(135deg,#f97316,#c2410c)",
shadowColor: "rgba(249,115,22,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
),
href: "/COMPANY_7/pop/outbound/production",
},
{
id: "transfer",
title: "재고이동",
gradient: "linear-gradient(135deg,#fb923c,#ea580c)",
shadowColor: "rgba(251,146,60,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
</svg>
),
href: "#",
},
{
id: "outbound-manage",
title: "출고관리",
gradient: "linear-gradient(135deg,#10b981,#047857)",
shadowColor: "rgba(16,185,129,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.375c.621 0 1.125.504 1.125 1.125V18a2.25 2.25 0 01-2.25 2.25M16.5 7.5V18a2.25 2.25 0 002.25 2.25M16.5 7.5V4.875c0-.621-.504-1.125-1.125-1.125H4.125C3.504 3.75 3 4.254 3 4.875V18a2.25 2.25 0 002.25 2.25h13.5M6 7.5h3v3H6v-3z" />
</svg>
),
href: "/COMPANY_7/pop/outbound/outbound-manage",
},
];
/* 최근 출고 정적 목업 데이터 */
const RECENT_ITEMS: RecentOutboundItem[] = [
{
id: "1",
time: "10:14",
type: "판매출고",
itemName: "데모제일 20L (3공정 시연용)",
qty: "20 EA",
supplier: "거래처테스트(발주처)",
statusColor: "text-green-600 bg-green-50",
statusLabel: "완료",
},
{
id: "2",
time: "09:52",
type: "외주출고",
itemName: "용주N_CTG28_반투명",
qty: "10 EA",
supplier: "거래처테스트(발주처)",
statusColor: "text-gray-600 bg-gray-50",
statusLabel: "대기",
},
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
function OutboundTypeSelect() {
const router = useRouter();
/* KPI carousel */
const [kpiIdx, setKpiIdx] = useState(1);
const kpiTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const startKpiAuto = useCallback(() => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
kpiTimerRef.current = setInterval(() => setKpiIdx((p) => (p + 1) % 3), 4000);
}, []);
useEffect(() => {
startKpiAuto();
return () => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
};
}, [startKpiAuto]);
const handleMenuClick = (item: OutboundMenuItem) => {
if (item.href === "#") {
alert(`${item.title} 화면은 준비 중입니다.`);
} else {
router.push(item.href);
}
};
return (
<div className="flex flex-col gap-5">
{/* ===== Back + Title ===== */}
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/main")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* ===== KPI Carousel ===== */}
<div className="relative overflow-hidden">
<div
className="flex select-none"
style={{
transform: `translateX(-${kpiIdx * 100}%)`,
transition: "transform 0.4s cubic-bezier(.25,.46,.45,.94)",
}}
>
{/* Slide 1 — 금일 출고 현황 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 출고" color="text-blue-600" />
<KpiCell value="0" label="출고 대기" color="text-amber-600" />
<KpiCell value="0" label="완료" color="text-green-600" />
</div>
</div>
</div>
{/* Slide 2 — 유형별 건수 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="완료" color="text-blue-600" />
<KpiCell value="0" label="판매출고" color="text-purple-600" />
<KpiCell value="0" label="외주출고" color="text-gray-600" />
</div>
</div>
</div>
{/* Slide 3 — 수량/출고율 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 수량" color="text-blue-600" unit="EA" />
<KpiCell value="0" label="출고율" color="text-green-600" unit="%" />
<KpiCell value="0" label="반품" color="text-red-600" unit="건" />
</div>
</div>
</div>
</div>
{/* Dots */}
<div className="flex justify-center gap-2 mt-3">
{[0, 1, 2].map((idx) => (
<button
key={idx}
onClick={() => {
setKpiIdx(idx);
startKpiAuto();
}}
className="border-none p-0 transition-all duration-300 cursor-pointer"
style={{
width: kpiIdx === idx ? 24 : 8,
height: 8,
borderRadius: kpiIdx === idx ? 4 : "50%",
background: kpiIdx === idx ? "#3b82f6" : "#D1D5DB",
}}
aria-label={`KPI 슬라이드 ${idx + 1}`}
/>
))}
</div>
</div>
{/* ===== External Outbound ===== */}
<section>
<div className="flex items-center gap-2 mb-3">
<div className="w-1 h-5 rounded-full bg-blue-500" />
<h2 className="text-base sm:text-lg font-bold text-gray-900"> </h2>
</div>
<div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
{EXTERNAL_ITEMS.map((item) => (
<MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
))}
</div>
</section>
{/* ===== Internal Outbound ===== */}
<section>
<div className="flex items-center gap-2 mb-3">
<div className="w-1 h-5 rounded-full bg-green-500" />
<h2 className="text-base sm:text-lg font-bold text-gray-900"> </h2>
</div>
<div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
{INTERNAL_ITEMS.map((item) => (
<MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
))}
</div>
</section>
{/* ===== Recent Outbound ===== */}
<section>
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
<h3 className="text-base sm:text-lg font-bold text-gray-900"> </h3>
<span className="text-xs text-gray-400"> 5</span>
</div>
<div className="flex flex-col gap-2">
{RECENT_ITEMS.map((item) => (
<div
key={item.id}
className="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition-colors"
>
<span
className="text-xs font-semibold text-gray-400 min-w-[44px] text-right"
style={{ fontVariantNumeric: "tabular-nums" }}
>
{item.time}
</span>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-semibold text-gray-900 truncate">{item.itemName}</span>
<span
className={`text-[10px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${item.statusColor}`}
>
{item.statusLabel}
</span>
</div>
<div className="text-xs text-gray-400 mt-0.5 truncate">
{item.type} | {item.supplier} | {item.qty}
</div>
</div>
</div>
))}
</div>
</div>
</section>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Sub-components */
/* ------------------------------------------------------------------ */
function KpiCell({
value,
label,
color,
unit,
}: {
value: string;
label: string;
color: string;
unit?: string;
}) {
return (
<div className="flex flex-col items-center py-2">
<div className="flex items-end gap-0.5">
<span
className={`text-2xl sm:text-3xl font-extrabold leading-none ${color}`}
style={{ fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}
>
{value}
</span>
{unit && <span className="text-xs text-gray-400 mb-0.5">{unit}</span>}
</div>
<span className="text-[11px] font-medium text-gray-400 mt-1">{label}</span>
</div>
);
}
function MenuIcon({
item,
onClick,
}: {
item: OutboundMenuItem;
onClick: (item: OutboundMenuItem) => void;
}) {
return (
<div
className="flex flex-col items-center gap-2 w-16 sm:w-[72px] cursor-pointer group"
style={{ WebkitTapHighlightColor: "transparent" }}
onClick={() => onClick(item)}
>
<div
className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center transition-transform duration-150 group-hover:scale-105 group-active:scale-[0.93]"
style={{ background: item.gradient, boxShadow: `0 4px 12px ${item.shadowColor}` }}
>
{item.icon}
</div>
<span className="text-[11px] sm:text-xs font-semibold text-gray-700 text-center leading-tight">
{item.title}
</span>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Page */
/* ------------------------------------------------------------------ */
export default function OutboundPage() {
return <OutboundTypeSelect />;
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ProductionOutbound } from "../../_components/outbound/ProductionOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ProductionOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/production");
};
return (
<ProductionOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="생산출고"
sourceTable="production_outbound_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ReturnOutbound } from "../../_components/outbound/ReturnOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function ReturnOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/return");
};
return (
<ReturnOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="반품출고"
sourceTable="return_outbound_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SalesOutbound } from "../../_components/outbound/SalesOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function SalesOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/sales");
};
return (
<SalesOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="판매출고"
sourceTable="shipment_instruction_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SubcontractorOutbound } from "../../_components/outbound/SubcontractorOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function SubcontractorOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/subcontractor");
};
return (
<SubcontractorOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="외주출고"
sourceTable="outsource_outbound_detail"
/>
);
}
@@ -0,0 +1,32 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { SuppliedOutbound } from "../../_components/outbound/SuppliedOutbound";
import { useCartSync } from "../../_components/common/useCartSync";
export default function SuppliedOutboundPage() {
const router = useRouter();
const cart = useCartSync("outbound");
const [saving, setSaving] = useState(false);
const handleCartClick = async () => {
if (cart.isDirty) {
setSaving(true);
const ok = await cart.saveToDb();
setSaving(false);
if (!ok) return;
}
router.push("/COMPANY_7/pop/outbound/cart?backUrl=/COMPANY_7/pop/outbound/supplied");
};
return (
<SuppliedOutbound
cart={cart}
onCartClick={handleCartClick}
saving={saving}
outboundType="사급출고"
sourceTable="supplied_outbound_detail"
/>
);
}
@@ -0,0 +1,242 @@
"use client";
import React, { useState, useRef, useCallback, useEffect } from "react";
import { useRouter } from "next/navigation";
/* ------------------------------------------------------------------ */
/* Types */
/* ------------------------------------------------------------------ */
interface ProductionMenuItem {
id: string;
title: string;
gradient: string;
shadowColor: string;
icon: React.ReactNode;
href: string;
}
/* ------------------------------------------------------------------ */
/* Static Data */
/* ------------------------------------------------------------------ */
const MENU_ITEMS: ProductionMenuItem[] = [
{
id: "process-execution",
title: "공정실행",
gradient: "linear-gradient(135deg,#f59e0b,#d97706)",
shadowColor: "rgba(245,158,11,.3)",
icon: (
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
),
href: "/COMPANY_7/pop/production/process",
},
];
/* ------------------------------------------------------------------ */
/* Component */
/* ------------------------------------------------------------------ */
function ProductionMenu() {
const router = useRouter();
/* KPI carousel */
const [kpiIdx, setKpiIdx] = useState(0);
const kpiTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const startKpiAuto = useCallback(() => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
kpiTimerRef.current = setInterval(() => setKpiIdx((p) => (p + 1) % 3), 4000);
}, []);
useEffect(() => {
startKpiAuto();
return () => {
if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
};
}, [startKpiAuto]);
const handleMenuClick = (item: ProductionMenuItem) => {
if (item.href === "#") {
alert(`${item.title} 화면은 준비 중입니다.`);
} else {
router.push(item.href);
}
};
return (
<div className="flex flex-col gap-5">
{/* ===== Back + Title ===== */}
<div className="flex items-center gap-3">
<button
onClick={() => router.push("/COMPANY_7/pop/main")}
className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
</svg>
</button>
<div>
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 tracking-tight"></h1>
<p className="text-xs text-gray-400 mt-0.5"> </p>
</div>
</div>
{/* ===== KPI Carousel ===== */}
<div className="relative overflow-hidden">
<div
className="flex select-none"
style={{
transform: `translateX(-${kpiIdx * 100}%)`,
transition: "transform 0.4s cubic-bezier(.25,.46,.45,.94)",
}}
>
{/* Slide 1 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 생산" color="text-amber-600" />
<KpiCell value="0" label="진행 중" color="text-blue-600" />
<KpiCell value="0" label="완료" color="text-green-600" />
</div>
</div>
</div>
{/* Slide 2 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="작업지시" color="text-amber-600" unit="건" />
<KpiCell value="0" label="공정완료" color="text-green-600" unit="건" />
<KpiCell value="0" label="불량" color="text-red-600" unit="건" />
</div>
</div>
</div>
{/* Slide 3 */}
<div className="min-w-full shrink-0">
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="grid grid-cols-3 gap-0">
<KpiCell value="0" label="금일 수량" color="text-amber-600" unit="EA" />
<KpiCell value="0" label="달성률" color="text-green-600" unit="%" />
<KpiCell value="0" label="불량률" color="text-red-600" unit="%" />
</div>
</div>
</div>
</div>
{/* Dots */}
<div className="flex justify-center gap-2 mt-3">
{[0, 1, 2].map((idx) => (
<button
key={idx}
onClick={() => {
setKpiIdx(idx);
startKpiAuto();
}}
className="border-none p-0 transition-all duration-300 cursor-pointer"
style={{
width: kpiIdx === idx ? 24 : 8,
height: 8,
borderRadius: kpiIdx === idx ? 4 : "50%",
background: kpiIdx === idx ? "#f59e0b" : "#D1D5DB",
}}
aria-label={`KPI 슬라이드 ${idx + 1}`}
/>
))}
</div>
</div>
{/* ===== Production Menu ===== */}
<section>
<div className="flex items-center gap-2 mb-3">
<div className="w-1 h-5 rounded-full bg-amber-500" />
<h2 className="text-base sm:text-lg font-bold text-gray-900"> </h2>
</div>
<div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
{MENU_ITEMS.map((item) => (
<MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
))}
</div>
</section>
{/* ===== Recent Activity ===== */}
<section>
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
<div className="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
<h3 className="text-base sm:text-lg font-bold text-gray-900"> </h3>
<span className="text-xs text-gray-400"> 5</span>
</div>
<div className="flex items-center justify-center py-8">
<p className="text-sm text-gray-400"> </p>
</div>
</div>
</section>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Sub-components */
/* ------------------------------------------------------------------ */
function KpiCell({
value,
label,
color,
unit,
}: {
value: string;
label: string;
color: string;
unit?: string;
}) {
return (
<div className="flex flex-col items-center py-2">
<div className="flex items-end gap-0.5">
<span
className={`text-2xl sm:text-3xl font-extrabold leading-none ${color}`}
style={{ fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}
>
{value}
</span>
{unit && <span className="text-xs text-gray-400 mb-0.5">{unit}</span>}
</div>
<span className="text-[11px] font-medium text-gray-400 mt-1">{label}</span>
</div>
);
}
function MenuIcon({
item,
onClick,
}: {
item: ProductionMenuItem;
onClick: (item: ProductionMenuItem) => void;
}) {
return (
<div
className="flex flex-col items-center gap-2 w-16 sm:w-[72px] cursor-pointer group"
style={{ WebkitTapHighlightColor: "transparent" }}
onClick={() => onClick(item)}
>
<div
className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center transition-transform duration-150 group-hover:scale-105 group-active:scale-[0.93]"
style={{ background: item.gradient, boxShadow: `0 4px 12px ${item.shadowColor}` }}
>
{item.icon}
</div>
<span className="text-[11px] sm:text-xs font-semibold text-gray-700 text-center leading-tight">
{item.title}
</span>
</div>
);
}
/* ------------------------------------------------------------------ */
/* Page */
/* ------------------------------------------------------------------ */
export default function ProductionPage() {
return <ProductionMenu />;
}