| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521 |
- 'use client';
- import { useState, useEffect, useMemo } from 'react';
- import api from '@/lib/api';
- import {
- X,
- User,
- Package,
- CreditCard,
- History,
- Copy,
- Check,
- ExternalLink,
- DollarSign,
- Wallet,
- Edit,
- Clock,
- Mail,
- Phone,
- FileSpreadsheet,
- XCircle,
- Loader2,
- } from 'lucide-react';
- import LocalTime from '@/components/common/LocalTime';
- import { getPaymentProviderIcon } from '@/components/admin/payments/paymentIcons';
- import { OrderDetail, PaymentRecord, PaymentQrDetail, UserDetail, OrderEvent, ExtendedOrderDetail } from '@/types';
- interface OrderDetailDrawerProps {
- isOpen: boolean;
- onClose: () => void;
- order: ExtendedOrderDetail | null;
- onAdjustPrice?: (order: OrderDetail) => void;
- onCheckPayments?: (order: OrderDetail) => void;
- onEdit?: (order: OrderDetail) => void;
- onCancel?: (orderId: string) => void;
- }
- const FIELD_DISPLAY_ORDER = [
- 'first_name',
- 'last_name',
- 'name',
- 'applicant_name',
- 'passport_no',
- 'birthday',
- 'gender',
- 'email',
- 'phone_country_code',
- 'phone',
- 'destination_country',
- 'visa_type',
- 'departure_date',
- 'social_media_account',
- ];
- export default function OrderDetailDrawer({
- isOpen,
- onClose,
- order,
- onAdjustPrice,
- onCheckPayments,
- onEdit,
- onCancel,
- }: OrderDetailDrawerProps) {
- const [paymentList, setPaymentList] = useState<PaymentRecord[]>([]);
- const [loadingPayments, setLoadingPayments] = useState(false);
- const [userData, setUserData] = useState<UserDetail | null>(null);
- const [loadingUser, setLoadingUser] = useState(false);
- const [qrDetails, setQrDetails] = useState<Record<number, PaymentQrDetail>>({});
- const [events, setEvents] = useState<OrderEvent[]>([]);
- const [loadingEvents, setLoadingEvents] = useState(false);
- const [copiedKey, setCopiedKey] = useState<string | null>(null);
- const [copiedAllInputs, setCopiedAllInputs] = useState(false);
- useEffect(() => {
- if (isOpen && order?.id) {
- fetchPayments(order.id);
- fetchEvents(order.id);
- if (order.user_id) {
- fetchUserDetails(order.user_id);
- } else {
- setUserData(null);
- }
- } else {
- setPaymentList([]);
- setEvents([]);
- setUserData(null);
- }
- }, [isOpen, order]);
- const fetchPayments = async (orderId: string) => {
- setLoadingPayments(true);
- try {
- const res = await api.get('/api/vas/payment/list_by_order', { params: { order_id: orderId } });
- const list = Array.isArray(res.data?.data) ? res.data.data : Array.isArray(res.data) ? res.data : [];
- setPaymentList(list);
- } catch {
- setPaymentList([]);
- } finally {
- setLoadingPayments(false);
- }
- };
- const fetchEvents = async (orderId: string) => {
- setLoadingEvents(true);
- try {
- const res = await api.get('/api/vas/order-event/list', { params: { order_id: orderId } });
- const list = Array.isArray(res.data?.data) ? res.data.data : [];
- setEvents(list);
- } catch {
- setEvents([]);
- } finally {
- setLoadingEvents(false);
- }
- };
- const fetchUserDetails = async (userId: string) => {
- setLoadingUser(true);
- try {
- const res = await api.get('/api/user/get_by_id', { params: { user_id: userId } });
- setUserData(res.data?.data || null);
- } catch {
- setUserData(null);
- } finally {
- setLoadingUser(false);
- }
- };
- const sortedUserInputs = useMemo(() => {
- if (!order?.user_inputs) return [];
- return Object.entries(order.user_inputs).sort(([keyA], [keyB]) => {
- const indexA = FIELD_DISPLAY_ORDER.indexOf(keyA);
- const indexB = FIELD_DISPLAY_ORDER.indexOf(keyB);
- if (indexA !== -1 && indexB !== -1) return indexA - indexB;
- if (indexA !== -1) return -1;
- if (indexB !== -1) return 1;
- return 0;
- });
- }, [order?.user_inputs]);
- useEffect(() => {
- const qrIds = paymentList.map((p) => p.qr_id).filter(Boolean) as number[];
- if (qrIds.length === 0) return;
- const fetchDetails = async () => {
- const detailMap: Record<number, PaymentQrDetail> = {};
- await Promise.all(
- Array.from(new Set(qrIds)).map(async (qrId) => {
- try {
- const res = await api.get('/api/vas/payment-qr/get', { params: { qr_id: qrId } });
- if (res.data?.data) {
- detailMap[qrId] = res.data.data;
- }
- } catch {
- // ignore
- }
- })
- );
- setQrDetails(detailMap);
- };
- fetchDetails();
- }, [paymentList]);
- const copyText = (key: string, text: string) => {
- navigator.clipboard.writeText(text);
- setCopiedKey(key);
- setTimeout(() => setCopiedKey(null), 2000);
- };
- const handleCopyAllInputs = () => {
- if (!order?.user_inputs) return;
- const formatted = JSON.stringify(order.user_inputs, null, 2);
- navigator.clipboard.writeText(formatted);
- setCopiedAllInputs(true);
- setTimeout(() => setCopiedAllInputs(false), 2000);
- };
- if (!isOpen || !order) return null;
- const currency = order.base_currency || 'CNY';
- const baseAmount = order.base_amount || 0;
- const finalAmount = order.final_amount !== undefined ? order.final_amount : baseAmount;
- const isAdjusted = finalAmount !== baseAmount;
- const delta = order.adjustment_delta ?? (finalAmount - baseAmount);
- const isPending = (order.status || '').toLowerCase() === 'pending';
- const isPaid = ['paid', 'succeeded', 'completed'].includes((order.status || '').toLowerCase());
- const isCancelled = (order.status || '').toLowerCase() === 'cancelled';
- const formatMoney = (amount: number, curr = currency) => {
- const symbol = curr === 'CNY' ? '¥' : curr === 'USD' ? '$' : `${curr} `;
- return `${symbol}${(amount / 100).toFixed(2)}`;
- };
- const formatStripeMode = (id: string) => (id.includes('_live_') ? 'live' : 'test');
- const getStripeLink = (pay: PaymentRecord) => {
- if (pay.provider.toLowerCase() !== 'stripe') return undefined;
- const id = pay.payment_intent_id;
- if (!id) return undefined;
- const mode = formatStripeMode(id);
- const resourcePath = id.startsWith('cs_') ? 'checkout/sessions' : 'payments';
- return `https://dashboard.stripe.com/${mode}/${resourcePath}/${id}`;
- };
- const displayEmail = userData?.email || order.user?.email || order.user_email || '未关联邮箱';
- const displayNickname = userData?.nickname || order.user_name || order.user?.nickname || order.applicant_name || '-';
- const displayPhone = userData?.phone || order.user?.phone || '-';
- return (
- <div className="fixed inset-0 z-50 flex justify-end bg-black/60 backdrop-grayscale font-mono">
- <div className="absolute inset-0" onClick={onClose} />
- {/* Drawer Body */}
- <div className="relative w-full max-w-2xl bg-neutral-50 h-full border-l-2 border-black shadow-[8px_0px_0px_#000] flex flex-col z-10 animate-in slide-in-from-right duration-200 overflow-hidden">
-
- {/* Drawer Header */}
- <div className="bg-neutral-200 px-5 py-3.5 border-b-2 border-black shrink-0 flex items-center justify-between select-none">
- <div className="flex items-center gap-2">
- <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
- <h3 className="font-black text-black text-xs sm:text-sm uppercase tracking-wider">
- [ ORDER DOSSIER // #{order.id} ]
- </h3>
- <button
- onClick={() => copyText('order_id', order.id)}
- className="p-1 hover:bg-white border border-transparent hover:border-black transition"
- title="复制单号"
- >
- {copiedKey === 'order_id' ? <Check size={12} className="text-black" /> : <Copy size={12} />}
- </button>
- </div>
- <button
- onClick={onClose}
- className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
- >
- ✕
- </button>
- </div>
- {/* Action Toolbar */}
- <div className="bg-white px-5 py-2.5 border-b-2 border-black flex flex-wrap items-center justify-between gap-2 shrink-0">
- <div className="flex items-center gap-2 text-xs">
- <span className="font-bold text-neutral-500 uppercase">STATUS:</span>
- <span
- className={`px-2 py-0.5 border border-black text-[10px] font-black uppercase ${
- isPaid
- ? 'bg-amber-300 text-black shadow-[1px_1px_0px_#000]'
- : isPending
- ? 'bg-neutral-100 text-black'
- : isCancelled
- ? 'bg-neutral-200 text-neutral-600'
- : 'bg-rose-100 text-rose-800'
- }`}
- >
- {order.status}
- </span>
- </div>
- <div className="flex items-center gap-1.5">
- {isPending && onAdjustPrice && (
- <button
- onClick={() => onAdjustPrice(order)}
- className="px-2.5 py-1 bg-amber-300 hover:bg-amber-400 text-black border border-black text-xs font-black shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
- >
- [ 调价 ]
- </button>
- )}
- {isPending && onCheckPayments && (
- <button
- onClick={() => onCheckPayments(order)}
- className="px-2.5 py-1 bg-neutral-100 hover:bg-neutral-200 text-black border border-black text-xs font-bold shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
- >
- [ 核销 ]
- </button>
- )}
- {onEdit && (
- <button
- onClick={() => onEdit(order)}
- className="px-2.5 py-1 bg-white hover:bg-neutral-100 text-black border border-black text-xs font-bold shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
- >
- [ 编辑 ]
- </button>
- )}
- {isPending && onCancel && (
- <button
- onClick={() => onCancel(order.id)}
- className="px-2.5 py-1 bg-rose-100 hover:bg-rose-200 text-rose-800 border border-black text-xs font-bold shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
- >
- [ 取消 ]
- </button>
- )}
- </div>
- </div>
- {/* Scrollable Content */}
- <div className="flex-1 overflow-y-auto p-5 space-y-5 bg-neutral-50">
-
- {/* 金额概览卡 */}
- <div className="bg-white border-2 border-black p-4 shadow-[3px_3px_0px_#000] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
- <div>
- <span className="text-[10px] text-neutral-500 uppercase font-bold block">SETTLEMENT AMOUNT</span>
- <div className="text-2xl font-black text-black">
- {formatMoney(finalAmount, currency)}
- </div>
- {isAdjusted && (
- <div className="text-xs text-neutral-500 flex items-center gap-1.5 mt-0.5">
- <span className="line-through">原价: {formatMoney(baseAmount, currency)}</span>
- <span className="bg-amber-100 border border-black px-1 text-[10px] font-bold text-black">
- {delta > 0 ? `+${(delta / 100).toFixed(2)}` : `${(delta / 100).toFixed(2)}`} 调价
- </span>
- </div>
- )}
- </div>
- <div className="text-left sm:text-right border-t sm:border-t-0 sm:border-l-2 border-dashed border-neutral-300 pt-2 sm:pt-0 sm:pl-3 text-xs">
- <span className="text-[10px] text-neutral-500 font-bold block">PRODUCT</span>
- <span className="font-bold text-black font-sans truncate max-w-[200px] block">
- {order.product_title || order.product_name || '默认服务'}
- </span>
- </div>
- </div>
- {/* Section 1: Customer Profile */}
- <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
- <div className="bg-neutral-100 px-4 py-2 border-b-2 border-black flex items-center justify-between text-xs font-black uppercase text-black">
- <div className="flex items-center gap-1.5">
- <User size={14} />
- <span>[ 01 // 客户档案与联系方式 ]</span>
- </div>
- {loadingUser && <Loader2 size={12} className="animate-spin" />}
- </div>
- <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
- <div className="border-b border-dashed border-neutral-300 pb-1.5">
- <span className="text-[10px] text-neutral-500 font-bold uppercase block">申请人姓名</span>
- <span className="font-bold text-black font-sans">{displayNickname}</span>
- </div>
- <div className="border-b border-dashed border-neutral-300 pb-1.5">
- <span className="text-[10px] text-neutral-500 font-bold uppercase block">联系电话</span>
- <span className="font-bold text-black">{displayPhone}</span>
- </div>
- <div className="border-b border-dashed border-neutral-300 pb-1.5 sm:col-span-2">
- <span className="text-[10px] text-neutral-500 font-bold uppercase block">登录账号 / 绑定邮箱</span>
- <div className="flex items-center gap-1.5">
- <span className="font-bold text-black">{displayEmail}</span>
- {displayEmail !== '未关联邮箱' && (
- <button
- onClick={() => copyText('email', displayEmail)}
- className="p-0.5 hover:bg-neutral-200 border border-transparent hover:border-black transition"
- title="复制邮箱"
- >
- {copiedKey === 'email' ? <Check size={11} className="text-black" /> : <Copy size={11} />}
- </button>
- )}
- </div>
- </div>
- </div>
- </div>
- {/* Section 2: Form & Application Parameters */}
- <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
- <div className="bg-neutral-100 px-4 py-2 border-b-2 border-black flex items-center justify-between text-xs font-black uppercase text-black">
- <div className="flex items-center gap-1.5">
- <FileSpreadsheet size={14} />
- <span>[ 02 // 申报资料参数清单 ]</span>
- </div>
- {sortedUserInputs.length > 0 && (
- <button
- onClick={handleCopyAllInputs}
- className="px-2 py-0.5 bg-white hover:bg-amber-300 border border-black text-[10px] font-bold shadow-[1px_1px_0px_#000]"
- >
- {copiedAllInputs ? '✓ 已复制 JSON' : '复制 JSON'}
- </button>
- )}
- </div>
- <div className="p-4">
- {sortedUserInputs.length === 0 ? (
- <div className="text-center py-4 text-neutral-400 text-xs">
- [ 暂无自定义表单输入参数 ]
- </div>
- ) : (
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
- {sortedUserInputs.map(([k, v]) => {
- const valStr = typeof v === 'object' ? JSON.stringify(v) : String(v || '-');
- return (
- <div key={k} className="border-b border-dashed border-neutral-300 pb-1.5">
- <div className="flex items-center justify-between text-[10px] text-neutral-500 font-bold uppercase mb-0.5">
- <span>[{k}]</span>
- <button
- onClick={() => copyText(`field_${k}`, valStr)}
- className="hover:text-black"
- title="复制"
- >
- {copiedKey === `field_${k}` ? <Check size={10} className="text-black" /> : <Copy size={10} />}
- </button>
- </div>
- <span className="font-bold text-black font-sans break-words break-all">
- {valStr}
- </span>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
- {/* Section 3: Payment History */}
- <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
- <div className="bg-neutral-100 px-4 py-2 border-b-2 border-black flex items-center justify-between text-xs font-black uppercase text-black">
- <div className="flex items-center gap-1.5">
- <CreditCard size={14} />
- <span>[ 03 // 支付流水核销明细 ({paymentList.length}) ]</span>
- </div>
- {loadingPayments && <Loader2 size={12} className="animate-spin" />}
- </div>
- <div className="p-4">
- {paymentList.length === 0 ? (
- <div className="text-center py-4 text-neutral-400 text-xs">
- [ 暂无该订单相关的支付流水 ]
- </div>
- ) : (
- <div className="space-y-3">
- {paymentList.map((pay) => {
- const stripeUrl = getStripeLink(pay);
- const isPaySucceeded = ['succeeded', 'paid'].includes((pay.status || '').toLowerCase());
- const qrDesc = pay.qr_id ? qrDetails[pay.qr_id]?.description : undefined;
- return (
- <div
- key={pay.id}
- className="p-3 bg-neutral-50 border border-black shadow-[2px_2px_0px_#000] space-y-1.5 text-xs"
- >
- <div className="flex items-center justify-between">
- <span className="font-black text-black uppercase">
- {pay.provider} // {pay.channel}
- </span>
- <div className="flex items-center gap-1.5">
- <span className="font-bold text-black">
- {formatMoney(pay.amount, pay.currency)}
- </span>
- <span
- className={`px-1.5 py-0.2 text-[10px] font-black uppercase border border-black ${
- isPaySucceeded ? 'bg-amber-300 text-black' : 'bg-neutral-200 text-neutral-600'
- }`}
- >
- {pay.status}
- </span>
- </div>
- </div>
- <div className="text-[11px] text-neutral-500 pt-1 border-t border-dashed border-neutral-300 flex flex-wrap justify-between gap-1">
- <span>ID: #{pay.id}</span>
- <LocalTime date={pay.created_at} />
- {qrDesc && <span className="w-full">QR: {qrDesc}</span>}
- {stripeUrl && (
- <a
- href={stripeUrl}
- target="_blank"
- rel="noreferrer"
- className="text-black hover:underline flex items-center gap-1 font-bold pt-0.5"
- >
- <span>在 Stripe 查看此笔流水</span>
- <ExternalLink size={10} />
- </a>
- )}
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </div>
- {/* Section 4: Timeline */}
- <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
- <div className="bg-neutral-100 px-4 py-2 border-b-2 border-black flex items-center justify-between text-xs font-black uppercase text-black">
- <div className="flex items-center gap-1.5">
- <History size={14} />
- <span>[ 04 // 流转日志与审计事件 ({events.length}) ]</span>
- </div>
- {loadingEvents && <Loader2 size={12} className="animate-spin" />}
- </div>
- <div className="p-4">
- {events.length === 0 ? (
- <div className="text-center py-4 text-neutral-400 text-xs">
- [ 暂无状态变更或流转事件记录 ]
- </div>
- ) : (
- <div className="space-y-3">
- {events.map((evt) => (
- <div key={evt.id} className="p-3 bg-neutral-50 border border-black shadow-[1px_1px_0px_#000] space-y-1 text-xs">
- <div className="flex items-center justify-between text-[11px] text-neutral-500">
- <span className="font-bold text-black font-sans">{evt.event_title || '流转事件'}</span>
- <LocalTime date={evt.event_time || evt.created_at} />
- </div>
- {evt.event_message && (
- <p className="text-neutral-700 font-sans text-xs whitespace-pre-line">
- {evt.event_message}
- </p>
- )}
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
- </div>
- </div>
- </div>
- );
- }
|