feat(quote): 거절 액션 + 의뢰 상태 동기화 + 관리자 알림

This commit is contained in:
2026-06-12 05:31:25 +09:00
parent 5ceae7e90b
commit d62653e834
2 changed files with 136 additions and 25 deletions

View File

@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { createAdminClient } from '@/lib/supabase/admin'; import { createAdminClient } from '@/lib/supabase/admin';
import { sendQuoteDecisionEmail } from '@/lib/request-emails';
export const runtime = 'nodejs'; export const runtime = 'nodejs';
@@ -24,21 +25,30 @@ export async function GET(_req: Request, { params }: { params: Promise<{ token:
return NextResponse.json({ quote: data, expired }); return NextResponse.json({ quote: data, expired });
} }
// 고객이 견적 수락 // 고객이 견적 수락/거절
export async function POST(request: Request, { params }: { params: Promise<{ token: string }> }) { export async function POST(request: Request, { params }: { params: Promise<{ token: string }> }) {
const { token } = await params; const { token } = await params;
const body = await request.json(); // { selectedItems, selectedMaintenance } const body = await request.json(); // { action?, selectedItems, selectedMaintenance, total }
const action: 'accept' | 'reject' = body.action === 'reject' ? 'reject' : 'accept';
const supabase = createAdminClient(); const supabase = createAdminClient();
const { data: quote, error: findErr } = await supabase const { data: quote, error: findErr } = await supabase
.from('quotes') .from('quotes')
.select('id, title, client_name, client_email') .select('id, title, client_name, client_email, status, contact_request_id')
.eq('public_token', token) .eq('public_token', token)
.single(); .single();
if (findErr || !quote) return NextResponse.json({ error: 'Not found' }, { status: 404 }); if (findErr || !quote) return NextResponse.json({ error: 'Not found' }, { status: 404 });
// 상태를 accepted로 변경 // 이미 처리된 견적 중복 처리 방지
if (quote.status === 'accepted' || quote.status === 'rejected') {
return NextResponse.json({ error: '이미 처리된 견적입니다' }, { status: 409 });
}
const now = new Date().toISOString();
if (action === 'accept') {
// 상태를 accepted로 변경 (기존 로직 유지)
await supabase await supabase
.from('quotes') .from('quotes')
.update({ .update({
@@ -46,9 +56,48 @@ export async function POST(request: Request, { params }: { params: Promise<{ tok
accepted_items: body.selectedItems, accepted_items: body.selectedItems,
accepted_maintenance: body.selectedMaintenance, accepted_maintenance: body.selectedMaintenance,
accepted_total: body.total, accepted_total: body.total,
updated_at: new Date().toISOString(), updated_at: now,
}) })
.eq('id', quote.id); .eq('id', quote.id);
} else {
// 상태를 rejected로 변경 (accepted_* 미기록)
await supabase
.from('quotes')
.update({
status: 'rejected',
updated_at: now,
})
.eq('id', quote.id);
}
// 연결된 의뢰 상태 동기화 (실패 시 무시)
if (quote.contact_request_id) {
try {
const crStatus = action === 'accept' ? 'accepted' : 'on_hold';
await supabase
.from('contact_requests')
.update({ status: crStatus, updated_at: now })
.eq('id', quote.contact_request_id);
} catch (e) {
console.error('[quote POST] contact_request sync failed:', e);
}
}
// 관리자 알림 메일 (실패 시 무시)
try {
const decision = action === 'accept' ? 'accepted' : 'rejected';
const totalValue = action === 'accept' && typeof body.total === 'number' && Number.isFinite(body.total)
? body.total
: undefined;
await sendQuoteDecisionEmail({
decision,
quoteTitle: quote.title,
clientName: quote.client_name || '고객',
total: totalValue,
});
} catch (e) {
console.error('[quote POST] sendQuoteDecisionEmail failed:', e);
}
return NextResponse.json({ success: true }); return NextResponse.json({ success: true });
} }

View File

@@ -37,6 +37,8 @@ export default function QuotePage() {
const [activeTab, setActiveTab] = useState<'overview' | 'wbs' | 'quote' | 'maintenance'>('overview'); const [activeTab, setActiveTab] = useState<'overview' | 'wbs' | 'quote' | 'maintenance'>('overview');
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [submitted, setSubmitted] = useState(false); const [submitted, setSubmitted] = useState(false);
const [rejected, setRejected] = useState(false);
const [alreadyProcessed, setAlreadyProcessed] = useState(false);
const [isPrinting, setIsPrinting] = useState(false); const [isPrinting, setIsPrinting] = useState(false);
useEffect(() => { useEffect(() => {
@@ -89,15 +91,31 @@ export default function QuotePage() {
if (!quote) return; if (!quote) return;
setSubmitting(true); setSubmitting(true);
const selectedItems = quote.items.filter((i) => !i.optional || checkedOptional[i.id]).map((i) => i.id); const selectedItems = quote.items.filter((i) => !i.optional || checkedOptional[i.id]).map((i) => i.id);
await fetch(`/api/quote/${token}`, { const res = await fetch(`/api/quote/${token}`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ selectedItems, selectedMaintenance, total: grandTotal }), body: JSON.stringify({ selectedItems, selectedMaintenance, total: grandTotal }),
}); });
setSubmitting(false); setSubmitting(false);
if (res.status === 409) { setAlreadyProcessed(true); return; }
setSubmitted(true); setSubmitted(true);
} }
async function handleReject() {
if (!quote) return;
const confirmed = window.confirm('견적을 거절하시겠습니까? 조건 조정이 필요하시면 회신으로 말씀해 주세요.');
if (!confirmed) return;
setSubmitting(true);
const res = await fetch(`/api/quote/${token}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'reject' }),
});
setSubmitting(false);
if (res.status === 409) { setAlreadyProcessed(true); return; }
setRejected(true);
}
if (loading) { if (loading) {
return ( return (
<div style={{ minHeight: '100vh', background: 'var(--jsm-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <div style={{ minHeight: '100vh', background: 'var(--jsm-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
@@ -141,6 +159,30 @@ export default function QuotePage() {
); );
} }
if (rejected) {
return (
<div style={{ minHeight: '100vh', background: 'var(--jsm-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 20, padding: 24 }}>
<style>{`@keyframes pop { 0% { transform: scale(0.5); opacity: 0; } 70% { transform: scale(1.1); } 100% { transform: scale(1); opacity: 1; } }`}</style>
<div style={{ fontSize: 80, animation: 'pop 0.5s ease forwards' }}>🙏</div>
<h1 style={{ color: 'var(--jsm-ink)', fontSize: 28, fontWeight: 800, fontFamily: 'sans-serif', textAlign: 'center' }}> </h1>
<p style={{ color: 'var(--jsm-ink-soft)', fontFamily: 'sans-serif', textAlign: 'center', lineHeight: 1.7 }}>
.<br />
.
</p>
</div>
);
}
if (alreadyProcessed) {
return (
<div style={{ minHeight: '100vh', background: 'var(--jsm-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16, padding: 24 }}>
<div style={{ fontSize: 64 }}>📋</div>
<h1 style={{ color: 'var(--jsm-ink)', fontSize: 24, fontWeight: 700, fontFamily: 'sans-serif', textAlign: 'center' }}> </h1>
<p style={{ color: 'var(--jsm-ink-soft)', fontFamily: 'sans-serif', textAlign: 'center' }}> .</p>
</div>
);
}
const tabs = [ const tabs = [
{ key: 'overview', label: '개요' }, { key: 'overview', label: '개요' },
{ key: 'wbs', label: 'WBS', show: quote.wbs.length > 0 }, { key: 'wbs', label: 'WBS', show: quote.wbs.length > 0 },
@@ -533,6 +575,18 @@ export default function QuotePage() {
)} )}
</div> </div>
</div> </div>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<button onClick={handleReject} disabled={submitting}
style={{
padding: '14px 24px', borderRadius: 12, border: '1px solid rgba(255,255,255,0.25)', cursor: 'pointer',
background: 'transparent',
color: 'rgba(255,255,255,0.75)', fontSize: 15, fontWeight: 600, transition: 'all 0.2s',
opacity: submitting ? 0.5 : 1,
}}
onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; e.currentTarget.style.color = 'white'; }}
onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.75)'; }}>
</button>
<button onClick={handleAccept} disabled={submitting} <button onClick={handleAccept} disabled={submitting}
style={{ style={{
padding: '14px 36px', borderRadius: 12, border: 'none', cursor: 'pointer', padding: '14px 36px', borderRadius: 12, border: 'none', cursor: 'pointer',
@@ -545,6 +599,7 @@ export default function QuotePage() {
</button> </button>
</div> </div>
</div> </div>
</div>
)} )}
{/* 수락된 경우 */} {/* 수락된 경우 */}
@@ -554,6 +609,13 @@ export default function QuotePage() {
</div> </div>
)} )}
{/* 거절된 경우 */}
{quote.status === 'rejected' && (
<div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, background: 'rgba(100,116,139,0.08)', borderTop: '1px solid rgba(100,116,139,0.3)', padding: '16px 24px', textAlign: 'center' }}>
<p style={{ color: '#64748b', fontWeight: 600, fontSize: 16 }}> </p>
</div>
)}
{/* 하단 여백 */} {/* 하단 여백 */}
<div style={{ height: 80 }} /> <div style={{ height: 80 }} />
</div> </div>