Lumen & Gesso / website · lumengesso.com / app / lib / order-customer.ts
| 1 | import 'server-only'; |
| 2 | import { stripe } from './stripe'; |
| 3 | import { customerDetailsById } from './lumen-auth'; |
| 4 | |
| 5 | type OrderIdentity = { |
| 6 | id: string; |
| 7 | user_id: string; |
| 8 | user_email: string; |
| 9 | stripe_session_id?: string | null; |
| 10 | }; |
| 11 | |
| 12 | function nameText(value: unknown): string { |
| 13 | if (typeof value !== 'string') return ''; |
| 14 | const name = value.trim().replace(/\s+/g, ' '); |
| 15 | return name.length <= 120 && /^\p{L}[\p{L}\p{M}'’. -]*$/u.test(name) ? name : ''; |
| 16 | } |
| 17 | |
| 18 | export async function getOrderCustomer( |
| 19 | order: OrderIdentity, |
| 20 | includePhone = false, |
| 21 | ) { |
| 22 | const profile = await customerDetailsById(order.user_id).catch(() => null); |
| 23 | const profileName = nameText(profile?.name); |
| 24 | let checkoutName = ''; |
| 25 | let checkoutPhone = ''; |
| 26 | |
| 27 | if (order.stripe_session_id && (!profileName || includePhone)) { |
| 28 | // Checkout identifies the purchaser. A shipping recipient may be someone else. |
| 29 | try { |
| 30 | const session = await stripe().checkout.sessions.retrieve(order.stripe_session_id, {}, { timeout: 2500, maxNetworkRetries: 0 }); |
| 31 | if (session.metadata?.orderId === order.id |
| 32 | && session.customer_details?.email?.toLowerCase() === order.user_email.toLowerCase()) { |
| 33 | checkoutName = nameText(session.customer_details.name); |
| 34 | checkoutPhone = session.customer_details.phone?.trim() || ''; |
| 35 | } |
| 36 | } catch { |
| 37 | // Profile information and the stored order stay available if Stripe is unavailable. |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | const name = profileName || checkoutName; |
| 42 | return { |
| 43 | name, |
| 44 | firstName: name.split(' ')[0], |
| 45 | phone: checkoutPhone, |
| 46 | }; |
| 47 | } |