import 'server-only'; import { stripe } from './stripe'; import { customerDetailsById } from './lumen-auth'; type OrderIdentity = { id: string; user_id: string; user_email: string; stripe_session_id?: string | null; }; function nameText(value: unknown): string { if (typeof value !== 'string') return ''; const name = value.trim().replace(/\s+/g, ' '); return name.length <= 120 && /^\p{L}[\p{L}\p{M}'’. -]*$/u.test(name) ? name : ''; } export async function getOrderCustomer( order: OrderIdentity, includePhone = false, ) { const profile = await customerDetailsById(order.user_id).catch(() => null); const profileName = nameText(profile?.name); let checkoutName = ''; let checkoutPhone = ''; if (order.stripe_session_id && (!profileName || includePhone)) { // Checkout identifies the purchaser. A shipping recipient may be someone else. try { const session = await stripe().checkout.sessions.retrieve(order.stripe_session_id, {}, { timeout: 2500, maxNetworkRetries: 0 }); if (session.metadata?.orderId === order.id && session.customer_details?.email?.toLowerCase() === order.user_email.toLowerCase()) { checkoutName = nameText(session.customer_details.name); checkoutPhone = session.customer_details.phone?.trim() || ''; } } catch { // Profile information and the stored order stay available if Stripe is unavailable. } } const name = profileName || checkoutName; return { name, firstName: name.split(' ')[0], phone: checkoutPhone, }; }