OrderDetailDrawer.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. 'use client';
  2. import { useState, useEffect, useMemo } from 'react';
  3. import api from '@/lib/api';
  4. import {
  5. X,
  6. User,
  7. Package,
  8. CreditCard,
  9. History,
  10. Copy,
  11. Check,
  12. ExternalLink,
  13. DollarSign,
  14. Wallet,
  15. Edit,
  16. Clock,
  17. Mail,
  18. Phone,
  19. FileSpreadsheet,
  20. XCircle,
  21. Loader2,
  22. } from 'lucide-react';
  23. import LocalTime from '@/components/common/LocalTime';
  24. import { getPaymentProviderIcon } from '@/components/admin/payments/paymentIcons';
  25. import { OrderDetail, PaymentRecord, PaymentQrDetail, UserDetail, OrderEvent, ExtendedOrderDetail } from '@/types';
  26. interface OrderDetailDrawerProps {
  27. isOpen: boolean;
  28. onClose: () => void;
  29. order: ExtendedOrderDetail | null;
  30. onAdjustPrice?: (order: OrderDetail) => void;
  31. onCheckPayments?: (order: OrderDetail) => void;
  32. onEdit?: (order: OrderDetail) => void;
  33. onCancel?: (orderId: string) => void;
  34. }
  35. const FIELD_DISPLAY_ORDER = [
  36. 'first_name',
  37. 'last_name',
  38. 'name',
  39. 'applicant_name',
  40. 'passport_no',
  41. 'birthday',
  42. 'gender',
  43. 'email',
  44. 'phone_country_code',
  45. 'phone',
  46. 'destination_country',
  47. 'visa_type',
  48. 'departure_date',
  49. 'social_media_account',
  50. ];
  51. export default function OrderDetailDrawer({
  52. isOpen,
  53. onClose,
  54. order,
  55. onAdjustPrice,
  56. onCheckPayments,
  57. onEdit,
  58. onCancel,
  59. }: OrderDetailDrawerProps) {
  60. const [paymentList, setPaymentList] = useState<PaymentRecord[]>([]);
  61. const [loadingPayments, setLoadingPayments] = useState(false);
  62. const [userData, setUserData] = useState<UserDetail | null>(null);
  63. const [loadingUser, setLoadingUser] = useState(false);
  64. const [qrDetails, setQrDetails] = useState<Record<number, PaymentQrDetail>>({});
  65. const [events, setEvents] = useState<OrderEvent[]>([]);
  66. const [loadingEvents, setLoadingEvents] = useState(false);
  67. const [copiedKey, setCopiedKey] = useState<string | null>(null);
  68. const [copiedAllInputs, setCopiedAllInputs] = useState(false);
  69. useEffect(() => {
  70. if (isOpen && order?.id) {
  71. fetchPayments(order.id);
  72. fetchEvents(order.id);
  73. if (order.user_id) {
  74. fetchUserDetails(order.user_id);
  75. } else {
  76. setUserData(null);
  77. }
  78. } else {
  79. setPaymentList([]);
  80. setEvents([]);
  81. setUserData(null);
  82. }
  83. }, [isOpen, order]);
  84. const fetchPayments = async (orderId: string) => {
  85. setLoadingPayments(true);
  86. try {
  87. const res = await api.get('/api/vas/payment/list_by_order', { params: { order_id: orderId } });
  88. const list = Array.isArray(res.data?.data) ? res.data.data : Array.isArray(res.data) ? res.data : [];
  89. setPaymentList(list);
  90. } catch {
  91. setPaymentList([]);
  92. } finally {
  93. setLoadingPayments(false);
  94. }
  95. };
  96. const fetchEvents = async (orderId: string) => {
  97. setLoadingEvents(true);
  98. try {
  99. const res = await api.get('/api/vas/order-event/list', { params: { order_id: orderId } });
  100. const list = Array.isArray(res.data?.data) ? res.data.data : [];
  101. setEvents(list);
  102. } catch {
  103. setEvents([]);
  104. } finally {
  105. setLoadingEvents(false);
  106. }
  107. };
  108. const fetchUserDetails = async (userId: string) => {
  109. setLoadingUser(true);
  110. try {
  111. const res = await api.get('/api/user/get_by_id', { params: { user_id: userId } });
  112. setUserData(res.data?.data || null);
  113. } catch {
  114. setUserData(null);
  115. } finally {
  116. setLoadingUser(false);
  117. }
  118. };
  119. const sortedUserInputs = useMemo(() => {
  120. if (!order?.user_inputs) return [];
  121. return Object.entries(order.user_inputs).sort(([keyA], [keyB]) => {
  122. const indexA = FIELD_DISPLAY_ORDER.indexOf(keyA);
  123. const indexB = FIELD_DISPLAY_ORDER.indexOf(keyB);
  124. if (indexA !== -1 && indexB !== -1) return indexA - indexB;
  125. if (indexA !== -1) return -1;
  126. if (indexB !== -1) return 1;
  127. return 0;
  128. });
  129. }, [order?.user_inputs]);
  130. useEffect(() => {
  131. const qrIds = paymentList.map((p) => p.qr_id).filter(Boolean) as number[];
  132. if (qrIds.length === 0) return;
  133. const fetchDetails = async () => {
  134. const detailMap: Record<number, PaymentQrDetail> = {};
  135. await Promise.all(
  136. Array.from(new Set(qrIds)).map(async (qrId) => {
  137. try {
  138. const res = await api.get('/api/vas/payment-qr/get', { params: { qr_id: qrId } });
  139. if (res.data?.data) {
  140. detailMap[qrId] = res.data.data;
  141. }
  142. } catch {
  143. // ignore
  144. }
  145. })
  146. );
  147. setQrDetails(detailMap);
  148. };
  149. fetchDetails();
  150. }, [paymentList]);
  151. const copyText = (key: string, text: string) => {
  152. navigator.clipboard.writeText(text);
  153. setCopiedKey(key);
  154. setTimeout(() => setCopiedKey(null), 2000);
  155. };
  156. const handleCopyAllInputs = () => {
  157. if (!order?.user_inputs) return;
  158. const formatted = JSON.stringify(order.user_inputs, null, 2);
  159. navigator.clipboard.writeText(formatted);
  160. setCopiedAllInputs(true);
  161. setTimeout(() => setCopiedAllInputs(false), 2000);
  162. };
  163. if (!isOpen || !order) return null;
  164. const currency = order.base_currency || 'CNY';
  165. const baseAmount = order.base_amount || 0;
  166. const finalAmount = order.final_amount !== undefined ? order.final_amount : baseAmount;
  167. const isAdjusted = finalAmount !== baseAmount;
  168. const delta = order.adjustment_delta ?? (finalAmount - baseAmount);
  169. const isPending = (order.status || '').toLowerCase() === 'pending';
  170. const isPaid = ['paid', 'succeeded', 'completed'].includes((order.status || '').toLowerCase());
  171. const isCancelled = (order.status || '').toLowerCase() === 'cancelled';
  172. const formatMoney = (amount: number, curr = currency) => {
  173. const symbol = curr === 'CNY' ? '¥' : curr === 'USD' ? '$' : `${curr} `;
  174. return `${symbol}${(amount / 100).toFixed(2)}`;
  175. };
  176. const formatStripeMode = (id: string) => (id.includes('_live_') ? 'live' : 'test');
  177. const getStripeLink = (pay: PaymentRecord) => {
  178. if (pay.provider.toLowerCase() !== 'stripe') return undefined;
  179. const id = pay.payment_intent_id;
  180. if (!id) return undefined;
  181. const mode = formatStripeMode(id);
  182. const resourcePath = id.startsWith('cs_') ? 'checkout/sessions' : 'payments';
  183. return `https://dashboard.stripe.com/${mode}/${resourcePath}/${id}`;
  184. };
  185. const displayEmail = userData?.email || order.user?.email || order.user_email || '未关联邮箱';
  186. const displayNickname = userData?.nickname || order.user_name || order.user?.nickname || order.applicant_name || '-';
  187. const displayPhone = userData?.phone || order.user?.phone || '-';
  188. return (
  189. <div className="fixed inset-0 z-50 flex justify-end bg-black/60 backdrop-grayscale font-mono">
  190. <div className="absolute inset-0" onClick={onClose} />
  191. {/* Drawer Body */}
  192. <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">
  193. {/* Drawer Header */}
  194. <div className="bg-neutral-200 px-5 py-3.5 border-b-2 border-black shrink-0 flex items-center justify-between select-none">
  195. <div className="flex items-center gap-2">
  196. <span className="w-2.5 h-2.5 bg-amber-300 border border-black inline-block" />
  197. <h3 className="font-black text-black text-xs sm:text-sm uppercase tracking-wider">
  198. [ ORDER DOSSIER // #{order.id} ]
  199. </h3>
  200. <button
  201. onClick={() => copyText('order_id', order.id)}
  202. className="p-1 hover:bg-white border border-transparent hover:border-black transition"
  203. title="复制单号"
  204. >
  205. {copiedKey === 'order_id' ? <Check size={12} className="text-black" /> : <Copy size={12} />}
  206. </button>
  207. </div>
  208. <button
  209. onClick={onClose}
  210. className="w-6 h-6 bg-white hover:bg-amber-300 border border-black flex items-center justify-center font-bold text-xs transition"
  211. >
  212. ✕
  213. </button>
  214. </div>
  215. {/* Action Toolbar */}
  216. <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">
  217. <div className="flex items-center gap-2 text-xs">
  218. <span className="font-bold text-neutral-500 uppercase">STATUS:</span>
  219. <span
  220. className={`px-2 py-0.5 border border-black text-[10px] font-black uppercase ${
  221. isPaid
  222. ? 'bg-amber-300 text-black shadow-[1px_1px_0px_#000]'
  223. : isPending
  224. ? 'bg-neutral-100 text-black'
  225. : isCancelled
  226. ? 'bg-neutral-200 text-neutral-600'
  227. : 'bg-rose-100 text-rose-800'
  228. }`}
  229. >
  230. {order.status}
  231. </span>
  232. </div>
  233. <div className="flex items-center gap-1.5">
  234. {isPending && onAdjustPrice && (
  235. <button
  236. onClick={() => onAdjustPrice(order)}
  237. 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"
  238. >
  239. [ 调价 ]
  240. </button>
  241. )}
  242. {isPending && onCheckPayments && (
  243. <button
  244. onClick={() => onCheckPayments(order)}
  245. 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"
  246. >
  247. [ 核销 ]
  248. </button>
  249. )}
  250. {onEdit && (
  251. <button
  252. onClick={() => onEdit(order)}
  253. 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"
  254. >
  255. [ 编辑 ]
  256. </button>
  257. )}
  258. {isPending && onCancel && (
  259. <button
  260. onClick={() => onCancel(order.id)}
  261. 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"
  262. >
  263. [ 取消 ]
  264. </button>
  265. )}
  266. </div>
  267. </div>
  268. {/* Scrollable Content */}
  269. <div className="flex-1 overflow-y-auto p-5 space-y-5 bg-neutral-50">
  270. {/* 金额概览卡 */}
  271. <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">
  272. <div>
  273. <span className="text-[10px] text-neutral-500 uppercase font-bold block">SETTLEMENT AMOUNT</span>
  274. <div className="text-2xl font-black text-black">
  275. {formatMoney(finalAmount, currency)}
  276. </div>
  277. {isAdjusted && (
  278. <div className="text-xs text-neutral-500 flex items-center gap-1.5 mt-0.5">
  279. <span className="line-through">原价: {formatMoney(baseAmount, currency)}</span>
  280. <span className="bg-amber-100 border border-black px-1 text-[10px] font-bold text-black">
  281. {delta > 0 ? `+${(delta / 100).toFixed(2)}` : `${(delta / 100).toFixed(2)}`} 调价
  282. </span>
  283. </div>
  284. )}
  285. </div>
  286. <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">
  287. <span className="text-[10px] text-neutral-500 font-bold block">PRODUCT</span>
  288. <span className="font-bold text-black font-sans truncate max-w-[200px] block">
  289. {order.product_title || order.product_name || '默认服务'}
  290. </span>
  291. </div>
  292. </div>
  293. {/* Section 1: Customer Profile */}
  294. <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
  295. <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">
  296. <div className="flex items-center gap-1.5">
  297. <User size={14} />
  298. <span>[ 01 // 客户档案与联系方式 ]</span>
  299. </div>
  300. {loadingUser && <Loader2 size={12} className="animate-spin" />}
  301. </div>
  302. <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
  303. <div className="border-b border-dashed border-neutral-300 pb-1.5">
  304. <span className="text-[10px] text-neutral-500 font-bold uppercase block">申请人姓名</span>
  305. <span className="font-bold text-black font-sans">{displayNickname}</span>
  306. </div>
  307. <div className="border-b border-dashed border-neutral-300 pb-1.5">
  308. <span className="text-[10px] text-neutral-500 font-bold uppercase block">联系电话</span>
  309. <span className="font-bold text-black">{displayPhone}</span>
  310. </div>
  311. <div className="border-b border-dashed border-neutral-300 pb-1.5 sm:col-span-2">
  312. <span className="text-[10px] text-neutral-500 font-bold uppercase block">登录账号 / 绑定邮箱</span>
  313. <div className="flex items-center gap-1.5">
  314. <span className="font-bold text-black">{displayEmail}</span>
  315. {displayEmail !== '未关联邮箱' && (
  316. <button
  317. onClick={() => copyText('email', displayEmail)}
  318. className="p-0.5 hover:bg-neutral-200 border border-transparent hover:border-black transition"
  319. title="复制邮箱"
  320. >
  321. {copiedKey === 'email' ? <Check size={11} className="text-black" /> : <Copy size={11} />}
  322. </button>
  323. )}
  324. </div>
  325. </div>
  326. </div>
  327. </div>
  328. {/* Section 2: Form & Application Parameters */}
  329. <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
  330. <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">
  331. <div className="flex items-center gap-1.5">
  332. <FileSpreadsheet size={14} />
  333. <span>[ 02 // 申报资料参数清单 ]</span>
  334. </div>
  335. {sortedUserInputs.length > 0 && (
  336. <button
  337. onClick={handleCopyAllInputs}
  338. className="px-2 py-0.5 bg-white hover:bg-amber-300 border border-black text-[10px] font-bold shadow-[1px_1px_0px_#000]"
  339. >
  340. {copiedAllInputs ? '✓ 已复制 JSON' : '复制 JSON'}
  341. </button>
  342. )}
  343. </div>
  344. <div className="p-4">
  345. {sortedUserInputs.length === 0 ? (
  346. <div className="text-center py-4 text-neutral-400 text-xs">
  347. [ 暂无自定义表单输入参数 ]
  348. </div>
  349. ) : (
  350. <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
  351. {sortedUserInputs.map(([k, v]) => {
  352. const valStr = typeof v === 'object' ? JSON.stringify(v) : String(v || '-');
  353. return (
  354. <div key={k} className="border-b border-dashed border-neutral-300 pb-1.5">
  355. <div className="flex items-center justify-between text-[10px] text-neutral-500 font-bold uppercase mb-0.5">
  356. <span>[{k}]</span>
  357. <button
  358. onClick={() => copyText(`field_${k}`, valStr)}
  359. className="hover:text-black"
  360. title="复制"
  361. >
  362. {copiedKey === `field_${k}` ? <Check size={10} className="text-black" /> : <Copy size={10} />}
  363. </button>
  364. </div>
  365. <span className="font-bold text-black font-sans break-words break-all">
  366. {valStr}
  367. </span>
  368. </div>
  369. );
  370. })}
  371. </div>
  372. )}
  373. </div>
  374. </div>
  375. {/* Section 3: Payment History */}
  376. <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
  377. <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">
  378. <div className="flex items-center gap-1.5">
  379. <CreditCard size={14} />
  380. <span>[ 03 // 支付流水核销明细 ({paymentList.length}) ]</span>
  381. </div>
  382. {loadingPayments && <Loader2 size={12} className="animate-spin" />}
  383. </div>
  384. <div className="p-4">
  385. {paymentList.length === 0 ? (
  386. <div className="text-center py-4 text-neutral-400 text-xs">
  387. [ 暂无该订单相关的支付流水 ]
  388. </div>
  389. ) : (
  390. <div className="space-y-3">
  391. {paymentList.map((pay) => {
  392. const stripeUrl = getStripeLink(pay);
  393. const isPaySucceeded = ['succeeded', 'paid'].includes((pay.status || '').toLowerCase());
  394. const qrDesc = pay.qr_id ? qrDetails[pay.qr_id]?.description : undefined;
  395. return (
  396. <div
  397. key={pay.id}
  398. className="p-3 bg-neutral-50 border border-black shadow-[2px_2px_0px_#000] space-y-1.5 text-xs"
  399. >
  400. <div className="flex items-center justify-between">
  401. <span className="font-black text-black uppercase">
  402. {pay.provider} // {pay.channel}
  403. </span>
  404. <div className="flex items-center gap-1.5">
  405. <span className="font-bold text-black">
  406. {formatMoney(pay.amount, pay.currency)}
  407. </span>
  408. <span
  409. className={`px-1.5 py-0.2 text-[10px] font-black uppercase border border-black ${
  410. isPaySucceeded ? 'bg-amber-300 text-black' : 'bg-neutral-200 text-neutral-600'
  411. }`}
  412. >
  413. {pay.status}
  414. </span>
  415. </div>
  416. </div>
  417. <div className="text-[11px] text-neutral-500 pt-1 border-t border-dashed border-neutral-300 flex flex-wrap justify-between gap-1">
  418. <span>ID: #{pay.id}</span>
  419. <LocalTime date={pay.created_at} />
  420. {qrDesc && <span className="w-full">QR: {qrDesc}</span>}
  421. {stripeUrl && (
  422. <a
  423. href={stripeUrl}
  424. target="_blank"
  425. rel="noreferrer"
  426. className="text-black hover:underline flex items-center gap-1 font-bold pt-0.5"
  427. >
  428. <span>在 Stripe 查看此笔流水</span>
  429. <ExternalLink size={10} />
  430. </a>
  431. )}
  432. </div>
  433. </div>
  434. );
  435. })}
  436. </div>
  437. )}
  438. </div>
  439. </div>
  440. {/* Section 4: Timeline */}
  441. <div className="bg-white border-2 border-black shadow-[3px_3px_0px_#000]">
  442. <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">
  443. <div className="flex items-center gap-1.5">
  444. <History size={14} />
  445. <span>[ 04 // 流转日志与审计事件 ({events.length}) ]</span>
  446. </div>
  447. {loadingEvents && <Loader2 size={12} className="animate-spin" />}
  448. </div>
  449. <div className="p-4">
  450. {events.length === 0 ? (
  451. <div className="text-center py-4 text-neutral-400 text-xs">
  452. [ 暂无状态变更或流转事件记录 ]
  453. </div>
  454. ) : (
  455. <div className="space-y-3">
  456. {events.map((evt) => (
  457. <div key={evt.id} className="p-3 bg-neutral-50 border border-black shadow-[1px_1px_0px_#000] space-y-1 text-xs">
  458. <div className="flex items-center justify-between text-[11px] text-neutral-500">
  459. <span className="font-bold text-black font-sans">{evt.event_title || '流转事件'}</span>
  460. <LocalTime date={evt.event_time || evt.created_at} />
  461. </div>
  462. {evt.event_message && (
  463. <p className="text-neutral-700 font-sans text-xs whitespace-pre-line">
  464. {evt.event_message}
  465. </p>
  466. )}
  467. </div>
  468. ))}
  469. </div>
  470. )}
  471. </div>
  472. </div>
  473. </div>
  474. </div>
  475. </div>
  476. );
  477. }